turndb 0.2.0

A content-addressed columnar store for AI traces: byte-exact, embedded, and readable by the CLI and npm from the same file.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
//! The store: WAL, pending change set, publication, manifest revisions, and WAL replay — the layer
//! that turns a fold and parts into a database.
//!
//! # Substrate
//!
//! A store is one container file plus a transient WAL sidecar while a writer has pending changes.
//! There is no daemon in this design; a server is a *role* a process takes when it holds the writer
//! lock, not a thing the format depends on. (That lock is enforced by the OS on native Unix and
//! Windows and **not enforced on `wasm32-wasip1`** — there the single-writer invariant is the
//! embedder's to maintain, since there is no advisory lock to hold. See `src/sys.rs` and FORMAT.md.)
//!
//! [`open_read_container`] takes no lock, replays nothing, and is safe to run
//! concurrently with a writer — parts are immutable and ordinary fold writes append without moving
//! existing locations, so a reader pinned to a store authority sees a consistent store with no
//! coordination at all. Declared content punch is the explicit operation that can end an older
//! view's readability.
//!
//! # Publication authority
//!
//! The container superblock flip is the only publication point. Its directory selects one manifest
//! revision (or the canonical origin), which names the referenced parts, fold tail, and WAL sequence
//! cursor. Everything else — block indexes, dedup indexes, and part contents — is subordinate evidence.
//!
//! # Ordering and WAL replay
//!
//! ```text
//! acceptance      -> fold.put (no fsync) + WAL append
//! synchronization -> acknowledge selected container authority if needed -> WAL fsync
//! publication     -> fold.sync -> write part -> stage manifest revision -> flip container state
//! settlement      -> truncate WAL replay input
//! ```
//! Writer open resolves the current store authority without truncating committed container members,
//! then WAL replay reconstructs the pending change set from complete valid input. Each frame carries
//! the bytes of every piece that was new, so replay never depends on unpublished fold bytes.

pub mod debris;
pub mod read;
pub mod refold;
pub mod wal;

pub use debris::{debris_report, debris_report_with_limits, DebrisEntry, DebrisKind, DebrisReport};

use crate::fold::{Fold, FoldCfg, FoldTail, Loc};
use crate::part::cache::SectionCache;
use crate::part::{self, Part};
use crate::read_limits::ReadLimits;
use crate::types::{AttrValue, Content, ContentHash, ContentOp, PieceHash, Record, BODY_CONTENT};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use wal::Wal;

/// Per-writer admission policy. These limits are runtime policy, not store format: reopening with
/// different values changes which future writes are accepted and never changes or invalidates
/// records already in the WAL or immutable parts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WriteLimits {
    /// Worst-case complete WAL frame bytes for one put or delete.
    pub max_record_bytes: u64,
    /// Sum of member frames plus the commit-marker frame for one atomic batch.
    pub max_batch_bytes: u64,
    /// Number of ordered put/delete members in one atomic batch.
    pub max_batch_records: usize,
    /// UTF-8 bytes in a record id, attribute name, or content name.
    pub max_identifier_bytes: usize,
}

/// Default worst-case framed-WAL ceiling for one record: 64 MiB.
pub const DEFAULT_MAX_RECORD_BYTES: u64 = 64 << 20;
/// Default worst-case framed-WAL ceiling for one atomic batch: 256 MiB.
pub const DEFAULT_MAX_BATCH_BYTES: u64 = 256 << 20;
/// Default ordered member ceiling for one atomic batch.
pub const DEFAULT_MAX_BATCH_RECORDS: usize = 4_096;
/// Default UTF-8 byte ceiling for ids and field/content names: 4 KiB.
pub const DEFAULT_MAX_IDENTIFIER_BYTES: usize = 4 << 10;
/// Maximum committed-manifest bytes accepted from a container under the default format reader.
/// A maintained store's manifest is orders of magnitude smaller; this prevents an untrusted sparse
/// file from becoming an unbounded `read_to_end` allocation before JSON parsing can refuse it.
pub const MAX_MANIFEST_BYTES: u64 = 64 << 20;

impl Default for WriteLimits {
    fn default() -> Self {
        WriteLimits {
            max_record_bytes: DEFAULT_MAX_RECORD_BYTES,
            max_batch_bytes: DEFAULT_MAX_BATCH_BYTES,
            max_batch_records: DEFAULT_MAX_BATCH_RECORDS,
            max_identifier_bytes: DEFAULT_MAX_IDENTIFIER_BYTES,
        }
    }
}

/// How much of the store a writer open verifies before it accepts a mutation.
///
/// Writer open always proves the current store authority intelligible before any cleanup or
/// mutation: the container directory and its checksum, the current manifest revision, every
/// retained revision's canonical name, parse, adjacency, `prev` link, cursor and tail order, the
/// presence of every part any of them names, every current part's schema, every fold segment's
/// framing, and the identity of every WAL frame that replay will apply. That work is proportional
/// to metadata, fold framing, and WAL size, never to content. Deep verification is the same
/// evidence [`Store::verify`] produces, obtained before the first mutation instead of on request:
/// every part pin, section, and physical row, every piece-dictionary entry against the fold, and
/// every visible content value reconstructed, for the current revision and each retained one. Its
/// cost is proportional to the whole store multiplied by the retained window, which is why it is
/// not the default for a database open.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OpenVerification {
    /// Structural evidence only, proportional to metadata and framing.
    #[default]
    Structural,
    /// Everything [`Store::verify`] checks, before the writer accepts a mutation.
    Deep,
}

/// Runtime writer configuration. None of these values are persisted format commitments.
#[derive(Clone, Copy, Debug)]
pub struct StoreOptions {
    pub fold: FoldCfg,
    pub write_limits: WriteLimits,
    /// Admission applied before atomic frame allocation and persistent collection growth.
    pub read_limits: ReadLimits,
    /// One decompressed-section cache budget shared by every immutable part in this handle.
    pub part_cache_bytes: usize,
    /// Verification performed by writer open before the first mutation.
    pub open_verification: OpenVerification,
}

impl Default for StoreOptions {
    fn default() -> Self {
        StoreOptions {
            fold: FoldCfg::default(),
            write_limits: WriteLimits::default(),
            read_limits: ReadLimits::default(),
            part_cache_bytes: crate::part::cache::BUDGET_DEFAULT,
            open_verification: OpenVerification::Structural,
        }
    }
}

impl WriteLimits {
    /// Return this policy when every ceiling is usable, or a typed invalid-policy error.
    pub fn validate(self) -> std::result::Result<Self, WriteAdmissionError> {
        if self.max_record_bytes == 0 {
            return Err(WriteAdmissionError::InvalidLimits(
                "max_record_bytes must be greater than zero",
            ));
        }
        if self.max_batch_bytes == 0 {
            return Err(WriteAdmissionError::InvalidLimits(
                "max_batch_bytes must be greater than zero",
            ));
        }
        if self.max_batch_records == 0 {
            return Err(WriteAdmissionError::InvalidLimits(
                "max_batch_records must be greater than zero",
            ));
        }
        if self.max_identifier_bytes == 0 {
            return Err(WriteAdmissionError::InvalidLimits(
                "max_identifier_bytes must be greater than zero",
            ));
        }
        Ok(self)
    }
}

/// Stable write refusal classes. Invalid names/settings are caller errors; size/count refusals are
/// resource exhaustion and can be handled by splitting input or reopening with a larger policy.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WriteAdmissionError {
    InvalidLimits(&'static str),
    EmptyIdentifier { kind: &'static str, item: Option<usize> },
    IdentifierTooLong { kind: &'static str, item: Option<usize>, actual: usize, allowed: usize },
    DuplicateContentName { item: Option<usize>, name: String },
    RecordTooLarge { item: Option<usize>, actual: u64, allowed: u64 },
    BatchTooLarge { actual: u64, allowed: u64 },
    TooManyBatchRecords { actual: usize, allowed: usize },
}

impl std::fmt::Display for WriteAdmissionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let where_ = |item: &Option<usize>| {
            item.map_or_else(String::new, |item| format!(" in batch item {item}"))
        };
        match self {
            WriteAdmissionError::InvalidLimits(reason) => write!(f, "invalid write limits: {reason}"),
            WriteAdmissionError::EmptyIdentifier { kind, item } => {
                write!(f, "{kind}{} must not be empty", where_(item))
            }
            WriteAdmissionError::IdentifierTooLong { kind, item, actual, allowed } => write!(
                f,
                "{kind}{} is {actual} UTF-8 bytes, exceeding the configured limit of {allowed}",
                where_(item)
            ),
            WriteAdmissionError::DuplicateContentName { item, name } => {
                write!(f, "duplicate content name {name:?}{}", where_(item))
            }
            WriteAdmissionError::RecordTooLarge { item, actual, allowed } => write!(
                f,
                "record{} has a worst-case WAL frame of {actual} bytes, exceeding the configured limit of {allowed}",
                where_(item)
            ),
            WriteAdmissionError::BatchTooLarge { actual, allowed } => write!(
                f,
                "atomic batch has a worst-case WAL representation of {actual} bytes, exceeding the configured limit of {allowed}"
            ),
            WriteAdmissionError::TooManyBatchRecords { actual, allowed } => write!(
                f,
                "atomic batch has {actual} records, exceeding the configured limit of {allowed}"
            ),
        }
    }
}

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

/// A carved span handed to the store: content to fold, or bytes to inline.
#[derive(Clone, Copy)]
pub enum Span<'a> {
    /// Connective tissue too small to be worth folding.
    Lit(&'a [u8]),
    /// Content — deduped by identity across the whole store.
    Piece(&'a [u8]),
}

/// One named content value handed to [`Store::put_record`] or [`Batch::put_record`].
///
/// The spans are already carved, preserving the existing escape hatch: a consumer can accept the
/// engine's default opinion, choose a [`crate::carve::Carve`] per value, or supply its own boundaries.
pub struct ContentSpans<'a> {
    pub name: &'a str,
    pub spans: Vec<Span<'a>>,
}

impl<'a> ContentSpans<'a> {
    pub fn new(name: &'a str, spans: Vec<Span<'a>>) -> ContentSpans<'a> {
        ContentSpans { name, spans }
    }

    pub fn carve(name: &'a str, bytes: &'a [u8], carve: &crate::carve::Carve) -> ContentSpans<'a> {
        ContentSpans { name, spans: carve.carve(bytes) }
    }
}

/// A group of writes that commits ATOMICALLY: after a crash, either every member replays or none
/// does. A lone `put` is durable per record, which means a crash can land between the records of
/// one logical ingest — half an export survived is an anomaly the source then has to reconcile.
/// A batch is the unit the source actually sent.
///
/// A `Batch` is pure staging: it owns copies of its spans and touches neither the fold nor the log
/// until [`Store::apply`], so a batch that is dropped instead of applied leaves NOTHING behind —
/// no fold content, no dedup-window entries, no frames.
#[derive(Default)]
pub struct Batch {
    items: Vec<BatchItem>,
}

enum BatchItem {
    Put { id: String, contents: Vec<OwnedContent>, attrs: Vec<(String, AttrValue)> },
    Delete { id: String },
}

struct OwnedContent {
    name: String,
    spans: Vec<OwnedSpan>,
}

enum OwnedSpan {
    Lit(Vec<u8>),
    Piece(Vec<u8>),
}

impl Batch {
    pub fn new() -> Batch {
        Batch::default()
    }

    /// Stage a put. Same shape as [`Store::put`]; nothing happens until [`Store::apply`].
    pub fn put(&mut self, id: &str, spans: &[Span], attrs: Vec<(String, AttrValue)>) {
        let spans = own_spans(spans);
        self.items.push(BatchItem::Put {
            id: id.to_string(),
            contents: vec![OwnedContent { name: BODY_CONTENT.to_string(), spans }],
            attrs,
        });
    }

    /// Stage a general record. Invalid ids or content maps are refused before the batch owns bytes.
    pub fn put_record(
        &mut self,
        id: &str,
        contents: &[ContentSpans<'_>],
        attrs: Vec<(String, AttrValue)>,
    ) -> Result<()> {
        let item = Some(self.items.len());
        validate_content_inputs(id, contents, item)?;
        if attrs.iter().any(|(name, _)| name.is_empty()) {
            return Err(
                WriteAdmissionError::EmptyIdentifier { kind: "attribute name", item }.into()
            );
        }
        let contents = contents
            .iter()
            .map(|content| OwnedContent {
                name: content.name.to_string(),
                spans: own_spans(&content.spans),
            })
            .collect();
        self.items.push(BatchItem::Put { id: id.to_string(), contents, attrs });
        Ok(())
    }

    /// Stage a put carved by the engine's default opinion. See [`crate::carve`].
    pub fn put_body(&mut self, id: &str, body: &[u8], attrs: Vec<(String, AttrValue)>) {
        self.put(id, &crate::carve::Carve::default().carve(body), attrs);
    }

    /// Stage a deletion.
    pub fn delete(&mut self, id: &str) {
        self.items.push(BatchItem::Delete { id: id.to_string() });
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

fn own_spans(spans: &[Span<'_>]) -> Vec<OwnedSpan> {
    spans
        .iter()
        .map(|s| match s {
            Span::Lit(b) => OwnedSpan::Lit(b.to_vec()),
            Span::Piece(b) => OwnedSpan::Piece(b.to_vec()),
        })
        .collect()
}

const WAL_FRAME_OVERHEAD: u64 = 1 + 8 + 4 + 4;

fn varint_bytes(mut value: u64) -> u64 {
    let mut bytes = 1;
    while value >= 0x80 {
        value >>= 7;
        bytes += 1;
    }
    bytes
}

fn add_size(total: &mut u64, value: u64) {
    *total = total.saturating_add(value);
}

fn bytes_field_size(len: usize) -> u64 {
    let len = len as u64;
    varint_bytes(len).saturating_add(len)
}

fn attr_encoded_size(name: &str, value: &AttrValue) -> u64 {
    let value = match value {
        AttrValue::Str(value) => bytes_field_size(value.len()),
        AttrValue::Int(_)
        | AttrValue::Float(_)
        | AttrValue::UInt(_)
        | AttrValue::TimestampNs(_) => 8,
        AttrValue::Bool(_) => 1,
        AttrValue::Bytes(value) => bytes_field_size(value.len()),
        AttrValue::Null => 0,
    };
    bytes_field_size(name.len()).saturating_add(1).saturating_add(value)
}

fn validate_identifier(
    kind: &'static str,
    value: &str,
    limits: WriteLimits,
    item: Option<usize>,
) -> Result<()> {
    if value.is_empty() {
        return Err(WriteAdmissionError::EmptyIdentifier { kind, item }.into());
    }
    if value.len() > limits.max_identifier_bytes {
        return Err(WriteAdmissionError::IdentifierTooLong {
            kind,
            item,
            actual: value.len(),
            allowed: limits.max_identifier_bytes,
        }
        .into());
    }
    Ok(())
}

fn validate_attr_names(
    attrs: &[(String, AttrValue)],
    limits: WriteLimits,
    item: Option<usize>,
) -> Result<()> {
    for (name, _) in attrs {
        validate_identifier("attribute name", name, limits, item)?;
    }
    Ok(())
}

fn input_record_admission_bytes(
    id: &str,
    contents: &[ContentSpans<'_>],
    attrs: &[(String, AttrValue)],
    limits: WriteLimits,
    read_limits: ReadLimits,
    item: Option<usize>,
) -> Result<u64> {
    validate_identifier("record id", id, limits, item)?;
    validate_attr_names(attrs, limits, item)?;
    let mut names = std::collections::BTreeSet::new();
    let mut size = WAL_FRAME_OVERHEAD;
    add_size(&mut size, bytes_field_size(id.len()));
    add_size(&mut size, varint_bytes(contents.len() as u64));
    for content in contents {
        validate_identifier("content name", content.name, limits, item)?;
        if !names.insert(content.name) {
            return Err(WriteAdmissionError::DuplicateContentName {
                item,
                name: content.name.to_string(),
            }
            .into());
        }
        validate_spans(&content.spans)?;
        add_size(&mut size, bytes_field_size(content.name.len()));
        add_size(&mut size, 32);
        add_size(&mut size, varint_bytes(content.spans.len() as u64));
        let mut novel = 0u64;
        for span in &content.spans {
            match span {
                Span::Lit(bytes) => {
                    add_size(&mut size, 1u64.saturating_add(bytes_field_size(bytes.len())))
                }
                Span::Piece(bytes) => {
                    if bytes.is_empty() {
                        add_size(&mut size, 1u64.saturating_add(bytes_field_size(0)));
                    } else {
                        read_limits.admit(
                            "new fold block",
                            bytes.len() as u64,
                            bytes.len() as u64,
                        )?;
                        add_size(
                            &mut size,
                            1u64.saturating_add(32)
                                .saturating_add(varint_bytes(bytes.len() as u64)),
                        );
                        add_size(&mut novel, 32u64.saturating_add(bytes_field_size(bytes.len())));
                    }
                }
            }
        }
        // Novel pieces are one record-level list; accumulating the entries here is equivalent.
        add_size(&mut size, novel);
    }
    add_size(&mut size, varint_bytes(attrs.len() as u64));
    for (name, value) in attrs {
        add_size(&mut size, attr_encoded_size(name, value));
    }
    let piece_count = contents
        .iter()
        .flat_map(|content| content.spans.iter())
        .filter(|span| matches!(span, Span::Piece(bytes) if !bytes.is_empty()))
        .count() as u64;
    add_size(&mut size, varint_bytes(piece_count));
    if size > limits.max_record_bytes {
        return Err(WriteAdmissionError::RecordTooLarge {
            item,
            actual: size,
            allowed: limits.max_record_bytes,
        }
        .into());
    }
    read_limits.admit("new WAL frame", size, size)?;
    Ok(size)
}

fn validate_content_inputs(
    id: &str,
    contents: &[ContentSpans<'_>],
    item: Option<usize>,
) -> Result<()> {
    if id.is_empty() {
        return Err(WriteAdmissionError::EmptyIdentifier { kind: "record id", item }.into());
    }
    let mut names = std::collections::BTreeSet::new();
    for content in contents {
        if content.name.is_empty() {
            return Err(WriteAdmissionError::EmptyIdentifier { kind: "content name", item }.into());
        }
        if !names.insert(content.name) {
            return Err(WriteAdmissionError::DuplicateContentName {
                item,
                name: content.name.to_string(),
            }
            .into());
        }
        validate_spans(&content.spans)?;
    }
    Ok(())
}

fn validate_spans(spans: &[Span<'_>]) -> Result<()> {
    for span in spans {
        if let Span::Piece(bytes) = span {
            u32::try_from(bytes.len())
                .context("one folded piece exceeds the format's u32 length")?;
        }
    }
    Ok(())
}

fn owned_record_admission_bytes(
    id: &str,
    contents: &[OwnedContent],
    attrs: &[(String, AttrValue)],
    limits: WriteLimits,
    read_limits: ReadLimits,
    item: Option<usize>,
) -> Result<u64> {
    validate_identifier("record id", id, limits, item)?;
    validate_attr_names(attrs, limits, item)?;
    let mut names = std::collections::BTreeSet::new();
    let mut size = WAL_FRAME_OVERHEAD;
    add_size(&mut size, bytes_field_size(id.len()));
    add_size(&mut size, varint_bytes(contents.len() as u64));
    let mut piece_count = 0u64;
    let mut novel = 0u64;
    for content in contents {
        validate_identifier("content name", &content.name, limits, item)?;
        if !names.insert(content.name.as_str()) {
            return Err(WriteAdmissionError::DuplicateContentName {
                item,
                name: content.name.clone(),
            }
            .into());
        }
        add_size(&mut size, bytes_field_size(content.name.len()));
        add_size(&mut size, 1 + 32);
        add_size(&mut size, varint_bytes(content.spans.len() as u64));
        for span in &content.spans {
            match span {
                OwnedSpan::Lit(bytes) => {
                    add_size(&mut size, 1u64.saturating_add(bytes_field_size(bytes.len())))
                }
                OwnedSpan::Piece(bytes) => {
                    if bytes.is_empty() {
                        add_size(&mut size, 1u64.saturating_add(bytes_field_size(0)));
                    } else {
                        read_limits.admit(
                            "new fold block",
                            bytes.len() as u64,
                            bytes.len() as u64,
                        )?;
                        u32::try_from(bytes.len())
                            .context("one folded piece exceeds the format's u32 length")?;
                        piece_count = piece_count.saturating_add(1);
                        add_size(
                            &mut size,
                            1u64.saturating_add(32)
                                .saturating_add(varint_bytes(bytes.len() as u64)),
                        );
                        add_size(&mut novel, 32u64.saturating_add(bytes_field_size(bytes.len())));
                    }
                }
            }
        }
    }
    add_size(&mut size, varint_bytes(attrs.len() as u64));
    for (name, value) in attrs {
        add_size(&mut size, attr_encoded_size(name, value));
    }
    add_size(&mut size, varint_bytes(piece_count));
    add_size(&mut size, novel);
    if size > limits.max_record_bytes {
        return Err(WriteAdmissionError::RecordTooLarge {
            item,
            actual: size,
            allowed: limits.max_record_bytes,
        }
        .into());
    }
    read_limits.admit("new WAL frame", size, size)?;
    Ok(size)
}

fn delete_admission_bytes(
    id: &str,
    limits: WriteLimits,
    read_limits: ReadLimits,
    item: Option<usize>,
) -> Result<u64> {
    validate_identifier("record id", id, limits, item)?;
    let size = WAL_FRAME_OVERHEAD.saturating_add(id.len() as u64);
    if size > limits.max_record_bytes {
        return Err(WriteAdmissionError::RecordTooLarge {
            item,
            actual: size,
            allowed: limits.max_record_bytes,
        }
        .into());
    }
    read_limits.admit("new WAL frame", size, size)?;
    Ok(size)
}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct PartRef {
    pub member: String,
    pub seq_lo: u64,
    pub seq_hi: u64,
    pub records: u32,
    /// BLAKE3 of the part member's logical bytes, hex — the manifest PINNING the part. Content is pinned
    /// transitively from here: this digest covers `pdict.hash`, which carries per-piece BLAKE3,
    /// so a fold that drifted from what a part expects is detectable without any segment-level
    /// digest. Every current part reference carries one.
    pub b3: String,
}

/// Identity of the one draft manifest schema this build writes and accepts.
pub const DRAFT_FORMAT_EPOCH: u8 = 1;

/// How many manifest revisions are retained beside the current one, as `MANIFEST.<commit>`.
///
/// Retention is what makes recent authority reopenable: every member a retained manifest revision
/// names survives the sweep, so a read view pinned within the window keeps its required bytes, and
/// corrupt current authority can be replaced by explicit manifest promotion. The window is a count
/// of manifest revisions, not time — each publication by flush, merge, or refold advances it by one.
pub const MANIFEST_RETAIN: usize = 4;

/// In-memory fields used for store authority.
///
/// A persisted value is a manifest revision and has `commit > 0`. The default value with
/// `commit == 0` is the implementation and public-result encoding of the canonical origin; it is
/// never persisted or interpreted as manifest revision zero.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// Required schema discriminator. This is an exact identity, not a compatibility range.
    pub draft_epoch: u8,
    pub parts: Vec<PartRef>,
    /// Which fold generation this revision references. A refold writes a new one and names it here,
    /// so the swap is one publication.
    pub fold_gen: u32,
    pub fold_seg: u32,
    pub fold_off: u32,
    pub next_seq: u64,
    /// Monotonic manifest-revision counter — the retained-history namespace. `next_seq` cannot
    /// serve here: it only advances at flush, while merge and refold can publish without flushing.
    pub commit: u64,
    /// Block ids whose bytes were PUNCHED out of the fold, as inclusive `[lo, hi]` ranges (erasure
    /// tends to hit runs of blocks, and ranges keep the manifest small). Authoritative, and that
    /// is the point: a punched block reads back as zeros, which is indistinguishable from
    /// corruption unless something says otherwise. This says otherwise.
    ///
    /// Ranges are ascending and disjoint.
    pub punched: Vec<(u32, u32)>,
    /// BLAKE3 of the previous manifest revision's exact bytes, hex — retained history as a hash chain, at
    /// zero marginal cost. `None` only on a store's first commit.
    ///
    /// This is an INTEGRITY check, not a security claim: it catches a manifest that was replaced,
    /// reordered, or restored out of band, which section checksums cannot see because each one is
    /// individually valid. Pruned manifests take their bytes with them, so the chain is verifiable
    /// across the retained window and says nothing about what is no longer there.
    pub prev: Option<String>,
}

impl Default for Manifest {
    fn default() -> Self {
        Self {
            draft_epoch: DRAFT_FORMAT_EPOCH,
            parts: Vec::new(),
            fold_gen: 0,
            fold_seg: 0,
            fold_off: 0,
            next_seq: 0,
            commit: 0,
            punched: Vec::new(),
            prev: None,
        }
    }
}

fn canonical_part_member_shape(name: &str) -> bool {
    let Some(body) = name.strip_prefix("part-").and_then(|rest| rest.strip_suffix(".part")) else {
        return false;
    };
    let fields = body.split('-').collect::<Vec<_>>();
    match fields.as_slice() {
        [one] => one.parse::<u64>().is_ok_and(|seq| name == format!("part-{seq:08}.part")),
        [lo, hi] => lo
            .parse::<u64>()
            .ok()
            .zip(hi.parse::<u64>().ok())
            .is_some_and(|(lo, hi)| name == format!("part-{lo:08}-{hi:08}.part")),
        [generation, lo, hi] => generation
            .strip_prefix('r')
            .filter(|value| value.len() == 4)
            .and_then(|value| value.parse::<u32>().ok())
            .filter(|generation| (1..=crate::fold::MAX_FOLD_GENERATION).contains(generation))
            .zip(lo.parse::<u64>().ok())
            .zip(hi.parse::<u64>().ok())
            .is_some_and(|((generation, lo), hi)| {
                name == format!("part-r{generation:04}-{lo:08}-{hi:08}.part")
            }),
        _ => false,
    }
}

fn valid_part_member_name(name: &str, seq_lo: u64, seq_hi: u64, fold_gen: u32) -> bool {
    let ordinary = if seq_lo == seq_hi {
        name == format!("part-{seq_lo:08}.part")
    } else {
        name == format!("part-{seq_lo:08}-{seq_hi:08}.part")
    };
    ordinary
        || (fold_gen != 0 && name == format!("part-r{fold_gen:04}-{seq_lo:08}-{seq_hi:08}.part"))
}

fn valid_blake3_hex(value: &str) -> bool {
    value.len() == 64
        && value.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn valid_fold_dictionary_member(name: &str) -> bool {
    let Some(hash) = name.strip_prefix("zdict-").and_then(|rest| rest.strip_suffix(".zd")) else {
        return false;
    };
    hash.len() == 64
        && hash.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn fold_sidecar_member(name: &str) -> Option<u32> {
    let digits = name.strip_prefix("seg-")?.strip_suffix(".dir")?;
    if digits.len() != 8 || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    digits.parse().ok()
}

fn exact_fold_member_name(name: &str) -> bool {
    let Some((_, rest)) = name.split_once('/') else { return false };
    fold_generation_of_member(name).is_some()
        && (crate::fold::segment::parse_seg_name(rest).is_some()
            || fold_sidecar_member(rest).is_some()
            || valid_fold_dictionary_member(rest))
}

fn validate_manifest_promotion_member_namespace(names: &[String]) -> Result<()> {
    for name in names {
        let retained = name.strip_prefix("MANIFEST.").is_some_and(|suffix| {
            suffix.parse::<u64>().is_ok_and(|revision| *name == format!("MANIFEST.{revision:08}"))
        });
        if name == "MANIFEST"
            || retained
            || canonical_part_member_shape(name)
            || exact_fold_member_name(name)
        {
            continue;
        }
        bail!("container member {name:?} is outside the current Store member namespace");
    }
    Ok(())
}

/// Enforce the exhaustive member namespace of one current-format Store container.
///
/// `Container` remains a generic low-level envelope, but a Store admits only its current manifest,
/// canonical retained-manifest names, parts referenced by current or retained authority, and exact
/// fold-member forms inside a referenced generation. An unrecognized member is not an extension:
/// it is a different physical format identity and must fail closed.
fn validate_store_member_namespace(
    names: &[String],
    current: Option<&Manifest>,
    mut read_member: impl FnMut(&str) -> Result<Vec<u8>>,
) -> Result<()> {
    let mut admitted = HashSet::new();
    let mut generations = HashSet::new();
    if let Some(manifest) = current {
        admitted.insert("MANIFEST".to_string());
        admitted.extend(manifest.parts.iter().map(|part| part.member.clone()));
        generations.insert(manifest.fold_gen);
    } else if !names.is_empty() {
        bail!("canonical-origin store carries container members");
    }

    for name in names.iter().filter(|name| name.starts_with("MANIFEST.")) {
        let suffix = &name["MANIFEST.".len()..];
        let commit = suffix
            .parse::<u64>()
            .with_context(|| format!("retained manifest member {name:?} has no revision number"))?;
        if *name != format!("MANIFEST.{commit:08}") {
            bail!("retained manifest member {name:?} is not in canonical revision form");
        }
        let manifest = Manifest::parse(&read_member(name)?)
            .with_context(|| format!("retained manifest member {name:?} is invalid"))?;
        if manifest.commit != commit {
            bail!("retained member {name:?} contains manifest revision {}", manifest.commit);
        }
        admitted.insert(name.clone());
        admitted.extend(manifest.parts.into_iter().map(|part| part.member));
        generations.insert(manifest.fold_gen);
    }

    for name in names {
        if admitted.contains(name) {
            continue;
        }
        if let Some(generation) = fold_generation_of_member(name) {
            let rest = name.split_once('/').expect("fold member has a slash").1;
            let exact_member = crate::fold::segment::parse_seg_name(rest).is_some()
                || fold_sidecar_member(rest).is_some()
                || valid_fold_dictionary_member(rest);
            if generations.contains(&generation) && exact_member {
                continue;
            }
        }
        bail!("container member {name:?} is outside the current Store member namespace");
    }
    Ok(())
}

impl Manifest {
    /// Parse manifest bytes, requiring and verifying its checksum trailer.
    ///
    /// The manifest is the authority whose corruption could otherwise hide durable content with no
    /// error: a flipped bit that still parses — a shortened `fold_off`, a wrong generation — must
    /// not become a believable read boundary. Every other structure refuses corruption; this
    /// closes the authority gap.
    ///
    pub(crate) fn parse(bytes: &[u8]) -> Result<Manifest> {
        let (payload, want) = checksum_trailer(bytes)
            .ok_or_else(|| anyhow::anyhow!("MANIFEST lacks the required checksum trailer"))?;
        let got = crc32fast::hash(payload);
        if got != want {
            bail!(
                "MANIFEST fails its checksum (crc32 {got:08x}, recorded {want:08x}) — \
                 refusing to open from corrupt manifest authority"
            );
        }
        if payload.len() as u64 > MAX_MANIFEST_BYTES {
            bail!(
                "MANIFEST is {} bytes, exceeding the supported {MAX_MANIFEST_BYTES}-byte limit",
                payload.len()
            );
        }
        let manifest: Manifest = serde_json::from_slice(payload).context("corrupt MANIFEST")?;
        if serde_json::to_vec(&manifest)? != payload {
            bail!("MANIFEST JSON is not in the one canonical current encoding");
        }
        manifest.validate()
    }

    /// Validate semantic fields before any one of them becomes a filesystem path or allocation
    /// input. JSON syntax and a checksum prove faithful bytes, not safe meaning.
    fn validate(self) -> Result<Manifest> {
        if self.draft_epoch != DRAFT_FORMAT_EPOCH {
            bail!(
                "MANIFEST declares draft epoch {}; this build accepts exactly {}",
                self.draft_epoch,
                DRAFT_FORMAT_EPOCH
            );
        }
        match (self.commit, self.prev.is_some()) {
            (0, _) => bail!("a persisted MANIFEST cannot have commit zero"),
            (1, false) => {}
            (1, true) => bail!("the origin MANIFEST must not name a predecessor"),
            (_, true) => {}
            (_, false) => bail!("MANIFEST revision {} must name its predecessor", self.commit),
        }
        if self.fold_gen > crate::fold::MAX_FOLD_GENERATION {
            bail!("MANIFEST fold generation {} is outside the current namespace", self.fold_gen);
        }
        if self.fold_seg > crate::fold::segment::MAX_SEGMENT_NUMBER {
            bail!("MANIFEST fold segment {} is outside the current namespace", self.fold_seg);
        }
        if u64::from(self.fold_off) < crate::fold::segment::SEG_HDR_LEN {
            bail!("a persisted MANIFEST must commit a complete fold segment header");
        }
        let mut members = HashSet::with_capacity(self.parts.len());
        let mut previous_part_hi: Option<u64> = None;
        for part in &self.parts {
            if !valid_part_member_name(&part.member, part.seq_lo, part.seq_hi, self.fold_gen) {
                bail!(
                    "MANIFEST part member {:?} is not the canonical name for sequence interval {}..={}",
                    part.member,
                    part.seq_lo,
                    part.seq_hi
                );
            }
            if !members.insert(part.member.as_str()) {
                bail!("MANIFEST names part member {:?} more than once", part.member);
            }
            if part.seq_lo > part.seq_hi {
                bail!(
                    "MANIFEST part {:?} has inverted sequence range {}..{}",
                    part.member,
                    part.seq_lo,
                    part.seq_hi
                );
            }
            let expected_lo = match previous_part_hi {
                Some(previous) => match previous.checked_add(1) {
                    Some(next) => next,
                    None => {
                        bail!("MANIFEST part sequence intervals exceed the u64 sequence domain")
                    }
                },
                None => 1,
            };
            if part.seq_lo != expected_lo {
                bail!(
                    "MANIFEST part sequence intervals must begin at one and remain contiguous; expected {expected_lo}, found {}",
                    part.seq_lo
                );
            }
            previous_part_hi = Some(part.seq_hi);
            if !valid_blake3_hex(&part.b3) {
                bail!("MANIFEST part {:?} lacks a valid BLAKE3 digest", part.member);
            }
        }
        match previous_part_hi {
            Some(highest) if self.next_seq != highest => bail!(
                "MANIFEST next_seq {} differs from the highest published part sequence {highest}",
                self.next_seq
            ),
            None if self.next_seq != 0 => {
                bail!("a MANIFEST without parts must have next_seq zero")
            }
            _ => {}
        }
        if self.prev.as_deref().is_some_and(|digest| !valid_blake3_hex(digest)) {
            bail!("MANIFEST carries an invalid previous-manifest BLAKE3 digest");
        }
        let mut previous_hi = None;
        for &(lo, hi) in &self.punched {
            if lo > hi || previous_hi.is_some_and(|previous| lo <= previous) {
                bail!("MANIFEST punched ranges must be ascending, disjoint, and non-empty");
            }
            previous_hi = Some(hi);
        }
        Ok(self)
    }

    /// The bytes as committed: compact JSON, then a `\ncrc32=XXXXXXXX` trailer over the JSON.
    fn encode(&self) -> Result<Vec<u8>> {
        let mut buf = serde_json::to_vec(self)?;
        let crc = crc32fast::hash(&buf);
        buf.extend_from_slice(format!("\ncrc32={crc:08x}").as_bytes());
        Ok(buf)
    }

    /// Stage a container manifest revision and its retained copy. The
    /// caller's superblock flip — not this — is the linearization point, so everything a flush
    /// staged (fold extents, the part, these manifests, the sweep's frees) publishes as ONE
    /// atomic state. Retention pruning is part of the same commit it belongs to.
    fn commit_into_container(&mut self, c: &mut crate::container::Container) -> Result<()> {
        // Chain onto whatever is being replaced — from the member's bytes, because the chain's
        // claim is about what a verifier can read back. Only actual absence means origin; an I/O
        // failure while reading existing authority must never fabricate a predecessor-free
        // revision.
        let predecessor = if c.contains("MANIFEST") {
            Some(c.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)
        } else {
            None
        };
        self.commit = self.commit.checked_add(1).context("MANIFEST revision space exhausted")?;
        self.prev = predecessor.map(|bytes| blake3::hash(&bytes).to_hex().to_string());
        self.clone().validate()?;
        let bytes = self.encode()?;
        c.put_bytes(&format!("MANIFEST.{:08}", self.commit), &bytes)?;
        c.put_bytes("MANIFEST", &bytes)?;
        let oldest_retained = self.commit.saturating_sub(MANIFEST_RETAIN as u64);
        for commit in container_retained_commits(c) {
            if commit <= oldest_retained {
                c.remove(&format!("MANIFEST.{commit:08}"))?;
            }
        }
        Ok(())
    }

    fn fold_tail(&self) -> Option<FoldTail> {
        if self.commit == 0 {
            None
        } else {
            Some(FoldTail { seg: self.fold_seg, off: self.fold_off })
        }
    }
}

fn open_manifest_part(
    reader: Box<dyn crate::readat::ReadAt>,
    reference: &PartRef,
    cache: Arc<SectionCache>,
    read_limits: ReadLimits,
) -> Result<Part> {
    let part = Part::open_reader_with_limits(reader, cache, read_limits)?;
    let meta = part.meta();
    if meta.n_records != reference.records
        || meta.seq_lo != reference.seq_lo
        || meta.seq_hi != reference.seq_hi
    {
        bail!(
            "MANIFEST metadata for {} disagrees with its part footer: manifest rows/range \
             {}/{}..{}, part rows/range {}/{}..{}",
            reference.member,
            reference.records,
            reference.seq_lo,
            reference.seq_hi,
            meta.n_records,
            meta.seq_lo,
            meta.seq_hi
        );
    }
    Ok(part)
}

/// The `(payload, recorded crc32)` of a checksummed manifest. Recognition is by exact shape: a
/// final line `crc32=` plus eight hex digits.
fn checksum_trailer(bytes: &[u8]) -> Option<(&[u8], u32)> {
    let pos = bytes.iter().rposition(|&b| b == b'\n')?;
    let tail = &bytes[pos + 1..];
    if tail.len() != 14 || !tail.starts_with(b"crc32=") {
        return None;
    }
    let hex = std::str::from_utf8(&tail[6..]).ok()?;
    if !hex.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) {
        return None;
    }
    let want = u32::from_str_radix(hex, 16).ok()?;
    Some((&bytes[..pos], want))
}

fn container_sidecar_bytes(
    container: &crate::container::Container,
    name: &str,
    segment_len: u64,
    read_limits: ReadLimits,
) -> Result<Option<Vec<u8>>> {
    let Some(stored) = container.member_len(name) else { return Ok(None) };
    read_limits.admit_stored(format!("fold directory sidecar {name}"), stored)?;
    Ok(Some(
        container
            .read_file_bounded(name, crate::fold::segment::max_dir_sidecar_bytes(segment_len))?,
    ))
}

fn container_reader_sidecar_bytes(
    container: &crate::container::ContainerReader,
    name: &str,
    segment_len: u64,
    read_limits: ReadLimits,
) -> Result<Option<Vec<u8>>> {
    let Some(extent) = container.extent(name) else { return Ok(None) };
    let stored = crate::readat::ReadAt::len(&extent)?;
    read_limits.admit_stored(format!("fold directory sidecar {name}"), stored)?;
    Ok(Some(
        container
            .read_file_bounded(name, crate::fold::segment::max_dir_sidecar_bytes(segment_len))?,
    ))
}

/// Open the exact fold view described by `manifest` from the supplied container handle. Keeping
/// the extents tied to this handle matters during verification: a concurrent path replacement
/// must never cause bytes from another inode to determine which checksums are exempt here.
fn open_fold_from_container(
    container: &crate::container::Container,
    manifest: &Manifest,
    cfg: FoldCfg,
    label: &Path,
    read_limits: ReadLimits,
) -> Result<Fold> {
    let fold_rel = crate::fold::fold_member_prefix(manifest.fold_gen);
    let fold_tail = manifest.fold_tail();
    let names = container.names().map(String::from).collect::<Vec<_>>();
    let mut segs = Vec::new();
    let mut present_segments = HashSet::new();
    let mut dict_files = Vec::new();
    let mut sidecars = HashSet::new();
    for name in names {
        let Some(rest) = name.strip_prefix(&format!("{fold_rel}/")) else { continue };
        if let Some(number) = crate::fold::segment::parse_seg_name(rest) {
            present_segments.insert(number);
            let extent = container.extent(&name).expect("name came from this container");
            let segment_len = crate::readat::ReadAt::len(&extent)?;
            let tail = fold_tail.ok_or_else(|| {
                anyhow::anyhow!(
                    "container has fold segment {number} but its manifest declares no fold tail"
                )
            })?;
            if number > tail.seg {
                bail!(
                    "container has fold segment {number} beyond manifest tail segment {}",
                    tail.seg
                );
            }
            if number == tail.seg && segment_len != u64::from(tail.off) {
                bail!(
                    "manifest fold tail is segment {}, offset {}, but that member is {segment_len} bytes",
                    tail.seg,
                    tail.off
                );
            }
            let reader: Arc<dyn crate::readat::ReadAt> = if number == tail.seg {
                Arc::new(crate::readat::Slice::new(extent, 0, u64::from(tail.off)))
            } else {
                Arc::new(extent)
            };
            segs.push(crate::fold::SegmentInput {
                seg: number,
                reader,
                sidecar: container_sidecar_bytes(
                    container,
                    &format!("{fold_rel}/seg-{number:08}.dir"),
                    segment_len,
                    read_limits,
                )?,
            });
        } else if let Some(number) = fold_sidecar_member(rest) {
            sidecars.insert(number);
        } else if valid_fold_dictionary_member(rest) {
            let bytes = container.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?;
            let exact = format!("zdict-{}.zd", PieceHash::of(&bytes).to_hex());
            if rest != exact {
                bail!("fold dictionary member {name:?} does not match its content identity");
            }
            dict_files.push(bytes);
        } else {
            bail!("container member {name:?} is not in the current fold namespace");
        }
    }
    if let Some(orphan) = sidecars.iter().find(|number| !segs.iter().any(|seg| seg.seg == **number))
    {
        bail!("fold sidecar seg-{orphan:08}.dir has no corresponding segment");
    }
    if let Some(tail) = fold_tail {
        if !present_segments.contains(&tail.seg) {
            bail!("manifest fold tail names absent segment {}", tail.seg);
        }
    }
    Fold::open_read_from_with_limits(segs, dict_files, cfg, label, &manifest.punched, read_limits)
}

/// Open a reader over a container, the store's single physical form.
pub fn open_read_container(path: &Path, cfg: FoldCfg) -> Result<ReadStore> {
    open_read_container_with_limits(path, cfg, ReadLimits::default())
}

/// Open a container reader with explicit frame and persistent object-count admission.
pub fn open_read_container_with_limits(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    debris::validate_store_path(path)?;
    open_read_container_with_limits_internal(path, cfg, read_limits)
}

fn open_read_container_with_limits_internal(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    crate::fold::validate_cfg(cfg)?;
    if !path.exists() && crate::container::reclaim_names(path).anchor.exists() {
        bail!(
            "{} is absent but its reclaim anchor {} exists: a reclaim's replace was interrupted; \
             a writer open recovers the store from the anchor (readers never mutate)",
            path.display(),
            crate::container::reclaim_names(path).anchor.display()
        );
    }
    let read_limits = read_limits.validate()?;
    let container = crate::container::Container::open_internal_with_limits(path, read_limits)?;
    open_read_container_handle(&container, cfg, path, read_limits)
}

/// Build the current read view entirely from one already-open container handle. Integrity and
/// writer-preflight callers must never combine a directory/manifest from one inode with parts or a
/// fold reopened from another path identity.
fn open_read_container_handle(
    container: &crate::container::Container,
    cfg: FoldCfg,
    label: &Path,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    crate::fold::validate_cfg(cfg)?;
    let read_limits = read_limits.validate()?;
    // Absent means a store nothing has flushed yet, with one tripwire: retained commits beside a
    // missing manifest are damage, not emptiness.
    let has_manifest = container.contains("MANIFEST");
    let manifest = if has_manifest {
        Manifest::parse(&container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?
    } else if container.committed_is_empty_birth() {
        Manifest::default()
    } else {
        bail!(
            "container {} has no MANIFEST authority but is not the exact empty sequence-zero \
             birth state",
            label.display(),
        );
    };
    let names = container.names().map(String::from).collect::<Vec<_>>();
    validate_store_member_namespace(&names, has_manifest.then_some(&manifest), |name| {
        container.read_file_bounded(name, MAX_MANIFEST_BYTES)
    })?;

    let fold = open_fold_from_container(container, &manifest, cfg, label, read_limits)?;

    let pcache = SectionCache::shared();
    let mut parts = Vec::with_capacity(manifest.parts.len());
    for p in &manifest.parts {
        let ext = container.extent(&p.member).ok_or_else(|| {
            anyhow::anyhow!(
                "container manifest names {} but the container does not hold it",
                p.member
            )
        })?;
        parts.push(Arc::new(open_manifest_part(Box::new(ext), p, pcache.clone(), read_limits)?));
    }
    Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
}

/// Open a read-only container over an arbitrary positioned byte source.
///
/// The source may be memory, an object-store range cache, or a browser callback. It receives the
/// same admission checks, part readers, fold readers, visibility, and query implementation as a
/// filesystem-backed snapshot.
pub fn open_read_container_source(
    source: std::sync::Arc<dyn crate::readat::ReadAt>,
    label: &str,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    let read_limits = read_limits.validate()?;
    let container =
        crate::container::ContainerReader::open_with_limits(source, label, read_limits)?;
    let has_manifest = container.contains("MANIFEST");
    let manifest = if has_manifest {
        Manifest::parse(&container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?
    } else if container.committed_is_empty_birth() {
        Manifest::default()
    } else {
        bail!("container {label} has no MANIFEST authority but is not the exact empty sequence-zero birth state")
    };
    let names = container.names().map(String::from).collect::<Vec<_>>();
    validate_store_member_namespace(&names, has_manifest.then_some(&manifest), |name| {
        container.read_file_bounded(name, MAX_MANIFEST_BYTES)
    })?;
    let fold_rel = if manifest.fold_gen == 0 {
        "fold".to_string()
    } else {
        format!("fold-{:04}", manifest.fold_gen)
    };
    let fold_tail = manifest.fold_tail();
    let mut segs = Vec::new();
    let mut present_segments = HashSet::new();
    let mut dict_files = Vec::new();
    let mut sidecars = HashSet::new();
    for name in names {
        let Some(rest) = name.strip_prefix(&format!("{fold_rel}/")) else { continue };
        if let Some(number) = crate::fold::segment::parse_seg_name(rest) {
            present_segments.insert(number);
            let extent = container.extent(&name).expect("name came from this directory");
            let segment_len = crate::readat::ReadAt::len(&extent)?;
            let tail = fold_tail.ok_or_else(|| {
                anyhow::anyhow!(
                    "container has fold segment {number} but its manifest declares no fold tail"
                )
            })?;
            if number > tail.seg {
                bail!(
                    "container has fold segment {number} beyond manifest tail segment {}",
                    tail.seg
                );
            }
            if number == tail.seg && segment_len != u64::from(tail.off) {
                bail!(
                    "manifest fold tail is segment {}, offset {}, but that member is {segment_len} bytes",
                    tail.seg,
                    tail.off
                );
            }
            let reader: Arc<dyn crate::readat::ReadAt> = if number == tail.seg {
                Arc::new(crate::readat::Slice::new(extent, 0, u64::from(tail.off)))
            } else {
                Arc::new(extent)
            };
            segs.push(crate::fold::SegmentInput {
                seg: number,
                reader,
                sidecar: container_reader_sidecar_bytes(
                    &container,
                    &format!("{fold_rel}/seg-{number:08}.dir"),
                    segment_len,
                    read_limits,
                )?,
            });
        } else if let Some(number) = fold_sidecar_member(rest) {
            // Opened alongside its exact segment name above; advisory absence is allowed.
            sidecars.insert(number);
        } else if valid_fold_dictionary_member(rest) {
            let bytes = container.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?;
            let exact = format!("zdict-{}.zd", PieceHash::of(&bytes).to_hex());
            if rest != exact {
                bail!("fold dictionary member {name:?} does not match its content identity");
            }
            dict_files.push(bytes);
        } else {
            bail!("container member {name:?} is not in the current fold namespace");
        }
    }
    if let Some(orphan) = sidecars.iter().find(|number| !segs.iter().any(|seg| seg.seg == **number))
    {
        bail!("fold sidecar seg-{orphan:08}.dir has no corresponding segment");
    }
    if let Some(tail) = fold_tail {
        if !present_segments.contains(&tail.seg) {
            bail!("manifest fold tail names absent segment {}", tail.seg);
        }
    }
    let fold = Fold::open_read_from_with_limits(
        segs,
        dict_files,
        cfg,
        Path::new(label),
        &manifest.punched,
        read_limits,
    )?;
    let pcache = SectionCache::shared();
    let mut parts = Vec::with_capacity(manifest.parts.len());
    for part in &manifest.parts {
        let extent = container.extent(&part.member).ok_or_else(|| {
            anyhow::anyhow!(
                "container manifest names {} but the container does not hold it",
                part.member
            )
        })?;
        parts.push(Arc::new(open_manifest_part(
            Box::new(extent),
            part,
            pcache.clone(),
            read_limits,
        )?));
    }
    Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
}

/// Prove the whole-value identities asserted by WAL replay before writer open mutates any store byte.
/// A frame carries only newly introduced piece bytes, so resolution spans the current store authority and
/// every earlier frame in this same WAL.
fn verify_replay_identities(frames: &[wal::Frame], current: &ReadStore) -> Result<()> {
    let pending_sequence = current.manifest.next_seq.checked_add(1);
    let mut saw_pending = false;
    let mut pending: HashMap<PieceHash, Vec<u8>> = HashMap::new();
    for frame in frames {
        let redundant = current.manifest.commit != 0 && frame.seq == current.manifest.next_seq;
        let is_pending = Some(frame.seq) == pending_sequence;
        if !redundant && !is_pending {
            bail!(
                "WAL frame carries sequence {}, expected the current record-version sequence {} or its representable successor",
                frame.seq,
                current.manifest.next_seq,
            );
        }
        if redundant && saw_pending {
            bail!("WAL returns from pending sequence to already-published sequence");
        }
        saw_pending |= is_pending;
        for (hash, bytes) in &frame.novel {
            if pending.insert(*hash, bytes.clone()).is_some() {
                bail!("WAL repeats novel piece identity {hash}");
            }
        }
        for content in &frame.record.contents {
            let mut hasher = blake3::Hasher::new();
            for op in &content.ops {
                match op {
                    ContentOp::Lit(bytes) => {
                        hasher.update(bytes);
                    }
                    ContentOp::Piece { hash, len } => {
                        let owned;
                        let bytes = if let Some(bytes) = pending.get(hash) {
                            bytes.as_slice()
                        } else {
                            let loc = locate_verified_piece(&current.parts, &current.fold, hash)?
                                .ok_or_else(|| {
                                anyhow::anyhow!(
                                    "WAL content {:?} references absent piece {hash}",
                                    content.name
                                )
                            })?;
                            owned = current.fold.read_verified(loc, *hash)?;
                            owned.as_slice()
                        };
                        let declared_len = usize::try_from(*len)
                            .context("WAL piece length exceeds this platform")?;
                        if bytes.len() != declared_len {
                            bail!(
                                "WAL content {:?} declares piece {hash} length {len}, actual {}",
                                content.name,
                                bytes.len()
                            );
                        }
                        hasher.update(bytes);
                    }
                }
            }
            let declared = content.identity.ok_or_else(|| {
                anyhow::anyhow!("WAL content {:?} has no whole-value identity", content.name)
            })?;
            let actual = ContentHash(hasher.finalize().into());
            if actual != declared {
                bail!(
                    "WAL content {:?} identity is {declared}, reconstructed bytes are {actual}",
                    content.name
                );
            }
        }
    }
    Ok(())
}

/// Resolve one piece through the pending Fold window and then the authoritative Part dictionaries.
/// A punched dictionary entry is historical residue, not a lookup result; continue through older
/// parts until a readable mapping is found. Acceptance and WAL replay must use this same rule or a
/// mutation can be accepted without bytes that its next open knows how to recover.
fn locate_verified_piece(
    parts: &[Arc<Part>],
    fold: &Fold,
    hash: &PieceHash,
) -> Result<Option<Loc>> {
    fold.ensure_no_failed_write()?;
    if let Some(location) = fold.lookup(*hash) {
        return Ok(Some(location));
    }
    for part in parts.iter().rev() {
        if let Some(location) = part.find_piece(hash)? {
            if fold.is_punched(location.block_id) {
                continue;
            }
            fold.read_verified(location, *hash)
                .with_context(|| format!("piece dictionary mapped {hash} to invalid fold bytes"))?;
            return Ok(Some(location));
        }
    }
    Ok(None)
}

/// Exact physical piece locations required by the rows visible under one store authority.
///
/// Programs are interpreted through their owning Part dictionaries, exactly like reconstruction.
/// A content identity may legitimately occur at several Fold locations; keying by `Loc` preserves
/// every such location so maintenance cannot punch one merely because another copy is readable.
fn live_fold_pieces_with_control(
    parts: &[Arc<Part>],
    fold: &Fold,
    control: &crate::control::OperationControl,
) -> Result<BTreeMap<Loc, PieceHash>> {
    let visible = read::visibility(parts)?;
    let mut pieces = BTreeMap::new();
    for (part_index, rows) in visible.rows.iter().enumerate() {
        let part = &parts[part_index];
        for &row in rows {
            control.check("content reachability")?;
            for content in part.record(row)?.contents {
                for operation in content.ops {
                    let ContentOp::Piece { hash, len } = operation else { continue };
                    let location = part.find_piece(&hash)?.ok_or_else(|| {
                        anyhow::anyhow!(
                            "a record resolved by current authority references absent piece {hash} in its owning Part"
                        )
                    })?;
                    if location.raw != len {
                        bail!(
                            "live piece {hash} is {} bytes but its record says {len}",
                            location.raw
                        );
                    }
                    fold.visit_verified(location, hash, |_| {}).with_context(|| {
                        format!(
                            "record resolved by current authority maps piece {hash} to invalid Fold bytes"
                        )
                    })?;
                    if let Some(existing) = pieces.insert(location, hash) {
                        if existing != hash {
                            bail!(
                                "live Fold location {location:?} carries conflicting piece identities {existing} and {hash}"
                            );
                        }
                    }
                }
            }
        }
    }
    Ok(pieces)
}

/// Open a read view at retained manifest revision `commit`.
///
/// The retained manifest names the state; `punched` comes from the current manifest revision because
/// content deallocation is declared by current authority and a retained copy predates later content
/// punches. Fold readers are bounded to the retained revision's exact tail.
pub fn open_read_container_at(path: &Path, cfg: FoldCfg, commit: u64) -> Result<ReadStore> {
    open_read_container_at_with_limits(path, cfg, commit, ReadLimits::default())
}

/// [`open_read_container_at`] with explicit frame and object-count admission.
pub fn open_read_container_at_with_limits(
    path: &Path,
    cfg: FoldCfg,
    commit: u64,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    let read_limits = read_limits.validate()?;
    debris::validate_store_path(path)?;
    let c = crate::container::Container::open_internal_with_limits(path, read_limits)?;
    let bytes =
        c.read_file_bounded(&format!("MANIFEST.{commit:08}"), MAX_MANIFEST_BYTES).with_context(
            || format!("retained manifest revision {commit} is not held by {}", path.display()),
        )?;
    let manifest = Manifest::parse(&bytes)?;
    let current = Manifest::parse(&c.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)
        .with_context(|| {
            format!(
                "retained read view at manifest revision {commit} needs current manifest authority in {} to tell \
                 erased blocks from damaged ones, and it could not be read",
                path.display()
            )
        })?;
    let names = c.names().map(String::from).collect::<Vec<_>>();
    validate_store_member_namespace(&names, Some(&current), |name| {
        c.read_file_bounded(name, MAX_MANIFEST_BYTES)
    })?;
    verification_integrity(
        "verify retained authority chain before opening a retained read view",
        verify_chain_container(&c, read_limits, &crate::control::OperationControl::default()),
    )?;
    open_retained_from_container(&c, path, cfg, commit, manifest, &current, names, read_limits)
}

#[allow(clippy::too_many_arguments)]
fn open_retained_from_container(
    c: &crate::container::Container,
    path: &Path,
    cfg: FoldCfg,
    commit: u64,
    mut manifest: Manifest,
    current: &Manifest,
    names: Vec<String>,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    if current.fold_gen != manifest.fold_gen {
        bail!(
            "retained manifest revision {commit} is from fold generation {} but current authority references {} — \
             a refold purges retained history, so this read view has no content-punch authority",
            manifest.fold_gen,
            current.fold_gen
        );
    }
    manifest.punched.clone_from(&current.punched);

    let prefix = crate::fold::fold_member_prefix(manifest.fold_gen);
    let tail = manifest.fold_tail();
    let mut segs = Vec::new();
    let mut dict_files = Vec::new();
    let mut present_segments = HashSet::new();
    let mut sidecars = HashSet::new();
    for name in names {
        let Some(rest) = name.strip_prefix(&format!("{prefix}/")) else { continue };
        if let Some(n) = crate::fold::segment::parse_seg_name(rest) {
            present_segments.insert(n);
            let extent = c.extent(&name).expect("name came from this container");
            let full_len = crate::readat::ReadAt::len(&extent)?;
            let (reader, len, whole): (Arc<dyn crate::readat::ReadAt>, u64, bool) = match tail {
                Some(t) if n > t.seg => continue,
                Some(t) if n == t.seg => (
                    Arc::new(crate::readat::Slice::new(extent, 0, u64::from(t.off))),
                    u64::from(t.off),
                    u64::from(t.off) == full_len,
                ),
                _ => (Arc::new(extent), full_len, true),
            };
            segs.push(crate::fold::SegmentInput {
                seg: n,
                reader,
                sidecar: if whole {
                    container_sidecar_bytes(
                        c,
                        &format!("{prefix}/seg-{n:08}.dir"),
                        len,
                        read_limits,
                    )?
                } else {
                    None
                },
            });
        } else if let Some(number) = fold_sidecar_member(rest) {
            sidecars.insert(number);
        } else if valid_fold_dictionary_member(rest) {
            let bytes = c.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?;
            let exact = format!("zdict-{}.zd", PieceHash::of(&bytes).to_hex());
            if rest != exact {
                bail!("fold dictionary member {name:?} does not match its content identity");
            }
            dict_files.push(bytes);
        } else {
            bail!("container member {name:?} is not in the current fold namespace");
        }
    }
    if let Some(orphan) = sidecars.iter().find(|number| !present_segments.contains(number)) {
        bail!("fold sidecar seg-{orphan:08}.dir has no corresponding segment");
    }
    if let Some(tail) = tail {
        if !present_segments.contains(&tail.seg) {
            bail!("retained manifest fold tail names absent segment {}", tail.seg);
        }
    }
    let fold = Fold::open_retained_read_from_with_limits(
        segs,
        dict_files,
        cfg,
        path,
        &manifest.punched,
        read_limits,
    )?;
    let pcache = SectionCache::shared();
    let mut parts = Vec::with_capacity(manifest.parts.len());
    for p in &manifest.parts {
        let ext = c.extent(&p.member).ok_or_else(|| {
            anyhow::anyhow!(
                "retained commit {commit} names {} but the container does not hold it",
                p.member
            )
        })?;
        parts.push(Arc::new(open_manifest_part(Box::new(ext), p, pcache.clone(), read_limits)?));
    }
    Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
}

/// Open a reader over the current TurnDB container format.
pub fn open_read_file(path: &Path, cfg: FoldCfg) -> Result<ReadStore> {
    open_read_file_with_limits(path, cfg, ReadLimits::default())
}

/// Open a single-file reader with explicit frame and persistent object-count admission.
pub fn open_read_file_with_limits(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    open_read_container_with_limits(path, cfg, read_limits)
}

/// What [`verify_chain_file`] checked.
#[derive(Clone, Copy, Debug, Default)]
pub struct ChainReport {
    /// Retained manifest members parsed and checked. Zero is an explicit empty/new-store result.
    pub retained_manifests: usize,
    /// Predecessor links verified across the retained window, including equality between the newest
    /// retained revision and current `MANIFEST`.
    pub links: usize,
    /// Part digests verified against their members, across every retained manifest revision.
    pub part_digests: usize,
}

/// Evidence returned by complete verification of one current store authority.
#[derive(Clone, Copy, Debug, Default)]
pub struct StoreVerification {
    pub chain: ChainReport,
    pub fold: crate::fold::FoldScrub,
    /// Distinct parts referenced by the current manifest revision. Retained-only parts are also
    /// verified but are not included in this current-authority count.
    pub parts: usize,
    /// Sections in parts referenced by the current manifest revision. Retained-only section work
    /// is evidenced by the retained-chain checks rather than added to this count.
    pub part_sections: usize,
    /// Distinct record slots resolved by the read view pinned to current store authority.
    pub records: usize,
    /// Named content values reconstructed byte-exactly.
    pub content_values: usize,
    /// Exact bytes reconstructed across all named content values.
    pub content_bytes: u64,
    /// Reconstructed values whose stored whole-value BLAKE3 identity was checked.
    pub content_identities: usize,
}

#[derive(Clone, Copy, Debug, Default)]
struct VerifiedVisibleContent {
    records: usize,
    values: usize,
    bytes: u64,
    identities: usize,
}

fn verify_visible_content(
    parts: &[Arc<Part>],
    fold: &Fold,
    control: &crate::control::OperationControl,
) -> Result<VerifiedVisibleContent> {
    let visible = verification_integrity("enumerate committed records", read::visibility(parts))?;
    let mut report = VerifiedVisibleContent::default();
    for (part_index, rows) in visible.rows.iter().enumerate() {
        let part = &parts[part_index];
        for &row in rows {
            control.check("store verification")?;
            let record = verification_integrity("decode committed record", part.record(row))?;
            report.records = report
                .records
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("verified record count overflow"))?;
            for content in &record.contents {
                control.check("store verification")?;
                let bytes = verification_integrity(
                    "verify committed content",
                    part.verify_projected_content_with_control(content, fold, control),
                )?;
                report.values = report
                    .values
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("verified content value count overflow"))?;
                report.bytes = report
                    .bytes
                    .checked_add(bytes)
                    .ok_or_else(|| anyhow::anyhow!("verified content byte count overflow"))?;
                report.identities = report
                    .identities
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("verified content identity count overflow"))?;
            }
        }
    }
    Ok(report)
}

fn verify_retained_visible_content(
    parts: &[Arc<Part>],
    fold: &Fold,
    control: &crate::control::OperationControl,
) -> Result<()> {
    let visible = verification_integrity("enumerate retained records", read::visibility(parts))?;
    for (part_index, rows) in visible.rows.iter().enumerate() {
        let part = &parts[part_index];
        for &row in rows {
            control.check("retained-authority verification")?;
            let record = verification_integrity("decode retained record", part.record(row))?;
            for content in &record.contents {
                verification_integrity(
                    "verify retained content",
                    part.verify_retained_projected_content_with_control(content, fold, control),
                )?;
            }
        }
    }
    Ok(())
}

fn verify_committed_store(
    parts: &[Arc<Part>],
    fold_store: &Fold,
    chain: ChainReport,
    control: &crate::control::OperationControl,
) -> Result<StoreVerification> {
    let fold =
        verification_integrity("verify fold frames", fold_store.scrub_with_control(control))?;
    let mut part_sections = 0usize;
    for part in parts {
        control.check("store verification")?;
        let sections = verification_integrity(
            "verify immutable part sections",
            part.verify_sections_with_control(control),
        )?;
        verification_integrity(
            "verify every physical part row",
            part.verify_semantics_with_control(control),
        )?;
        verification_integrity(
            "verify every operational piece dictionary entry",
            part.verify_piece_dictionary_with_control(fold_store, control),
        )?;
        part_sections = part_sections
            .checked_add(sections)
            .ok_or_else(|| anyhow::anyhow!("verified part section count overflow"))?;
    }
    let content = verify_visible_content(parts, fold_store, control)?;
    Ok(StoreVerification {
        chain,
        fold,
        parts: parts.len(),
        part_sections,
        records: content.records,
        content_values: content.values,
        content_bytes: content.bytes,
        content_identities: content.identities,
    })
}

fn verify_retained_piece_dictionaries(
    container: &crate::container::Container,
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<usize> {
    if !container.contains("MANIFEST") {
        return Ok(0);
    }
    let current = Manifest::parse(&container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?;
    let names = container.names().map(String::from).collect::<Vec<_>>();
    let mut verified_pieces = 0usize;
    for commit in container_retained_commits(container) {
        control.check("piece dictionary verification")?;
        // A retained authority ends at its own fold tail. Checking its dictionary against the
        // current, longer fold would falsely prove a location introduced only by a later revision.
        // The retained opener also applies the current manifest's punched declaration, which is
        // the authority for intentionally unavailable historical payloads.
        let manifest = Manifest::parse(
            &container.read_file_bounded(&format!("MANIFEST.{commit:08}"), MAX_MANIFEST_BYTES)?,
        )?;
        let retained = open_retained_from_container(
            container,
            path,
            cfg,
            commit,
            manifest,
            &current,
            names.clone(),
            read_limits,
        )?;
        for part in &retained.parts {
            verified_pieces = verified_pieces
                .checked_add(part.verify_piece_dictionary_with_control(&retained.fold, control)?)
                .ok_or_else(|| anyhow::anyhow!("verified piece count overflow"))?;
        }
        verification_integrity(
            "verify retained-authority content",
            verify_retained_visible_content(&retained.parts, &retained.fold, control),
        )?;
    }
    Ok(verified_pieces)
}

/// Best-effort cleanup ownership for an artifact that has not crossed its installation rename.
struct UninstalledArtifact {
    path: PathBuf,
    armed: bool,
}

fn artifact_staging_path(out: &Path, operation: &str) -> PathBuf {
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let serial = NEXT.fetch_add(1, Ordering::Relaxed);
    let mut staging = out.as_os_str().to_os_string();
    staging.push(format!(".{operation}-{}-{serial}", crate::vfs::protocol_process_id()));
    PathBuf::from(staging)
}

impl UninstalledArtifact {
    fn new(path: PathBuf) -> Self {
        Self { path, armed: true }
    }

    fn installed(&mut self) {
        self.armed = false;
    }
}

impl Drop for UninstalledArtifact {
    fn drop(&mut self) {
        if self.armed {
            let _ = crate::vfs::unlink(&self.path);
        }
    }
}

/// Copy a single-file store's current store authority into a fresh container at `out`.
///
/// The backup carries `MANIFEST`, every part it names, and the fold generation referenced by the
/// selected authority — no
/// retained log and no writer state. Staged beside the destination,
/// committed, fully verified as a store, then installed with a rename that refuses to replace. A
/// crash leaves staging litter and an untouched destination.
fn backup_container_copy(
    container: &std::sync::Arc<std::sync::Mutex<crate::container::Container>>,
    manifest: &Manifest,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    out: &Path,
    staging: &Path,
    control: &crate::control::OperationControl,
) -> Result<crate::backup::BackupStats> {
    let mut fresh = crate::container::Container::create_staging(staging)?;
    let mut uninstalled = UninstalledArtifact::new(staging.to_path_buf());

    let c = container.lock().expect("container lock poisoned");
    let prefix = crate::fold::fold_member_prefix(manifest.fold_gen);
    let mut names = Vec::new();
    if manifest.commit != 0 {
        names.push("MANIFEST".to_string());
        names.extend(manifest.parts.iter().map(|p| p.member.clone()));
        let mut fold_members: Vec<String> =
            c.names().filter(|n| n.starts_with(&format!("{prefix}/"))).map(String::from).collect();
        fold_members.sort();
        names.extend(fold_members);
    }

    let mut bytes = 0u64;
    for name in &names {
        control.check("backup")?;
        let reader = c.extent(name).ok_or_else(|| {
            anyhow::anyhow!("the current manifest revision names {name} but the container lost it")
        })?;
        let len = crate::readat::ReadAt::len(&reader)?;
        fresh.put_stream(name, len, |at, into| {
            crate::control::OperationControl::check(control, "backup")
                .map_err(std::io::Error::other)?;
            crate::readat::ReadAt::read_exact_at(&reader, into, at)
        })?;
        bytes += len;
    }
    drop(c);
    control.check("backup")?;
    fresh.commit()?;
    drop(fresh);
    verify_container_artifact(staging, cfg, read_limits, control)
        .with_context(|| format!("verify staged backup {}", staging.display()))?;
    crate::vfs::rename_noreplace(staging, out)?;
    uninstalled.installed();
    if let Some(parent) = out.parent() {
        // The installed name is the result; a failed directory sync means it may not survive a
        // crash, and the operation reports that rather than success.
        crate::vfs::sync_dir(parent).with_context(|| {
            format!("sync {} after installing {}", parent.display(), out.display())
        })?;
    }
    Ok(crate::backup::BackupStats { members: names.len(), bytes, commit: manifest.commit })
}

/// [`verify_chain`] over a single-file store's members: the same walk and claims, with no
/// filesystem namespace between the evidence and the check.
fn verify_chain_container(
    c: &crate::container::Container,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<ChainReport> {
    verify_chain_container_scoped(c, read_limits, control, true)
}

/// [`verify_chain_container`] with the part checks optional. Without them the walk still proves
/// every retained revision's name, parse, adjacency, `prev` link, cursor and tail order, generation,
/// equality between current and newest retained bytes, and the presence of every named part; it
/// reads no part bytes, so its cost is proportional to the retained manifests alone.
fn verify_chain_container_scoped(
    c: &crate::container::Container,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
    check_parts: bool,
) -> Result<ChainReport> {
    let names = c.names().map(String::from).collect::<Vec<_>>();
    let current = if c.contains("MANIFEST") {
        Some(Manifest::parse(&c.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?)
    } else {
        None
    };
    validate_store_member_namespace(&names, current.as_ref(), |name| {
        c.read_file_bounded(name, MAX_MANIFEST_BYTES)
    })?;
    let mut report = ChainReport::default();
    let part_cache = SectionCache::shared();
    let mut verified_parts = HashSet::new();
    for name in c.names().filter(|name| name.starts_with("MANIFEST.")) {
        let rest = &name["MANIFEST.".len()..];
        let commit = rest
            .parse::<u64>()
            .with_context(|| format!("retained manifest member {name:?} has no commit number"))?;
        if name != format!("MANIFEST.{commit:08}") {
            bail!("retained manifest member {name:?} is not in canonical commit form");
        }
    }
    let commits = container_retained_commits(c);
    if commits.len() > MANIFEST_RETAIN {
        bail!(
            "container retains {} manifest revisions, over the current-format limit of {MANIFEST_RETAIN}",
            commits.len()
        );
    }
    report.retained_manifests = commits.len();
    let mut prev_bytes: Option<Vec<u8>> = None;
    let mut prev_commit: Option<u64> = None;
    let mut prev_next_seq: Option<u64> = None;
    let mut prev_fold_tail: Option<(u32, u32)> = None;
    for &commit in &commits {
        control.check("manifest verification")?;
        let bytes = c.read_file_bounded(&format!("MANIFEST.{commit:08}"), MAX_MANIFEST_BYTES)?;
        let m = Manifest::parse(&bytes)
            .with_context(|| format!("retained manifest {commit} is corrupt"))?;
        if m.commit != commit {
            bail!("retained member MANIFEST.{commit:08} contains manifest revision {}", m.commit);
        }
        if current.as_ref().is_some_and(|authority| m.fold_gen != authority.fold_gen) {
            bail!(
                "retained manifest revision {commit} references fold generation {}, but current authority references {}; refold must purge its predecessors",
                m.fold_gen,
                current.as_ref().expect("checked as present").fold_gen
            );
        }
        if let Some(previous) = prev_commit {
            let expected = previous
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("retained manifest revision order overflows"))?;
            if commit != expected {
                bail!(
                    "manifest chain has a revision gap: retained revision {previous} is followed by {commit}, expected {expected}"
                );
            }
        }
        if prev_next_seq.is_some_and(|previous| m.next_seq < previous) {
            bail!(
                "manifest chain moves the record-version cursor backward from {} to {} at revision {commit}",
                prev_next_seq.expect("checked as present"),
                m.next_seq
            );
        }
        let fold_tail = (m.fold_seg, m.fold_off);
        if prev_fold_tail.is_some_and(|previous| fold_tail < previous) {
            bail!(
                "manifest chain moves the fold tail backward from {:?} to {:?} at revision {commit}",
                prev_fold_tail.expect("checked as present"),
                fold_tail
            );
        }
        if let Some(pb) = &prev_bytes {
            let want = m.prev.as_ref().ok_or_else(|| {
                anyhow::anyhow!(
                    "manifest chain broken: retained commit {commit} has no predecessor digest"
                )
            })?;
            let got = blake3::hash(pb).to_hex().to_string();
            if *want != got {
                bail!(
                    "manifest chain broken: commit {commit} names prev {want} but the previous \
                     retained commit hashes to {got}"
                );
            }
            report.links += 1;
        }
        for p in &m.parts {
            control.check("manifest verification")?;
            if !check_parts {
                if !c.contains(&p.member) {
                    bail!(
                        "part {} named by commit {commit} is not held by the container",
                        p.member
                    );
                }
                continue;
            }
            {
                let want = &p.b3;
                let reader = c.extent(&p.member).ok_or_else(|| {
                    anyhow::anyhow!(
                        "part {} named by commit {commit} is not held by the container",
                        p.member
                    )
                })?;
                let got = hash_reader_with_control(&reader, control, "manifest verification")
                    .with_context(|| format!("part {} named by commit {commit}", p.member))?
                    .to_hex()
                    .to_string();
                if *want != got {
                    bail!("part {} drifted from the digest commit {commit} pinned", p.member);
                }
                report.part_digests += 1;
            }
            if verified_parts.insert(p.member.clone()) {
                let reader = c.extent(&p.member).expect("part presence proved while hashing");
                let part = open_manifest_part(Box::new(reader), p, part_cache.clone(), read_limits)
                    .with_context(|| {
                        format!("open part {} named by retained manifest {commit}", p.member)
                    })?;
                part.verify_sections_with_control(control)
                    .with_context(|| format!("verify sections of retained part {}", p.member))?;
                part.verify_semantics_with_control(control).with_context(|| {
                    format!("verify physical rows of retained part {}", p.member)
                })?;
            }
        }
        prev_bytes = Some(bytes);
        prev_commit = Some(commit);
        prev_next_seq = Some(m.next_seq);
        prev_fold_tail = Some(fold_tail);
    }
    if let (Some(&newest), Some(pb)) = (commits.last(), &prev_bytes) {
        let live = c.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?;
        if live != *pb {
            bail!("MANIFEST diverges from its retained copy at commit {newest}");
        }
        report.links += 1;
    } else if c.contains("MANIFEST") {
        // Backup artifacts intentionally omit retained history. Their current manifest is still
        // authority, so its part pins must be checked directly rather than disappearing with the
        // chain that normally duplicates the live revision.
        let bytes = c.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?;
        let manifest = Manifest::parse(&bytes).context("current manifest is corrupt")?;
        for part in &manifest.parts {
            control.check("manifest verification")?;
            if !check_parts {
                if !c.contains(&part.member) {
                    bail!(
                        "part {} named by the current manifest revision is not held by the container",
                        part.member
                    );
                }
                continue;
            }
            {
                let want = &part.b3;
                let reader = c.extent(&part.member).ok_or_else(|| {
                    anyhow::anyhow!(
                        "part {} named by the current manifest revision is not held by the container",
                        part.member
                    )
                })?;
                let got = hash_reader_with_control(&reader, control, "manifest verification")?
                    .to_hex()
                    .to_string();
                if *want != got {
                    bail!(
                        "part {} drifted from the digest the current manifest revision pinned",
                        part.member
                    );
                }
                report.part_digests += 1;
            }
            if verified_parts.insert(part.member.clone()) {
                let reader = c.extent(&part.member).expect("part presence proved while hashing");
                let opened =
                    open_manifest_part(Box::new(reader), part, part_cache.clone(), read_limits)
                        .with_context(|| {
                            format!(
                                "open part {} named by the current manifest revision",
                                part.member
                            )
                        })?;
                opened
                    .verify_sections_with_control(control)
                    .with_context(|| format!("verify sections of current part {}", part.member))?;
                opened.verify_semantics_with_control(control).with_context(|| {
                    format!("verify physical rows of current part {}", part.member)
                })?;
            }
        }
    } else if !c.committed_is_empty_birth() {
        // Sequence zero is the one valid manifestless state: a newly created store before its
        // first publication. Once any container state has committed, losing MANIFEST is losing
        // the authority for every remaining member, never a return to emptiness.
        bail!("committed container sequence {} has no MANIFEST authority", c.seq());
    }
    Ok(report)
}

/// Validate exactly the container bytes that artifact installation would make reachable.
/// This is read-only: it verifies the member directory and payload checksums, opens every
/// manifest-named part and fold member, walks the retained chain, scrubs every section/frame, and
/// reconstructs every live named content value.
pub(crate) fn verify_container_artifact(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<(usize, u64, u64, StoreVerification)> {
    let container = verification_integrity(
        "open container for verification",
        crate::container::Container::open_internal_with_limits(path, read_limits),
    )?;
    read_limits.admit_directory_entries(
        format!("container {} member directory", path.display()),
        container.len() as u64,
    )?;
    let members = verification_integrity(
        "verify container members",
        container.verify_with_store_profile_and_control(cfg, read_limits, control),
    )?;
    let member_bytes = container.member_bytes();
    let chain = verification_integrity(
        "verify retained manifest chain",
        verify_chain_container(&container, read_limits, control),
    )?;
    let store = verification_integrity(
        "open container store for verification",
        open_read_container_handle(&container, cfg, path, read_limits),
    )?;
    verification_integrity(
        "verify retained-authority piece dictionaries",
        verify_retained_piece_dictionaries(&container, path, cfg, read_limits, control),
    )?;
    drop(container);
    let commit = store.manifest.commit;
    let report = verification_integrity(
        "verify complete container store",
        verify_committed_store(&store.parts, &store.fold, chain, control),
    )?;
    Ok((members, member_bytes, commit, report))
}

fn verification_integrity<T>(context: &'static str, result: Result<T>) -> Result<T> {
    result.map_err(|error| {
        if crate::error::classify(&error) == crate::error::ErrorClass::Internal {
            crate::error::IntegrityError::new(context, error).into()
        } else {
            error
        }
    })
}

/// Explicit rollback bounds for checked manifest promotion.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ManifestPromotionOptions {
    /// Maximum number of newer retained commits that may be abandoned. Zero repairs only to the
    /// newest retained commit and is the safe default.
    pub max_rollback_commits: u64,
}

/// Evidence returned after checked manifest promotion.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ManifestPromotionReport {
    pub commit: u64,
    pub rollback_commits: u64,
    /// Retained revisions older than the promoted one that were abandoned because they, or the
    /// link joining them to the survivors, no longer validated. Retention shrinks by this many.
    pub abandoned_retained_revisions: usize,
    pub records: usize,
    pub content_values: usize,
    pub parts: usize,
    pub part_sections: usize,
    pub fold_segments: u32,
    pub fold_blocks: usize,
    pub fold_bytes: u64,
}

#[derive(Debug)]
pub enum ManifestPromotionError {
    Healthy(PathBuf),
    RollbackLimit { needed: u64, allowed: u64 },
    NoUsableCandidate { examined: usize, reason: String },
}

impl std::fmt::Display for ManifestPromotionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ManifestPromotionError::Healthy(path) => write!(
                f,
                "MANIFEST at {} is intact and its retained history validates; refusing manifest promotion for an intact store",
                path.display()
            ),
            ManifestPromotionError::RollbackLimit { needed, allowed } => write!(
                f,
                "manifest promotion needs to abandon {needed} newer retained revisions but only {allowed} were authorized"
            ),
            ManifestPromotionError::NoUsableCandidate { examined, reason } => write!(
                f,
                "none of {examined} retained manifest revisions is a fully readable promotion candidate: {reason}"
            ),
        }
    }
}

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

/// Failures that say nothing about the bytes: interruption, admission, and the filesystem itself.
/// Manifest promotion propagates these instead of treating them as damage to work around.
fn environmental_failure(error: &anyhow::Error) -> bool {
    matches!(
        crate::error::classify(error),
        crate::error::ErrorClass::Cancelled
            | crate::error::ErrorClass::ResourceExhausted
            | crate::error::ErrorClass::Io
            | crate::error::ErrorClass::NotFound
            | crate::error::ErrorClass::Unsupported
    )
}

fn validate_surviving_promotion_history(
    container: &crate::container::Container,
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
    selected: &Manifest,
) -> Result<SurvivingHistory> {
    let mut admitted_parts: HashSet<String> =
        selected.parts.iter().map(|part| part.member.clone()).collect();
    let mut abandoned_older = Vec::new();
    let mut newer = selected.clone();
    let older = container_retained_commits(container)
        .into_iter()
        .filter(|commit| *commit < selected.commit)
        .rev();
    for commit in older {
        control.check("manifest promotion retained-history validation")?;
        if !abandoned_older.is_empty() {
            // Nothing older than a break can be linked to the survivors, so it is abandoned
            // with the revision that broke the chain.
            abandoned_older.push(commit);
            continue;
        }
        let bytes =
            container.read_file_bounded(&format!("MANIFEST.{commit:08}"), MAX_MANIFEST_BYTES)?;
        match validate_retained_predecessor(
            container,
            path,
            cfg,
            read_limits,
            control,
            &bytes,
            &newer,
        ) {
            Ok(manifest) => {
                admitted_parts.extend(manifest.parts.iter().map(|part| part.member.clone()));
                newer = manifest;
            }
            Err(error) if environmental_failure(&error) => return Err(error),
            Err(_) => abandoned_older.push(commit),
        }
    }
    Ok(SurvivingHistory { admitted_parts, abandoned_older })
}

/// The retained history that survives beside a promotion candidate.
struct SurvivingHistory {
    /// Parts named by the candidate or by any surviving older revision.
    admitted_parts: HashSet<String>,
    /// Older retained revisions abandoned because they, or the link that would join them to the
    /// survivors, no longer validate. Retention ends for them in the promoting flip.
    abandoned_older: Vec<u64>,
}

/// Prove that `bytes` is the immediate, fully usable predecessor of `newer`: adjacent revision
/// number, valid current-format manifest, the same fold generation, named by `newer`'s `prev`,
/// monotonic cursor and tail, and content that reconstructs at its own tail.
fn validate_retained_predecessor(
    container: &crate::container::Container,
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
    bytes: &[u8],
    newer: &Manifest,
) -> Result<Manifest> {
    let manifest = Manifest::parse(bytes).context("retained manifest revision is invalid")?;
    let expected = newer.commit.checked_sub(1).context("retained revision order underflows")?;
    if manifest.commit != expected {
        bail!(
            "retained revision {} does not immediately precede revision {}",
            manifest.commit,
            newer.commit
        );
    }
    if manifest.fold_gen != newer.fold_gen {
        bail!(
            "retained revision {} references fold generation {} but revision {} references {}",
            manifest.commit,
            manifest.fold_gen,
            newer.commit,
            newer.fold_gen
        );
    }
    let link = blake3::hash(bytes).to_hex().to_string();
    if newer.prev.as_deref() != Some(link.as_str()) {
        bail!(
            "retained revision {} does not name revision {} as its predecessor",
            newer.commit,
            manifest.commit
        );
    }
    if manifest.next_seq > newer.next_seq {
        bail!(
            "retained history moves the record-version cursor backward from {} to {} at revision {}",
            manifest.next_seq,
            newer.next_seq,
            newer.commit
        );
    }
    if (manifest.fold_seg, manifest.fold_off) > (newer.fold_seg, newer.fold_off) {
        bail!(
            "retained history moves the fold tail backward from {:?} to {:?} at revision {}",
            (manifest.fold_seg, manifest.fold_off),
            (newer.fold_seg, newer.fold_off),
            newer.commit
        );
    }
    validate_recovery_candidate_container(
        container,
        path,
        cfg,
        manifest.clone(),
        read_limits,
        control,
    )?;
    Ok(manifest)
}

/// Checked manifest promotion for a single-file store: OS-enforced writer role on native container
/// handles, a
/// healthy refusal by the same rule, candidates validated whole at their exact tails, and
/// promotion as ONE flip that restages `MANIFEST` verbatim and removes the abandoned newer
/// retained members in the same atomic state.
pub fn promote_manifest_file(
    path: &Path,
    cfg: FoldCfg,
    options: ManifestPromotionOptions,
) -> Result<ManifestPromotionReport> {
    promote_manifest_file_with_limits_and_control(
        path,
        cfg,
        options,
        ReadLimits::default(),
        &crate::control::OperationControl::default(),
    )
}

/// [`promote_manifest_file`] with explicit admission and cooperative cancellation; the last
/// checkpoint is immediately before the publishing flip.
pub fn promote_manifest_file_with_limits_and_control(
    path: &Path,
    cfg: FoldCfg,
    options: ManifestPromotionOptions,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<ManifestPromotionReport> {
    debris::validate_store_path(path)?;
    crate::fold::validate_cfg(cfg)?;
    let read_limits = read_limits.validate()?;
    control.check("manifest promotion")?;
    let mut container = crate::container::Container::open_internal_with_limits(path, read_limits)?
        .lock_writer_current()?;
    control.check("manifest promotion")?;
    if container.contains("MANIFEST") {
        let current = container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?;
        if Manifest::parse(&current).is_ok() {
            // Intact current authority alone is not health: retained history that no longer
            // validates refuses every open just as surely, and promotion at rollback zero is the
            // one operation authorized to end retention of what cannot be reopened.
            match verify_chain_container(&container, read_limits, control) {
                Ok(_) => return Err(ManifestPromotionError::Healthy(path.to_path_buf()).into()),
                Err(error) if environmental_failure(&error) => return Err(error),
                Err(_) => {}
            }
        }
    }
    let commits = container_retained_commits(&container);
    let member_names = container.names().map(String::from).collect::<Vec<_>>();
    validate_manifest_promotion_member_namespace(&member_names)?;
    let mut retained_generation = None;
    for &revision in &commits {
        let bytes =
            container.read_file_bounded(&format!("MANIFEST.{revision:08}"), MAX_MANIFEST_BYTES)?;
        let Ok(candidate) = Manifest::parse(&bytes) else { continue };
        if candidate.commit != revision {
            bail!(
                "retained member MANIFEST.{revision:08} contains manifest revision {}",
                candidate.commit
            );
        }
        if let Some(expected) = retained_generation {
            if candidate.fold_gen != expected {
                bail!(
                    "retained manifest history crosses fold generations {expected} and {}; refold must purge its predecessors",
                    candidate.fold_gen
                );
            }
        } else {
            retained_generation = Some(candidate.fold_gen);
        }
    }
    let newest = commits.last().copied().unwrap_or(0);
    let mut examined = 0usize;
    let mut last_reason = "no retained manifests exist".to_string();
    for c in commits.into_iter().rev() {
        control.check("manifest promotion validation")?;
        examined += 1;
        let bytes = container.read_file_bounded(&format!("MANIFEST.{c:08}"), MAX_MANIFEST_BYTES)?;
        let manifest = match Manifest::parse(&bytes) {
            Ok(manifest) => manifest,
            Err(error) => {
                last_reason = error.to_string();
                continue;
            }
        };
        let (cand_gen, cand_seg, cand_off) =
            (manifest.fold_gen, manifest.fold_seg, manifest.fold_off);
        match validate_recovery_candidate_container(
            &container,
            path,
            cfg,
            manifest.clone(),
            read_limits,
            control,
        ) {
            Ok(mut report) => {
                let rollback_commits = newest.saturating_sub(c);
                if rollback_commits > options.max_rollback_commits {
                    return Err(ManifestPromotionError::RollbackLimit {
                        needed: rollback_commits,
                        allowed: options.max_rollback_commits,
                    }
                    .into());
                }
                let history = match validate_surviving_promotion_history(
                    &container,
                    path,
                    cfg,
                    read_limits,
                    control,
                    &manifest,
                ) {
                    Ok(history) => history,
                    Err(error) => {
                        if environmental_failure(&error) {
                            return Err(error);
                        }
                        last_reason = error.to_string();
                        continue;
                    }
                };
                let abandoned: HashSet<u64> = history.abandoned_older.iter().copied().collect();
                // No cancellation checkpoint after this point: promotion is one flip, and its
                // selected authority or an explicit ambiguous-durability error must be reported.
                control.check("manifest promotion publication")?;
                container.put_bytes("MANIFEST", &bytes)?;
                for name in container.names().map(String::from).collect::<Vec<_>>() {
                    if let Some(revision) =
                        name.strip_prefix("MANIFEST.").and_then(|suffix| suffix.parse::<u64>().ok())
                    {
                        if revision > c || abandoned.contains(&revision) {
                            container.remove(&name)?;
                        }
                        continue;
                    }
                    let unreferenced_part = canonical_part_member_shape(&name)
                        && !history.admitted_parts.contains(&name);
                    let abandoned_fold = exact_fold_member_name(&name)
                        && fold_generation_of_member(&name) != Some(cand_gen);
                    if unreferenced_part || abandoned_fold {
                        container.remove(&name)?;
                    }
                }
                // The abandoned commits may have grown the fold past the candidate's tail —
                // advanced its active segment, sealed it, rolled new ones. The promoted state
                // must AGREE with its own manifest, so the same flip truncates the active
                // segment member to the candidate's tail and drops every same-generation
                // member past it. (Rollback across a re-fold cannot happen: a re-fold purges
                // the retained log, so no candidate from the old generation survives.)
                let fold_rel =
                    if cand_gen == 0 { "fold".to_string() } else { format!("fold-{cand_gen:04}") };
                let keep_seg = cand_seg;
                let keep_len = u64::from(cand_off);
                for name in container.names().map(String::from).collect::<Vec<_>>() {
                    let Some(rest) = name.strip_prefix(&format!("{fold_rel}/")) else { continue };
                    if let Some(n) = crate::fold::segment::parse_seg_name(rest) {
                        if n > keep_seg {
                            container.remove(&name)?;
                        } else if n == keep_seg && container.member_len(&name) != Some(keep_len) {
                            let ext = container.extent(&name).ok_or_else(|| {
                                anyhow::anyhow!(
                                    "container lost member {name} during manifest promotion"
                                )
                            })?;
                            container.put_stream(&name, keep_len, |at, into| {
                                crate::readat::ReadAt::read_exact_at(&ext, into, at)
                            })?;
                            // A sidecar describes the sealed segment this member no longer is.
                            container.remove(&format!("{fold_rel}/seg-{n:08}.dir"))?;
                        }
                    } else if let Some(n) = rest
                        .strip_prefix("seg-")
                        .and_then(|r| r.strip_suffix(".dir"))
                        .and_then(|digits| digits.parse::<u32>().ok())
                    {
                        if n > keep_seg {
                            container.remove(&name)?;
                        }
                    }
                }
                let final_names = container.names().map(String::from).collect::<Vec<_>>();
                validate_store_member_namespace(&final_names, Some(&manifest), |name| {
                    container.read_file_bounded(name, MAX_MANIFEST_BYTES)
                })?;
                if let Err(error) = container.commit() {
                    if container.failed_publication_selected() == Some(true) {
                        return Err(error).context(
                            "manifest promotion is selected by the current container state, but its final synchronization failed; reopen to determine crash durability",
                        );
                    }
                    return Err(error).context("publish the promoted manifest revision");
                }
                report.commit = c;
                report.rollback_commits = rollback_commits;
                report.abandoned_retained_revisions = history.abandoned_older.len();
                return Ok(report);
            }
            Err(error) => {
                if environmental_failure(&error) {
                    return Err(error);
                }
                last_reason = error.to_string();
            }
        }
    }
    Err(ManifestPromotionError::NoUsableCandidate { examined, reason: last_reason }.into())
}

/// The home-neutral half of candidate validation: every visible record's every content value
/// reconstructed piece by piece, lengths checked, whole-value identities checked where carried.
fn validate_candidate_records(
    reader: &ReadStore,
    control: &crate::control::OperationControl,
) -> Result<(usize, usize)> {
    let visible = read::visibility(&reader.parts)?;
    let mut records = 0usize;
    let mut content_values = 0usize;
    for (part_index, rows) in visible.rows.iter().enumerate() {
        let part = &reader.parts[part_index];
        for &row in rows {
            control.check("manifest promotion validation")?;
            let record = part.record(row)?;
            records = records
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("candidate record count overflow"))?;
            for content in &record.contents {
                control.check("manifest promotion validation")?;
                // Interpret the program through the owning Part—the same authority ordinary reads
                // use—and hash each literal/piece incrementally rather than allocating the value.
                part.verify_projected_content_with_control(content, &reader.fold, control)?;
                content_values = content_values
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("candidate content count overflow"))?;
            }
        }
    }
    Ok((records, content_values))
}

/// [`validate_recovery_candidate`] for a candidate held as members: the fold opens over extent
/// readers bounded to the candidate's EXACT tail — the active segment sliced to `fold_off`,
/// segments above it excluded entirely — so validation sees precisely the fold the candidate
/// committed, not whatever later commits appended to the same members.
fn validate_recovery_candidate_container(
    c: &crate::container::Container,
    path: &Path,
    cfg: FoldCfg,
    manifest: Manifest,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<ManifestPromotionReport> {
    control.check("manifest promotion validation")?;
    let prefix = crate::fold::fold_member_prefix(manifest.fold_gen);
    let tail = manifest.fold_tail();
    let mut segs = Vec::new();
    let mut dict_files = Vec::new();
    let mut present_segments = HashSet::new();
    let mut sidecars = HashSet::new();
    for name in c.names().map(String::from).collect::<Vec<_>>() {
        let Some(rest) = name.strip_prefix(&format!("{prefix}/")) else { continue };
        if let Some(n) = crate::fold::segment::parse_seg_name(rest) {
            present_segments.insert(n);
            let extent = c.extent(&name).expect("name came from this container");
            let full_len = crate::readat::ReadAt::len(&extent)?;
            let (reader, len, whole): (Arc<dyn crate::readat::ReadAt>, u64, bool) = match tail {
                Some(t) if n > t.seg => continue,
                Some(t) if n == t.seg => (
                    Arc::new(crate::readat::Slice::new(extent, 0, u64::from(t.off))),
                    u64::from(t.off),
                    u64::from(t.off) == full_len,
                ),
                _ => (Arc::new(extent), full_len, true),
            };
            segs.push(crate::fold::SegmentInput {
                seg: n,
                reader,
                // A sidecar describes a segment's full length; for a candidate-bounded segment
                // it would fail its own staleness gate, so it is only offered when whole.
                sidecar: if whole {
                    container_sidecar_bytes(
                        c,
                        &format!("{prefix}/seg-{n:08}.dir"),
                        len,
                        read_limits,
                    )?
                } else {
                    None
                },
            });
        } else if let Some(number) = fold_sidecar_member(rest) {
            sidecars.insert(number);
        } else if valid_fold_dictionary_member(rest) {
            let bytes = c.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?;
            let exact = format!("zdict-{}.zd", PieceHash::of(&bytes).to_hex());
            if rest != exact {
                bail!("fold dictionary member {name:?} does not match its content identity");
            }
            dict_files.push(bytes);
        } else {
            bail!("container member {name:?} is not in the current fold namespace");
        }
    }
    if let Some(orphan) = sidecars.iter().find(|number| !present_segments.contains(number)) {
        bail!("fold sidecar seg-{orphan:08}.dir has no corresponding segment");
    }
    if let Some(tail) = tail {
        if !present_segments.contains(&tail.seg) {
            bail!("manifest-promotion candidate tail names absent segment {}", tail.seg);
        }
    }
    let fold = Fold::open_read_from_with_limits(
        segs,
        dict_files,
        cfg,
        path,
        &manifest.punched,
        read_limits,
    )?;
    let scrub = fold.scrub_with_control(control)?;
    let pcache = SectionCache::shared();
    let mut parts = Vec::with_capacity(manifest.parts.len());
    let mut part_sections = 0usize;
    for part_ref in &manifest.parts {
        control.check("manifest promotion validation")?;
        let reader = c.extent(&part_ref.member).ok_or_else(|| {
            anyhow::anyhow!(
                "candidate commit {} names part {} but the container does not hold it",
                manifest.commit,
                part_ref.member
            )
        })?;
        let got = hash_reader_with_control(&reader, control, "manifest promotion validation")?
            .to_hex()
            .to_string();
        if got != part_ref.b3 {
            bail!(
                "candidate commit {} names part {} with the wrong digest",
                manifest.commit,
                part_ref.member
            );
        }
        let part =
            Arc::new(open_manifest_part(Box::new(reader), part_ref, pcache.clone(), read_limits)?);
        part_sections += part.verify_sections_with_control(control)?;
        part.verify_semantics_with_control(control)?;
        part.verify_piece_dictionary_with_control(&fold, control)?;
        parts.push(part);
    }
    let reader = ReadStore { fold: Arc::new(fold), parts, manifest, read_limits };
    let (records, content_values) = validate_candidate_records(&reader, control)?;
    Ok(ManifestPromotionReport {
        records,
        content_values,
        parts: reader.parts.len(),
        part_sections,
        fold_segments: scrub.segments,
        fold_blocks: scrub.blocks,
        fold_bytes: scrub.bytes,
        ..ManifestPromotionReport::default()
    })
}

/// Hash bytes that live behind a bounded reader.
fn hash_reader_with_control(
    reader: &dyn crate::readat::ReadAt,
    control: &crate::control::OperationControl,
    operation: &'static str,
) -> Result<blake3::Hash> {
    let len = reader.len()?;
    let mut hasher = blake3::Hasher::new();
    let mut buf = vec![0u8; 1 << 20];
    let mut at = 0u64;
    while at < len {
        control.check(operation)?;
        let take = buf.len().min((len - at) as usize);
        reader.read_exact_at(&mut buf[..take], at)?;
        hasher.update(&buf[..take]);
        at += take as u64;
    }
    Ok(hasher.finalize())
}

/// `<store>` is absent and `<store>.reclaimed` — a reclaim's anchor — is present: reinstate the
/// anchor to the store's name, or refuse. One contender at a time: the anchor's own writer lock
/// is the exclusion, so a second recoverer sees `WriterLocked`. The anchor is validated whole
/// (fold at its tail scrubbed, every part by digest and sections, every record reconstructed —
/// the same bar as manifest promotion) BEFORE anything is created; a corrupt or incomplete anchor
/// refuses and leaves everything as found. Reinstatement is a copy to a fresh candidate, fsynced,
/// writer-locked, and placed at `<store>` by a write-through no-replace rename — a name taken
/// meanwhile refuses with the anchor intact — after which the anchor is unlinked (laggable). A
/// crash at any point re-enters here on the next writer open and converges.
fn restore_store_from_reclaim_anchor(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<()> {
    let names = crate::container::reclaim_names(path);
    let anchor = crate::container::Container::open_internal_with_limits(&names.anchor, read_limits)
        .with_context(|| format!("open reclaim anchor {}", names.anchor.display()))?
        .lock_writer_current()
        .with_context(|| "another interrupted-reclaim restoration is in progress")?;
    let control = crate::control::OperationControl::default();
    verify_container_artifact(&names.anchor, cfg, read_limits, &control).with_context(|| {
        format!(
            "reclaim anchor {} does not validate whole; the store is not recreated from it",
            names.anchor.display()
        )
    })?;
    if !anchor.is_current_path_file(&names.anchor)? {
        bail!("reclaim anchor changed identity while it was being validated");
    }
    let parent = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
    crate::vfs::unlink_if_exists(&names.candidate_tmp).with_context(|| {
        format!("remove stale reclaim candidate {}", names.candidate_tmp.display())
    })?;
    crate::vfs::unlink_if_exists(&names.candidate)
        .with_context(|| format!("remove stale reclaim candidate {}", names.candidate.display()))?;
    crate::container::copy_container_bytes_pub(&names.anchor, &names.candidate_tmp)?;
    crate::vfs::sync_dir(&parent)?;
    crate::vfs::rename_noreplace(&names.candidate_tmp, &names.candidate)?;
    crate::vfs::sync_dir(&parent)?;
    let new_store = crate::vfs::open_rw(&names.candidate)?;
    if !crate::sys::lock_exclusive(&new_store)? {
        return Err(crate::fold::WriterLocked { path: names.candidate.clone() }.into());
    }
    verify_container_artifact(&names.candidate, cfg, read_limits, &control)?;
    crate::vfs::rename_noreplace(&names.candidate, path).with_context(|| {
        format!("{} was taken while the reclaim anchor was being promoted", path.display())
    })?;
    crate::vfs::sync_dir(&parent)?;
    drop(anchor);
    crate::vfs::unlink_if_exists(&names.anchor)
        .with_context(|| format!("remove reclaim anchor {}", names.anchor.display()))?;
    crate::vfs::sync_dir(&parent)
        .with_context(|| format!("sync {} after removing the reclaim anchor", parent.display()))?;
    drop(new_store);
    Ok(())
}

/// The retained manifest revisions a single-file store holds, oldest first — the revisions
/// [`open_read_container_at`] can still serve.
pub fn retained_commits_file(path: &Path) -> Result<Vec<u64>> {
    let c = crate::container::Container::open(path)?;
    verify_chain_container(
        &c,
        ReadLimits::default(),
        &crate::control::OperationControl::default(),
    )?;
    Ok(container_retained_commits(&c))
}

/// Verify a single-file store's retained manifest chain: prev-links across the retained
/// members, every part pin hashed against the extents the file actually holds, and the live
/// manifest checked byte-identical to its newest retained copy.
pub fn verify_chain_file(path: &Path) -> Result<ChainReport> {
    let c = crate::container::Container::open(path)?;
    verify_chain_container(&c, ReadLimits::default(), &crate::control::OperationControl::default())
}

/// Restore a single-file backup: copy `src` into staging, fully verify that exact staged store,
/// then install it at `dst` with a rename that refuses to replace. The backup is itself a store,
/// so restoring is verified copying, and a crash leaves staging litter and an untouched
/// destination.
pub fn restore_file(src: &Path, dst: &Path) -> Result<crate::backup::RestoreStats> {
    restore_file_with_control_and_limits(
        src,
        dst,
        ReadLimits::default(),
        &crate::control::OperationControl::default(),
    )
}

/// [`restore_file`] with explicit admission limits for the staged artifact.
pub fn restore_file_with_limits(
    src: &Path,
    dst: &Path,
    read_limits: ReadLimits,
) -> Result<crate::backup::RestoreStats> {
    restore_file_with_control_and_limits(
        src,
        dst,
        read_limits,
        &crate::control::OperationControl::default(),
    )
}

/// [`restore_file`] with cooperative cancellation; the last checkpoint is immediately before the
/// installing rename, and a cancelled restore removes its staging and never installs.
pub fn restore_file_with_control(
    src: &Path,
    dst: &Path,
    control: &crate::control::OperationControl,
) -> Result<crate::backup::RestoreStats> {
    restore_file_with_control_and_limits(src, dst, ReadLimits::default(), control)
}

/// [`restore_file`] with both explicit staged-artifact admission and cooperative cancellation.
pub fn restore_file_with_control_and_limits(
    src: &Path,
    dst: &Path,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<crate::backup::RestoreStats> {
    let read_limits = read_limits.validate()?;
    debris::validate_store_path(src)?;
    debris::validate_store_path(dst)?;
    control.check("backup restore")?;
    crate::backup::ensure_destination_available(dst)?;
    let staging = artifact_staging_path(dst, "restoring");
    crate::backup::ensure_source_is_not_staging(src, &staging)?;
    // The copy goes through the vfs seam in bounded chunks and is fsynced before anything
    // depends on it: the installing rename must never make bytes reachable that a crash could
    // still take back — and a copy the crash simulator cannot see is a copy the crash-safety
    // argument does not cover.
    let mut uninstalled = {
        use std::io::Read;
        let mut from =
            crate::vfs::open_read(src).with_context(|| format!("open backup {}", src.display()))?;
        let to = crate::vfs::create_new_staging(&staging)
            .with_context(|| format!("stage restore at {}", staging.display()))?;
        let cleanup = UninstalledArtifact::new(staging.clone());
        let mut buf = vec![0u8; 1 << 20];
        let mut at = 0u64;
        loop {
            let n = from.read(&mut buf)?;
            if n == 0 {
                break;
            }
            crate::vfs::write_all_at(&to, &staging, &buf[..n], at)?;
            at += n as u64;
        }
        crate::vfs::sync_file(&to, &staging)?;
        cleanup
    };
    let (members, bytes, commit, _) =
        verify_container_artifact(&staging, FoldCfg::default(), read_limits, control)
            .with_context(|| format!("verify staged restore {}", staging.display()))?;
    control.check("backup restore installation")?;
    crate::vfs::rename_noreplace(&staging, dst)?;
    uninstalled.installed();
    if let Some(parent) = dst.parent() {
        crate::vfs::sync_dir(parent).with_context(|| {
            format!("sync {} after installing {}", parent.display(), dst.display())
        })?;
    }
    Ok(crate::backup::RestoreStats { members, bytes, commit })
}

/// Retained commit numbers held as `MANIFEST.NNNNNNNN` members, parsed numerically exactly as
/// their file forms are, ascending.
fn container_retained_commits(c: &crate::container::Container) -> Vec<u64> {
    let mut commits: Vec<u64> = c
        .names()
        .filter_map(|name| name.strip_prefix("MANIFEST."))
        .filter(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
        .filter_map(|rest| rest.parse::<u64>().ok())
        .collect();
    commits.sort_unstable();
    commits
}

/// The fold generation a member name belongs to, if it is a fold member at all.
fn fold_generation_of_member(name: &str) -> Option<u32> {
    let (prefix, _) = name.split_once('/')?;
    if prefix == "fold" {
        Some(0)
    } else {
        let digits = prefix.strip_prefix("fold-")?;
        if digits.len() == 4 && digits.bytes().all(|b| b.is_ascii_digit()) {
            digits
                .parse::<u32>()
                .ok()
                .filter(|generation| (1..=crate::fold::MAX_FOLD_GENERATION).contains(generation))
        } else {
            None
        }
    }
}

/// Fold segment members whose outer container checksum was intentionally invalidated by content
/// punch. Their frame-level validation remains mandatory; only the redundant whole-member CRC is
/// inapplicable after an authorized payload has been deallocated or partially deallocated.
pub(crate) fn verified_punched_fold_members(
    container: &crate::container::Container,
    cfg: FoldCfg,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<HashSet<String>> {
    if !container.contains("MANIFEST") {
        return Ok(HashSet::new());
    }
    let manifest = Manifest::parse(&container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?;
    if manifest.punched.is_empty() {
        return Ok(HashSet::new());
    }
    let fold = open_fold_from_container(container, &manifest, cfg, container.path(), read_limits)?;
    fold.scrub_with_control(control)?;
    let prefix = crate::fold::fold_member_prefix(manifest.fold_gen);
    let punched =
        |block_id: u32| manifest.punched.iter().any(|&(lo, hi)| (lo..=hi).contains(&block_id));
    Ok(fold
        .block_inventory_with_control(control)?
        .into_iter()
        .filter(|block| punched(block.block_id))
        .map(|block| format!("{prefix}/{}", crate::fold::segment::seg_name(block.segment)))
        .collect())
}

/// The sweep's single-file form: move members no manifest — live or retained — names onto the
/// free list. Same keep-set rule as the directory sweep, with "unlink" replaced by "free": the
/// bytes stay where they are, never reused, reclaimable by punch or rewrite. Staged only; the
/// caller's flip publishes the frees with everything else.
fn sweep_unreachable_container(
    c: &mut crate::container::Container,
    live: &Manifest,
    _read_limits: ReadLimits,
) -> Result<()> {
    let mut keep_parts: std::collections::HashSet<String> =
        live.parts.iter().map(|p| p.member.clone()).collect();
    let mut keep_gens: std::collections::HashSet<u32> = std::iter::once(live.fold_gen).collect();
    for commit in container_retained_commits(c) {
        let name = format!("MANIFEST.{commit:08}");
        let bytes = c
            .read_file_bounded(&name, MAX_MANIFEST_BYTES)
            .with_context(|| format!("read retained manifest {commit} before member sweep"))?;
        let m = Manifest::parse(&bytes)
            .with_context(|| format!("validate retained manifest {commit} before member sweep"))?;
        keep_parts.extend(m.parts.into_iter().map(|p| p.member));
        keep_gens.insert(m.fold_gen);
    }
    let names: Vec<String> = c.names().map(String::from).collect();
    for name in names {
        let unreachable = if name.starts_with("part-") && name.ends_with(".part") {
            !keep_parts.contains(&name)
        } else if let Some(gen) = fold_generation_of_member(&name) {
            !keep_gens.contains(&gen)
        } else {
            false
        };
        if unreachable {
            c.remove(&name)?;
        }
    }
    Ok(())
}

/// The WAL a single-file store keeps beside it while hot: `<store>.turndb-wal`, mirroring
/// SQLite's `-wal`. Present at open means a crash; removed on clean close.
fn file_wal_path(store: &Path) -> PathBuf {
    let mut p = store.as_os_str().to_os_string();
    p.push("-wal");
    PathBuf::from(p)
}

/// The transient scratch directory a single-file store's maintenance uses for merge spools:
/// `<store>.turndb-tmp/`. Exists only while an operation runs; never holds durable state; swept
/// whole at writer open, which is what makes crashed-merge cleanup O(1) instead of a scan of
/// whatever directory the store file happens to live in.
fn file_tmp_dir(store: &Path) -> PathBuf {
    let mut p = store.as_os_str().to_os_string();
    p.push("-tmp");
    PathBuf::from(p)
}

pub struct Store {
    path: PathBuf,
    container: std::sync::Arc<std::sync::Mutex<crate::container::Container>>,
    fold: Fold,
    parts: Vec<Arc<Part>>,
    manifest: Manifest,
    /// Uncommitted records, last-write-wins by id.
    /// Uncommitted records. `None` is a staged DELETION — it must be a value rather than an absence,
    /// because it has to shadow whatever older parts still say about the id.
    mem: BTreeMap<String, Option<Record>>,
    mem_bytes: usize,
    wal: Wal,
    cfg: FoldCfg,
    write_limits: WriteLimits,
    read_limits: ReadLimits,
    retained_commit_count: usize,
    /// ONE budget for every part in this store, not one per part. Section caches are what make a
    /// whole-part walk linear, so they cannot be removed — but unbounded they pinned 9.5x each part's
    /// on-disk size, which is a per-part cost that multiplies by part count.
    pcache: Arc<SectionCache>,
    metrics: crate::observability::StoreMetrics,
    events: crate::observability::EventJournal,
    /// Fold state may already contain content for a mutation whose WAL append failed. Reusing that
    /// dedup state could let a later WAL frame omit bytes replay cannot find, so only reopen may
    /// discard the unpublished fold tail and restore a coherent acceptance boundary.
    requires_reopen: bool,
}

/// Cheap operational state for an embedder's health and metrics endpoint.
///
/// This reports engine facts, not a telemetry format or consumer policy. Counters that require a
/// full visibility walk (for example exact live-record count) are deliberately absent from this
/// cheap snapshot rather than hidden behind a surprisingly expensive getter.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StoreHealth {
    /// Public store-authority encoding: zero is the canonical origin; a positive value is the
    /// current manifest revision.
    pub commit: u64,
    pub fold_generation: u32,
    pub parts: usize,
    pub part_rows: u64,
    pub memtable_entries: usize,
    pub memtable_bytes: usize,
    pub wal_bytes: u64,
    pub wal_frames: u64,
    pub fold_disk_bytes: u64,
    pub fold_segments: u32,
    pub fold_cache_hits: u64,
    pub fold_cache_misses: u64,
    pub fold_cache_bytes: usize,
    pub fold_cache_budget: usize,
    pub fold_block_target_bytes: usize,
    pub fold_segment_max_bytes: u32,
    pub fold_compression_level: i32,
    pub fold_compression_threads: usize,
    pub part_cache_bytes: usize,
    pub part_cache_budget: usize,
    pub max_stored_frame_bytes: u64,
    pub max_decoded_frame_bytes: u64,
    pub max_directory_entries: u64,
    pub max_wal_frames: u64,
    pub max_fold_blocks: u64,
    pub dedup_window_entries: usize,
    pub retained_commits: usize,
    pub punched_blocks: u64,
}

/// Member bytes in one reachability class.
///
/// `logical_bytes` is portable member length. `allocated_bytes` is `None` until single-file extent
/// attribution can report real filesystem allocation rather than inventing a structural zero.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SpaceAmount {
    pub members: usize,
    pub logical_bytes: u64,
    pub allocated_bytes: Option<u64>,
}

/// Exact reachability-aware storage facts for preflight and operational reporting.
///
/// Categories are disjoint. `retained_only` is not garbage: bounded time-travel manifests still
/// require it. `unclassified` is deliberately not called reclaimable: it includes both unnamed
/// free extents and named members for which neither live nor retained manifest grants authority.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StoreSpaceUsage {
    pub live: SpaceAmount,
    pub retained_only: SpaceAmount,
    pub unclassified: SpaceAmount,
    pub total: SpaceAmount,
    /// Bytes available to the current user on the containing filesystem, or `None` when unavailable.
    pub filesystem_available_bytes: Option<u64>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// Space facts and an explicitly advisory duplicate-generation estimate for refold.
pub struct RefoldSpaceEstimate {
    pub source_fold_logical_bytes: u64,
    pub source_part_bytes: u64,
    pub source_part_sections: usize,
    pub source_part_raw_section_bytes: u64,
    pub retained_only_bytes_before: u64,
    pub estimated_stage_bytes: u64,
    pub estimate_is_hard_bound: bool,
    pub filesystem_available_bytes: Option<u64>,
}

/// Refuse an inverted scan range before it reaches `BTreeMap::range`, which PANICS on
/// `start > end` rather than returning empty.
///
/// The corruption storm holds every on-disk parser to "errors, never panics". That discipline was
/// applied rigorously to bytes on disk and not at all to API arguments — so a store that refuses to
/// panic on a corrupt file would panic on a reversed range, which draws the trust boundary in the
/// wrong place: disk bytes are hostile, but the embedder is merely capable of being mistaken, and
/// only one of those can be fixed by refusing. Equal bounds are a legitimately empty half-open
/// range and are allowed.
fn check_range(from: Option<&str>, to: Option<&str>) -> Result<()> {
    if let (Some(f), Some(t)) = (from, to) {
        if f > t {
            bail!("scan range is inverted: from {f:?} sorts after to {t:?}");
        }
    }
    Ok(())
}

impl Store {
    /// Part count at which [`Store::auto_compact`] runs a total merge. Chosen by measurement, not
    /// taste — see that method's numbers.
    pub const AUTO_COMPACT_K: usize = 8;

    fn ensure_writer_usable(&self) -> Result<()> {
        if self.requires_reopen {
            bail!("writer requires reopen after a failed staged operation");
        }
        self.fold.ensure_no_failed_write()?;
        self.container.lock().expect("container lock poisoned").ensure_store_writer_usable()
    }

    fn discard_staged_and_require_reopen(
        &mut self,
        operation: &str,
        error: anyhow::Error,
    ) -> anyhow::Error {
        self.requires_reopen = true;
        match self.container.lock().expect("container lock poisoned").discard_staged() {
            Ok(()) => error.context(format!(
                "{operation} failed after staging began; staged authority discarded and writer requires reopen"
            )),
            Err(cleanup) => cleanup.context(format!(
                "{operation} failed ({error:#}); discarding its staged authority also failed and writer requires reopen"
            )),
        }
    }

    /// Open a writer over the single-file store — THE way a store opens for writing.
    ///
    /// `path` names a container; an absent path becomes a new, empty store. Beside it while open:
    /// `<path>-wal`, replayed here if a crash left it. Native writer exclusion uses `flock` on Unix
    /// and `LockFileEx` on Windows, on the container handle, and is OS-released on death.
    pub fn open_file(path: &Path, cfg: FoldCfg) -> Result<Store> {
        Self::open_file_with_options(path, StoreOptions { fold: cfg, ..StoreOptions::default() })
    }

    /// [`Store::open_file`] with explicit write-admission policy.
    pub fn open_file_with_limits(
        path: &Path,
        cfg: FoldCfg,
        write_limits: WriteLimits,
    ) -> Result<Store> {
        Self::open_file_with_options(
            path,
            StoreOptions { fold: cfg, write_limits, ..StoreOptions::default() },
        )
    }

    /// [`Store::open_file`] with explicit storage, cache, and admission configuration.
    pub fn open_file_with_options(path: &Path, options: StoreOptions) -> Result<Store> {
        let recovery_started = std::time::Instant::now();
        let StoreOptions {
            fold: cfg,
            write_limits,
            read_limits,
            part_cache_bytes,
            open_verification,
        } = options;
        debris::validate_store_path(path)?;
        crate::fold::validate_cfg(cfg)?;
        let write_limits = write_limits.validate()?;
        let read_limits = read_limits.validate()?;
        if part_cache_bytes < crate::part::cache::BUDGET_MIN {
            bail!("part_cache_bytes must be at least {}", crate::part::cache::BUDGET_MIN);
        }
        if path.is_dir() {
            bail!("{} is a directory; a TurnDB store is one current-format file", path.display());
        }
        let reclaim = crate::container::reclaim_names(path);
        if !path.exists() && !reclaim.anchor.exists() {
            // Transient names beside an ABSENT store — a pending publish that never landed,
            // reclaim material without its anchor — are not proven dead, so nothing is removed;
            // the ones that mean "a store was being published here" refuse creation.
            let refusing = debris::names_refusing_creation(path, read_limits)?;
            if !refusing.is_empty() {
                bail!(
                    "{} is absent but transient files sit beside it ({}); not creating a new \
                     store over them — inspect and remove them first",
                    path.display(),
                    refusing.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
                );
            }
        }
        if !path.exists() && reclaim.anchor.exists() {
            // A reclaim's replace crashed in the state the ANCHOR protocol admits — the store's
            // name gone, the anchor intact. That protocol runs where a replace over an open
            // destination is not durable (`sys::replace_open_durability`), but the anchor is a
            // file beside the store and travels with it, so interrupted-reclaim completion runs on
            // every platform. Restore from the anchor, or refuse; never create.
            restore_store_from_reclaim_anchor(path, cfg, read_limits)?;
        }
        let container = if !path.exists() {
            if let Some(parent) = path.parent() {
                if !parent.as_os_str().is_empty() {
                    crate::vfs::mkdir_all(parent)?;
                }
            }
            crate::container::Container::create_internal_with_limits(path, read_limits)?
        } else {
            crate::container::Container::open_internal_with_limits(path, read_limits)?
        };
        let container = container.lock_writer_current()?;

        // The manifest is a member. Missing means a new store — UNLESS retained commits exist,
        // This store has committed before
        // and MANIFEST was lost, and opening it as new buries the loss.
        let manifest = if container.contains("MANIFEST") {
            let bytes = container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?;
            verification_integrity("open current manifest revision", Manifest::parse(&bytes))?
        } else {
            if container.committed_is_empty_birth() {
                Manifest::default()
            } else {
                return verification_integrity(
                    "open current manifest revision",
                    Err(anyhow::anyhow!(
                        "container {} has no MANIFEST authority but is not the exact empty \
                         sequence-zero birth state",
                        path.display(),
                    )),
                );
            }
        };
        // Validate every structure referenced by current authority and the complete current WAL
        // before any cleanup or writer-open mutation. An unknown/corrupt artifact is refused byte-for-
        // byte, including its adjacent evidence.
        let current = verification_integrity(
            "preflight current store authority",
            open_read_container_handle(&container, cfg, path, read_limits),
        )?;
        let wal_path = file_wal_path(path);
        let mut replay = Wal::replay_state_with_limits(&wal_path, read_limits)?;
        verification_integrity(
            "preflight WAL content identities",
            verify_replay_identities(&replay.frames, &current),
        )?;
        let verification_control = crate::control::OperationControl::default();
        // Publication can become current before the now-redundant WAL prefix is truncated. Its
        // frames remain integrity input above, but they are already represented by the current
        // manifest and must not become pending record versions or be published a second time.
        if manifest.commit != 0 {
            replay.frames.retain(|frame| frame.seq != manifest.next_seq);
        }
        let deep = open_verification == OpenVerification::Deep;
        let chain = verification_integrity(
            "preflight retained manifest chain",
            verify_chain_container_scoped(&container, read_limits, &verification_control, deep),
        )?;
        if deep {
            verification_integrity(
                "preflight complete current store authority",
                verify_committed_store(&current.parts, &current.fold, chain, &verification_control),
            )?;
            verification_integrity(
                "preflight retained-authority piece dictionaries",
                verify_retained_piece_dictionaries(
                    &container,
                    path,
                    cfg,
                    read_limits,
                    &verification_control,
                ),
            )?;
        }
        drop(current);
        let retained_commit_count = container_retained_commits(&container).len();
        let container = std::sync::Arc::new(std::sync::Mutex::new(container));

        // No residue reconciliation and no fold truncation: a retained manifest revision newer than
        // current cannot exist (one flip names everything), and the selected extent lists are the
        // complete authority. No writer-open mutation begins until current state and WAL validate.
        let fold = verification_integrity(
            "open fold referenced by current authority",
            Fold::open_container_writer(
                container.clone(),
                manifest.fold_gen,
                cfg,
                manifest.fold_tail(),
                &manifest.punched,
                read_limits,
            ),
        )?;

        let pcache = Arc::new(SectionCache::new(part_cache_bytes));
        let mut parts = Vec::with_capacity(manifest.parts.len());
        for p in &manifest.parts {
            let reader =
                container.lock().expect("container lock poisoned").extent(&p.member).ok_or_else(
                    || {
                        anyhow::anyhow!(
                            "MANIFEST names part {} but {} does not hold it",
                            p.member,
                            path.display()
                        )
                    },
                )?;
            parts.push(Arc::new(verification_integrity(
                "open committed part",
                open_manifest_part(Box::new(reader), p, pcache.clone(), read_limits),
            )?));
        }

        // Only now has every committed storage plane and WAL frame proved intelligible.
        let debris_removed = debris::remove_beside_present_store(path, read_limits)?;

        // No member sweep here: the selected container state was already proved to name only
        // members some current or retained manifest revision requires, so there is nothing to
        // free. Every publication that prunes retention frees what it stops retaining in the same
        // container state, which is what keeps that proof true.
        // A crashed merge leaves its spool scratch beside the store — pre-commit garbage, removed
        // whole. The member it was assembling is uncommitted noise needing nothing.
        let tmp_dir = file_tmp_dir(path);
        if tmp_dir.exists() {
            let _ = crate::vfs::remove_tree(&tmp_dir);
        }

        let recovered_wal_frames = u64::try_from(replay.frames.len()).unwrap_or(u64::MAX);
        let physical_wal_frames = replay.physical_frames;
        let valid_wal_bytes = replay.valid_bytes;
        let mut mem: BTreeMap<String, Option<Record>> = BTreeMap::new();
        let mut mem_bytes = 0usize;
        let mut fold = fold;
        for f in replay.frames {
            for (h, bytes) in &f.novel {
                // Resolve through both tiers before re-folding, exactly as the write path does.
                // The crash window between the flip and the WAL truncate replays frames whose
                // pieces the just-committed part already holds; re-appending them would leak the
                // bytes into the file for nothing.
                let mut known = fold.lookup(*h).is_some();
                if !known {
                    for part in parts.iter().rev() {
                        if let Some(location) = part.find_piece(h)? {
                            if !fold.is_punched(location.block_id) {
                                known = true;
                                break;
                            }
                        }
                    }
                }
                if !known {
                    let put = fold.put_hashed(bytes, *h)?;
                    debug_assert_eq!(put.hash, *h);
                }
            }
            mem_bytes += approx_bytes(&f.record);
            if f.tomb {
                mem.insert(f.record.id, None);
            } else {
                mem.insert(f.record.id.clone(), Some(f.record));
            }
        }
        let wal =
            Wal::open_recovered(&wal_path, read_limits, physical_wal_frames, valid_wal_bytes)?;

        let mut metrics = crate::observability::StoreMetrics {
            recovered_wal_frames,
            debris_removed,
            ..crate::observability::StoreMetrics::default()
        };
        let recovery_duration = recovery_started.elapsed();
        metrics.open_wal_replay.observe_success(recovery_duration);
        let mut events = crate::observability::EventJournal::default();
        let recovery_result: Result<()> = Ok(());
        events.observe(
            crate::observability::LifecycleOperation::OpenWalReplay,
            recovery_duration,
            &recovery_result,
        );
        Ok(Store {
            path: path.to_path_buf(),
            container,
            fold,
            parts,
            manifest,
            mem,
            mem_bytes,
            wal,
            cfg,
            write_limits,
            read_limits,
            retained_commit_count,
            pcache,
            metrics,
            events,
            requires_reopen: false,
        })
    }

    /// Settle and release this writer. For a single-file store this is what leaves exactly one
    /// file at rest: the memtable flushes if it holds anything, and the emptied WAL sidecar is
    /// removed. A store dropped without closing keeps its sidecar — present-at-open means crash,
    /// and the next open replays it — so close is a tidy, never a requirement.
    pub fn close(mut self) -> Result<()> {
        self.ensure_writer_usable()?;
        if !self.mem.is_empty() {
            self.flush()?;
        }
        // Close completes any delayed publication acknowledgement even when the selected
        // successor came from WAL-free maintenance such as merge or refold.
        self.container.lock().expect("container lock poisoned").acknowledge_current_state()?;
        if self.mem.is_empty() && self.wal.frame_count() != 0 {
            // A publication can succeed before WAL truncation reports a barrier failure. The
            // handle has already adopted the manifest and cleared the pending set in that case;
            // retrying close must finish settling the now-redundant WAL rather than return success
            // with a nonempty sidecar.
            self.wal.truncate()?;
        }
        if self.wal.frame_count() == 0 {
            let wal_path = file_wal_path(&self.path);
            match crate::vfs::unlink(&wal_path) {
                Ok(()) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(error).with_context(|| {
                        format!("remove settled write-ahead log {}", wal_path.display())
                    });
                }
            }
            if let Some(parent) = wal_path.parent() {
                // "Exactly one file" is close's promise; it is not durable if this fails.
                crate::vfs::sync_dir(parent).with_context(|| {
                    format!("sync {} after removing the write-ahead log", parent.display())
                })?;
            }
        }
        Ok(())
    }

    /// The policy governing future writes through this handle.
    pub fn write_limits(&self) -> WriteLimits {
        self.write_limits
    }

    /// Atomic persisted-frame admission governing this handle.
    pub fn read_limits(&self) -> ReadLimits {
        self.read_limits
    }

    /// The fold configuration this writer was opened with, so an embedder deriving a reader from
    /// a live writer inherits cache and block policy instead of silently reverting to defaults.
    pub fn fold_cfg(&self) -> FoldCfg {
        self.cfg
    }

    fn note_manifest_commit(&mut self) {
        self.retained_commit_count =
            self.retained_commit_count.saturating_add(1).min(MANIFEST_RETAIN);
    }

    /// A referenced part's logical member size.
    fn part_member_bytes(&self, member: &str) -> Result<u64> {
        self.container.lock().expect("container lock poisoned").member_len(member).ok_or_else(
            || anyhow::anyhow!("MANIFEST names part {member} but the container does not hold it"),
        )
    }

    /// Directory containing the store, where filesystem capacity is measured.
    fn fs_probe_path(&self) -> &Path {
        self.path.parent().unwrap_or_else(|| Path::new("."))
    }

    /// Monotonic, process-lifetime operation metrics for this writer handle.
    pub fn metrics(&self) -> crate::observability::StoreMetrics {
        self.metrics
    }

    /// Read retained lifecycle outcomes after an independent consumer cursor.
    ///
    /// Reads are non-destructive. `gap` reports that the requested next sequence aged out of the
    /// bounded journal; `dropped_events` is cumulative for this handle.
    pub fn lifecycle_events_after(
        &self,
        after_sequence: u64,
        limit: usize,
    ) -> crate::observability::LifecycleEventBatch {
        self.events.read_after(after_sequence, limit)
    }

    fn observe_lifecycle<T>(
        &mut self,
        operation: crate::observability::LifecycleOperation,
        duration: std::time::Duration,
        result: &Result<T>,
    ) {
        use crate::observability::LifecycleOperation;
        match operation {
            LifecycleOperation::OpenWalReplay => {
                self.metrics.open_wal_replay.observe(duration, result)
            }
            LifecycleOperation::Sync => self.metrics.sync.observe(duration, result),
            LifecycleOperation::Flush => self.metrics.flush.observe(duration, result),
            LifecycleOperation::Merge => self.metrics.merge.observe(duration, result),
            LifecycleOperation::Backup => self.metrics.backup.observe(duration, result),
            LifecycleOperation::Verification => self.metrics.verification.observe(duration, result),
            LifecycleOperation::ContentPunch => {
                self.metrics.content_punch.observe(duration, result)
            }
            LifecycleOperation::Refold => self.metrics.refold.observe(duration, result),
            LifecycleOperation::Erase => self.metrics.erase.observe(duration, result),
        }
        self.events.observe(operation, duration, result);
    }

    /// Verify the retained manifest chain, every selected immutable-part section, and every fold frame.
    ///
    /// This covers current store authority only. A writer that wants the report to include its
    /// pending change set must synchronize and publish first. Failures are classified at this integrity boundary and
    /// recorded in [`Store::metrics`].
    pub fn verify(&mut self) -> Result<StoreVerification> {
        self.verify_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::verify`] with cooperative checkpoints between bounded verification units.
    pub fn verify_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<StoreVerification> {
        let started = std::time::Instant::now();
        let result = self.verify_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Verification,
            started.elapsed(),
            &result,
        );
        if result.as_ref().err().is_some_and(|error| {
            crate::error::classify(error) == crate::error::ErrorClass::Corruption
        }) {
            self.metrics.verification_corruption_failures =
                self.metrics.verification_corruption_failures.saturating_add(1);
        }
        result
    }

    fn verify_inner_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<StoreVerification> {
        control.check("store verification")?;
        // The writer fold may contain pieces accepted into the pending change set. Verification
        // observes one selected store authority, never writer staging.
        let container =
            crate::container::Container::open_internal_with_limits(&self.path, self.read_limits)?;
        let chain = verification_integrity(
            "verify retained manifest chain",
            verify_chain_container(&container, self.read_limits, control),
        )?;
        let selected = verification_integrity(
            "open selected store authority for verification",
            open_read_container_handle(&container, self.cfg, &self.path, self.read_limits),
        )?;
        verification_integrity(
            "verify retained-authority piece dictionaries",
            verify_retained_piece_dictionaries(
                &container,
                &self.path,
                self.cfg,
                self.read_limits,
                control,
            ),
        )?;
        drop(container);
        verify_committed_store(&selected.parts, &selected.fold, chain, control)
    }

    /// Exact member-size and physical-row distribution for the current live immutable parts.
    pub fn part_distribution(&self) -> Result<crate::observability::PartDistribution> {
        self.part_distribution_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::part_distribution`] with cooperative checkpoints between part metadata reads.
    pub fn part_distribution_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<crate::observability::PartDistribution> {
        control.check("part distribution")?;
        let mut bytes = Vec::with_capacity(self.manifest.parts.len());
        let mut rows = Vec::with_capacity(self.manifest.parts.len());
        let mut total_bytes = 0u64;
        let mut total_rows = 0u64;
        for part in &self.manifest.parts {
            control.check("part distribution")?;
            let size = self.part_member_bytes(&part.member)?;
            let part_rows = u64::from(part.records);
            total_bytes = total_bytes
                .checked_add(size)
                .ok_or_else(|| anyhow::anyhow!("part distribution byte count overflow"))?;
            total_rows = total_rows
                .checked_add(part_rows)
                .ok_or_else(|| anyhow::anyhow!("part distribution row count overflow"))?;
            bytes.push(size);
            rows.push(part_rows);
        }
        bytes.sort_unstable();
        rows.sort_unstable();
        let percentile = |values: &[u64], percent: usize| -> u64 {
            let rank = values
                .len()
                .saturating_mul(percent)
                .saturating_add(99)
                .checked_div(100)
                .unwrap_or(0);
            values
                .get(rank.saturating_sub(1).min(values.len().saturating_sub(1)))
                .copied()
                .unwrap_or(0)
        };
        Ok(crate::observability::PartDistribution {
            parts: bytes.len(),
            total_bytes,
            min_bytes: bytes.first().copied().unwrap_or(0),
            p50_bytes: percentile(&bytes, 50),
            p95_bytes: percentile(&bytes, 95),
            max_bytes: bytes.last().copied().unwrap_or(0),
            total_rows,
            min_rows: rows.first().copied().unwrap_or(0),
            p50_rows: percentile(&rows, 50),
            p95_rows: percentile(&rows, 95),
            max_rows: rows.last().copied().unwrap_or(0),
        })
    }

    /// Inspect exact referenced, unreferenced, and block-reclaimable folded content for the
    /// current manifest revision.
    ///
    /// This walks visible record programs and verifies every exact owning-Part piece location.
    /// A flushed memtable is required so unpublished references cannot make dead content appear
    /// safe to reclaim.
    pub fn content_liveness(&self) -> Result<crate::observability::ContentLiveness> {
        self.content_liveness_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::content_liveness`] with cooperative record and block checkpoints.
    pub fn content_liveness_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<crate::observability::ContentLiveness> {
        control.check("content liveness")?;
        if !self.mem.is_empty() {
            bail!("content liveness requires a flushed memtable; call sync() and flush() first");
        }
        let live_pieces = live_fold_pieces_with_control(&self.parts, &self.fold, control)?;
        let live_block_ids: HashSet<u32> =
            live_pieces.keys().map(|location| location.block_id).collect();
        let mut report = crate::observability::ContentLiveness {
            live_pieces: u64::try_from(live_pieces.len())
                .map_err(|_| anyhow::anyhow!("live piece count exceeds u64"))?,
            ..crate::observability::ContentLiveness::default()
        };
        for location in live_pieces.keys() {
            report.live_logical_bytes = report
                .live_logical_bytes
                .checked_add(u64::from(location.raw))
                .ok_or_else(|| anyhow::anyhow!("live content byte count overflow"))?;
        }

        let inventory = self.fold.block_inventory_with_control(control)?;
        let punched = |block_id: u32| {
            self.manifest.punched.iter().any(|&(lo, hi)| (lo..=hi).contains(&block_id))
        };
        let mut observed_live_blocks = HashSet::new();
        for block in inventory {
            control.check("content liveness")?;
            if punched(block.block_id) {
                continue;
            }
            if live_block_ids.contains(&block.block_id) {
                report
                    .live_blocks
                    .checked_observe(block.raw_bytes, block.stored_bytes)
                    .ok_or_else(|| anyhow::anyhow!("live block space count overflow"))?;
                observed_live_blocks.insert(block.block_id);
            } else {
                report
                    .reclaimable_blocks
                    .checked_observe(block.raw_bytes, block.stored_bytes)
                    .ok_or_else(|| anyhow::anyhow!("reclaimable block space count overflow"))?;
            }
        }
        if observed_live_blocks != live_block_ids {
            let missing = live_block_ids.difference(&observed_live_blocks).next().copied().unwrap();
            bail!("live content references block {missing}, which is absent or declared punched");
        }
        report.stranded_dead_logical_bytes =
            report.live_blocks.raw_bytes.checked_sub(report.live_logical_bytes).ok_or_else(
                || anyhow::anyhow!("live piece bytes exceed their containing block bytes"),
            )?;
        report.dead_logical_bytes = report
            .reclaimable_blocks
            .raw_bytes
            .checked_add(report.stranded_dead_logical_bytes)
            .ok_or_else(|| anyhow::anyhow!("dead content byte count overflow"))?;
        Ok(report)
    }

    /// Resolve one piece of content to a location, consulting both dedup tiers before appending.
    ///
    /// ```text
    ///   Tier 0   the fold's in-memory window   — this flush's pieces, no I/O
    ///   Tier 1   every referenced part's dictionary — published content, filter then search
    ///   append   genuinely novel content
    /// ```
    ///
    /// Tier 1 is what makes dedup **unbounded** while Tier 0 stays bounded: the window is released at
    /// every flush (see [`Store::flush`]), so resident dedup memory tracks the flush interval rather
    /// than the store, and Tier 1 is what keeps that from costing any dedup at all.
    ///
    /// Parts are consulted newest-first: recently written content is the content most likely to repeat.
    ///
    /// **Why a Tier-1 hit needs no WAL bytes.** A part is only named by the manifest after its content
    /// was durable, and the committed fold tail only grows — so any location reachable through a part's
    /// dictionary is already referenced below the current fold tail. The bytes cannot be the ones
    /// a crash discards.
    fn fold_piece(&mut self, b: &[u8]) -> Result<crate::fold::Put> {
        let hash = PieceHash::of(b);
        let result = match (|| -> Result<crate::fold::Put> {
            if let Some(loc) = self.locate(&hash)? {
                // Seed the window so further references in this flush interval answer from memory.
                self.fold.note(hash, loc);
                Ok(crate::fold::Put { hash, loc, deduped: true })
            } else {
                self.fold.put_hashed(b, hash)
            }
        })() {
            Ok(result) => result,
            Err(error) => {
                // Another span or batch member may already have staged healthy Fold bytes. No WAL
                // frame owns them yet, so allowing the handle to continue could later dedup against
                // bytes that disappear on reopen. Treat every folding-phase failure as requiring
                // that reopen, even when this individual piece refused before mutation.
                self.requires_reopen = true;
                return Err(error).context(
                    "content folding failed after acceptance staging began; reopen required",
                );
            }
        };
        self.metrics.folded_content.observe(b.len(), result.deduped);
        Ok(result)
    }

    /// Fold the spans, log the record, and stage it. Durable only after [`Store::sync`].
    pub fn put(&mut self, id: &str, spans: &[Span], attrs: Vec<(String, AttrValue)>) -> Result<()> {
        self.ensure_writer_usable()?;
        let input = [ContentSpans::new(BODY_CONTENT, spans.to_vec())];
        input_record_admission_bytes(
            id,
            &input,
            &attrs,
            self.write_limits,
            self.read_limits,
            None,
        )?;
        let sequence = self.pending_sequence()?;
        self.wal.admit_additional_frames(1)?;
        let mut novel = Vec::new();
        let body = self.fold_spans(BODY_CONTENT, spans, &mut novel)?;
        let rec = Record::new(id, vec![body], attrs)?;
        self.stage_record(sequence, rec, novel)
    }

    /// Fold, log, and stage a general record with independently named content values.
    pub fn put_record(
        &mut self,
        id: &str,
        contents: &[ContentSpans<'_>],
        attrs: Vec<(String, AttrValue)>,
    ) -> Result<()> {
        self.ensure_writer_usable()?;
        // Validate and meter the whole map before `fold_spans` can append anything to the fold.
        input_record_admission_bytes(
            id,
            contents,
            &attrs,
            self.write_limits,
            self.read_limits,
            None,
        )?;
        let sequence = self.pending_sequence()?;
        self.wal.admit_additional_frames(1)?;
        let mut novel = Vec::new();
        let mut carved = Vec::with_capacity(contents.len());
        for content in contents {
            carved.push(self.fold_spans(content.name, &content.spans, &mut novel)?);
        }
        let rec = Record::new(id, carved, attrs)?;
        self.stage_record(sequence, rec, novel)
    }

    fn fold_spans(
        &mut self,
        name: &str,
        spans: &[Span<'_>],
        novel: &mut Vec<(PieceHash, Vec<u8>)>,
    ) -> Result<Content> {
        let mut ops = Vec::with_capacity(spans.len());
        let mut identity = blake3::Hasher::new();
        for s in spans {
            match s {
                Span::Lit(b) => {
                    identity.update(b);
                    ops.push(ContentOp::Lit(b.to_vec()));
                }
                Span::Piece(b) => {
                    identity.update(b);
                    if b.is_empty() {
                        ops.push(ContentOp::Lit(Vec::new()));
                        continue;
                    }
                    let put = self.fold_piece(b)?;
                    if !put.deduped {
                        // New content: the WAL must carry the bytes because writer open ignores
                        // anything the fold wrote past the tail referenced by current authority.
                        novel.push((put.hash, b.to_vec()));
                    }
                    ops.push(ContentOp::Piece { hash: put.hash, len: b.len() as u32 });
                }
            }
        }
        Ok(Content::identified(name, ops, ContentHash(identity.finalize().into())))
    }

    fn pending_sequence(&self) -> Result<u64> {
        self.manifest
            .next_seq
            .checked_add(1)
            .ok_or_else(|| anyhow::anyhow!("MANIFEST sequence space is exhausted"))
    }

    fn stage_record(
        &mut self,
        sequence: u64,
        rec: Record,
        novel: Vec<(PieceHash, Vec<u8>)>,
    ) -> Result<()> {
        if let Err(error) = self.wal.append(sequence, &rec, &novel) {
            self.requires_reopen = true;
            return Err(error)
                .context("WAL acceptance failed after fold staging; writer poisoned until reopen");
        }
        self.mem_bytes += approx_bytes(&rec);
        self.mem.insert(rec.id.clone(), Some(rec));
        Ok(())
    }

    /// [`Store::put`], with the engine's default carve deciding the spans. The convenience most
    /// ingest wants; see [`crate::carve`] for the opinion and its escape hatches.
    pub fn put_body(
        &mut self,
        id: &str,
        body: &[u8],
        attrs: Vec<(String, AttrValue)>,
    ) -> Result<()> {
        self.put_body_with(id, body, attrs, &crate::carve::Carve::default())
    }

    /// [`Store::put`], carved by an explicit strategy — the per-call escape hatch.
    pub fn put_body_with(
        &mut self,
        id: &str,
        body: &[u8],
        attrs: Vec<(String, AttrValue)>,
        carve: &crate::carve::Carve,
    ) -> Result<()> {
        self.put(id, &carve.carve(body), attrs)
    }

    /// Apply a [`Batch`]: every member, or — across a crash — none.
    ///
    /// Fold work happens first, so each member's novel bytes are known; then every member frame
    /// plus the completion marker goes to the log in one append. Replay applies the members only when
    /// the marker committed them, so a crash anywhere inside this call replays nothing of the batch.
    /// (Content the fold gathered for an unreplayed batch is beyond the committed tail and is
    /// truncated at open, exactly like content from an unsynced put.)
    ///
    /// Durability is unchanged: the batch is ACKed by [`Store::sync`], like everything else.
    /// Within the batch, later members win over earlier ones on the same id, exactly as two puts
    /// would.
    pub fn apply(&mut self, batch: Batch) -> Result<()> {
        self.ensure_writer_usable()?;
        if batch.items.is_empty() {
            return Ok(());
        }
        if batch.items.len() > self.write_limits.max_batch_records {
            return Err(WriteAdmissionError::TooManyBatchRecords {
                actual: batch.items.len(),
                allowed: self.write_limits.max_batch_records,
            }
            .into());
        }
        // Refuse and meter the complete batch before folding any member. Otherwise an invalid later item could
        // leave novel bytes and dedup-window state behind even though no atomic batch was logged.
        let mut batch_bytes =
            WAL_FRAME_OVERHEAD.saturating_add(varint_bytes(batch.items.len() as u64));
        for (index, item) in batch.items.iter().enumerate() {
            let item_bytes = match item {
                BatchItem::Put { id, contents, attrs } => owned_record_admission_bytes(
                    id,
                    contents,
                    attrs,
                    self.write_limits,
                    self.read_limits,
                    Some(index),
                )?,
                BatchItem::Delete { id } => {
                    delete_admission_bytes(id, self.write_limits, self.read_limits, Some(index))?
                }
            };
            add_size(&mut batch_bytes, item_bytes);
        }
        if batch_bytes > self.write_limits.max_batch_bytes {
            return Err(WriteAdmissionError::BatchTooLarge {
                actual: batch_bytes,
                allowed: self.write_limits.max_batch_bytes,
            }
            .into());
        }
        let sequence = self.pending_sequence()?;
        let batch_frames = u64::try_from(batch.items.len())
            .ok()
            .and_then(|count| count.checked_add(1))
            .ok_or_else(|| anyhow::anyhow!("WAL batch frame count overflow"))?;
        self.wal.admit_additional_frames(batch_frames)?;
        let mut framed: Vec<crate::store::wal::FramedRecord> =
            Vec::with_capacity(batch.items.len());
        for item in &batch.items {
            match item {
                BatchItem::Put { id, contents, attrs } => {
                    let mut novel = Vec::new();
                    let mut carved = Vec::with_capacity(contents.len());
                    for content in contents {
                        let mut ops = Vec::with_capacity(content.spans.len());
                        let mut identity = blake3::Hasher::new();
                        for s in &content.spans {
                            match s {
                                OwnedSpan::Lit(b) => {
                                    identity.update(b);
                                    ops.push(ContentOp::Lit(b.clone()));
                                }
                                OwnedSpan::Piece(b) => {
                                    identity.update(b);
                                    if b.is_empty() {
                                        ops.push(ContentOp::Lit(Vec::new()));
                                        continue;
                                    }
                                    let put = self.fold_piece(b)?;
                                    if !put.deduped {
                                        novel.push((put.hash, b.clone()));
                                    }
                                    ops.push(ContentOp::Piece {
                                        hash: put.hash,
                                        len: b.len() as u32,
                                    });
                                }
                            }
                        }
                        carved.push(Content::identified(
                            &content.name,
                            ops,
                            ContentHash(identity.finalize().into()),
                        ));
                    }
                    framed.push((Record::new(id, carved, attrs.clone())?, novel, false));
                }
                BatchItem::Delete { id } => {
                    framed.push((
                        Record { id: id.clone(), contents: Vec::new(), attrs: Vec::new() },
                        Vec::new(),
                        true,
                    ));
                }
            }
        }
        if let Err(error) = self.wal.append_batch(sequence, &framed) {
            self.requires_reopen = true;
            return Err(error).context(
                "atomic WAL acceptance failed after fold staging; writer poisoned until reopen",
            );
        }
        for (rec, _, tomb) in framed {
            if tomb {
                self.mem_bytes += rec.id.len() + 32;
                self.mem.insert(rec.id, None);
            } else {
                self.mem_bytes += approx_bytes(&rec);
                self.mem.insert(rec.id.clone(), Some(rec));
            }
        }
        Ok(())
    }

    /// Delete `id`. Durable only after [`Store::sync`], exactly like a put.
    ///
    /// Recorded as a TOMBSTONE rather than by removing anything: older parts are immutable and still
    /// hold the record, so a deletion has to be a newer version that says "absent". Space is not
    /// reclaimed here — the content stays in the fold, which is append-only. Reclaiming it is a
    /// separate, deliberate operation, because the fold is shared and the same bytes may be referenced
    /// by records that are still live.
    pub fn delete(&mut self, id: &str) -> Result<()> {
        self.ensure_writer_usable()?;
        delete_admission_bytes(id, self.write_limits, self.read_limits, None)?;
        let sequence = self.pending_sequence()?;
        self.wal.admit_additional_frames(1)?;
        self.wal.append_tomb(sequence, id)?;
        self.mem_bytes += id.len() + 32;
        self.mem.insert(id.to_string(), None);
        Ok(())
    }

    /// The ACK point: everything put so far survives a crash.
    pub fn sync(&mut self) -> Result<()> {
        self.sync_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::sync`] with an interruption checkpoint before entering the durability boundary.
    ///
    /// Once the durability boundary begins, cancellation is no longer observed. That boundary may
    /// first acknowledge a previously selected container authority before WAL fsync; returning
    /// cancellation after either dependency became durable would misreport the outcome.
    pub fn sync_with_control(&mut self, control: &crate::control::OperationControl) -> Result<()> {
        let started = std::time::Instant::now();
        let result = (|| {
            self.ensure_writer_usable()?;
            control.check("store sync")?;
            // A newer WAL frame can depend on the manifest revision this handle currently sees.
            // If an earlier publication selected that revision but its final barrier failed, WAL
            // fsync alone cannot acknowledge the dependency: a crash could select the predecessor
            // and leave replay input spanning two publication sequences. Establish the selected
            // container authority before acknowledging any dependent accepted mutation.
            self.container.lock().expect("container lock poisoned").acknowledge_current_state()?;
            self.wal.sync()
        })();
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Sync,
            started.elapsed(),
            &result,
        );
        result
    }

    /// Synchronize and publish every accepted operation, then install a verified, self-contained
    /// backup store.
    ///
    /// The destination must not exist. Holding `&mut self` prevents this process from changing the
    /// manifest while the backup walks the members it names — that part holds everywhere. Excluding a
    /// second writer *process* is the writer lock's job; native Unix and Windows enforce it. On
    /// `wasm32-wasip1` it gates nothing, so a concurrent writer is admitted and the artifact may be
    /// a racing cut. See [the store shape](https://github.com/turndb/turndb/blob/main/FORMAT.md#store-shape).
    pub fn backup(&mut self, out: &Path) -> Result<crate::backup::BackupStats> {
        self.backup_with_control(out, &crate::control::OperationControl::default())
    }

    /// [`Store::backup`] with cooperative cancellation before atomic artifact installation.
    ///
    /// Sync/flush may publish an equivalent representation of earlier accepted writes in
    /// the source store. Cancellation never installs the backup destination.
    pub fn backup_with_control(
        &mut self,
        out: &Path,
        control: &crate::control::OperationControl,
    ) -> Result<crate::backup::BackupStats> {
        let started = std::time::Instant::now();
        let result = self.backup_inner_with_control(out, control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Backup,
            started.elapsed(),
            &result,
        );
        result
    }

    fn backup_inner_with_control(
        &mut self,
        out: &Path,
        control: &crate::control::OperationControl,
    ) -> Result<crate::backup::BackupStats> {
        self.ensure_writer_usable()?;
        control.check("backup")?;
        crate::backup::ensure_destination_available(out)?;
        let staging = artifact_staging_path(out, "backing-up");
        crate::backup::ensure_source_is_not_staging(&self.path, &staging)?;
        self.sync_with_control(control)?;
        self.flush_with_control(control)?;
        control.check("backup")?;
        backup_container_copy(
            &self.container,
            &self.manifest,
            self.cfg,
            self.read_limits,
            out,
            &staging,
            control,
        )
    }

    /// Publish the memtable as a part and commit it.
    ///
    /// Data before pointers, and the manifest last: the fold is durable before a part names any of
    /// it, and the part is durable before the manifest names the part.
    pub fn flush(&mut self) -> Result<Option<PartRef>> {
        self.flush_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::flush`] with cooperative checks before manifest publication.
    ///
    /// Fold sync may make accepted content bytes durable before a later cancellation, but the live
    /// manifest revision and pending change set remain unchanged. An unpublished part is removed. Once publication
    /// begins, cancellation is no longer observed and the ordinary crash protocol owns the outcome.
    pub fn flush_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<PartRef>> {
        let started = std::time::Instant::now();
        let result = self.flush_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Flush,
            started.elapsed(),
            &result,
        );
        result
    }

    fn flush_inner_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<PartRef>> {
        self.ensure_writer_usable()?;
        control.check("memtable flush")?;
        if self.mem.is_empty() {
            // Publication may have selected the successor before its final barrier reported an
            // error, leaving only redundant replay input. A retry of the publication primitive is
            // also the settlement retry; otherwise backup and actor preludes could claim a
            // settled source while preserving a WAL that replays already-published mutations.
            if self.wal.frame_count() != 0 {
                self.container
                    .lock()
                    .expect("container lock poisoned")
                    .acknowledge_current_state()?;
                self.wal.truncate()?;
            }
            return Ok(None);
        }
        let prepared = (|| -> Result<(Part, Manifest)> {
            let tail = self.fold.sync()?;
            let seq = self
                .manifest
                .next_seq
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("MANIFEST sequence space is exhausted"))?;
            let file = format!("part-{seq:08}.part");
            let mut recs: Vec<Record> = Vec::with_capacity(self.mem.len());
            let mut tombs: Vec<bool> = Vec::with_capacity(self.mem.len());
            for (id, v) in &self.mem {
                control.check("memtable flush planning")?;
                match v {
                    Some(r) => {
                        recs.push(r.clone());
                        tombs.push(false);
                    }
                    // A tombstone still needs a row, so it gets an empty one carrying only its id.
                    None => {
                        recs.push(Record {
                            id: id.clone(),
                            contents: Vec::new(),
                            attrs: Vec::new(),
                        });
                        tombs.push(true);
                    }
                }
            }

            // Resolve every referenced piece through both dedup tiers before building the part.
            let mut locs: HashMap<PieceHash, Loc> = HashMap::new();
            for record in &recs {
                control.check("memtable flush planning")?;
                for content in &record.contents {
                    for op in &content.ops {
                        control.check("memtable flush planning")?;
                        let ContentOp::Piece { hash, .. } = op else { continue };
                        if locs.contains_key(hash) {
                            continue;
                        }
                        let loc = self.locate(hash)?.ok_or_else(|| {
                            anyhow::anyhow!(
                                "pending piece {hash} is in neither the fold window nor any referenced part"
                            )
                        })?;
                        locs.insert(*hash, loc);
                    }
                }
            }
            let member =
                self.container.lock().expect("container lock poisoned").begin_member(&file)?;
            let (meta, member) = part::build_full_into(
                member,
                &recs,
                &tombs,
                seq,
                seq,
                self.cfg.level,
                |hash| locs.get(hash).copied(),
                &HashMap::new(),
                self.read_limits,
            )?;
            control.check("memtable flush publication")?;
            let digest = {
                let mut container = self.container.lock().expect("container lock poisoned");
                PieceHash(container.finish_member(member)?).to_hex()
            };
            let reader = self
                .container
                .lock()
                .expect("container lock poisoned")
                .extent(&file)
                .expect("the member was staged a moment ago");
            let opened = Part::open_reader_with_limits(
                Box::new(reader),
                self.pcache.clone(),
                self.read_limits,
            )?;

            let mut manifest = self.manifest.clone();
            manifest.parts.push(PartRef {
                member: file,
                seq_lo: seq,
                seq_hi: seq,
                records: meta.n_records,
                b3: digest,
            });
            manifest.fold_seg = tail.seg;
            manifest.fold_off = tail.off;
            manifest.next_seq = seq;
            let mut container = self.container.lock().expect("container lock poisoned");
            manifest.commit_into_container(&mut container)?;
            sweep_unreachable_container(&mut container, &manifest, self.read_limits)?;
            Ok((opened, manifest))
        })();
        let (opened, m) = match prepared {
            Ok(prepared) => prepared,
            Err(error) => {
                return Err(self.discard_staged_and_require_reopen("flush preparation", error));
            }
        };
        let mut c = self.container.lock().expect("container lock poisoned");
        let publication_error = match c.commit() {
            Ok(_) => None,
            Err(error) if c.failed_publication_selected() == Some(true) => Some(error),
            Err(error) => return Err(error),
        }; // <- the linearization point: one flip names everything above
        drop(c);

        self.parts.push(Arc::new(opened));
        self.manifest = m;
        self.note_manifest_commit();
        self.mem.clear();
        self.mem_bytes = 0;
        // Release Tier 0 only here, after the part is committed and open. Closing it any earlier
        // would drop the window while the part being built still needs it, and the part cannot answer
        // a Tier-1 lookup until it is committed and in `self.parts`. Everything the window covered is
        // now reachable through that part's dictionary, so nothing is lost but the memory.
        self.fold.release_dedup_window();
        if let Some(error) = publication_error {
            // The successor is selected but its durability barrier was not acknowledged. Keep the
            // redundant WAL for retry/reopen, but never leave this live handle behind its own
            // selected manifest revision.
            return Err(error).context(
                "container selected the flushed manifest revision, but its final synchronization failed",
            );
        }
        // Only now: the records are in a committed part, so the log that carried them is redundant.
        self.wal.truncate()?;
        Ok(self.manifest.parts.last().cloned())
    }

    /// Merge a contiguous run of parts referenced by the current manifest revision into one, then
    /// publish the resulting manifest revision atomically.
    ///
    /// Contiguity is the correctness gate: parts resolve versions by sequence, so merging a
    /// non-adjacent set would drop whatever an excluded part said about a shared id. The range is
    /// therefore expressed as a slice of that ordered part list, which cannot express a gap.
    pub fn merge_range(
        &mut self,
        lo: usize,
        len: usize,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        self.merge_range_with_control(lo, len, &crate::control::OperationControl::default())
    }

    /// [`Store::merge_range`] with cooperative checkpoints. The final cancellable checkpoint is
    /// immediately before manifest publication; publication and the in-memory replacement are
    /// then uninterruptible.
    pub fn merge_range_with_control(
        &mut self,
        lo: usize,
        len: usize,
        control: &crate::control::OperationControl,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        let started = std::time::Instant::now();
        let result = self.merge_range_inner_with_control(lo, len, control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Merge,
            started.elapsed(),
            &result,
        );
        result
    }

    fn merge_range_inner_with_control(
        &mut self,
        lo: usize,
        len: usize,
        control: &crate::control::OperationControl,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        self.ensure_writer_usable()?;
        control.check("part compaction")?;
        let Some(end) = lo.checked_add(len) else { return Ok(None) };
        if len < 2 || end > self.parts.len() {
            return Ok(None);
        }
        let inputs: Vec<Arc<Part>> = self.parts[lo..end].to_vec();
        // Named by the sequence RANGE it spans. The output's range strictly contains every input's
        // (the inputs are disjoint and there are at least two), so the name cannot collide with a part
        // this merge is about to replace — which the post-commit sweep would otherwise unlink.
        let seq_lo = self.manifest.parts[lo].seq_lo;
        let seq_hi = self.manifest.parts[end - 1].seq_hi;
        let file = format!("part-{seq_lo:08}-{seq_hi:08}.part");
        debug_assert!(
            !self.manifest.parts.iter().any(|p| p.member == file),
            "merge output {file} collides with a referenced part"
        );
        // A tombstone may only be discarded when this merge covers the ENTIRE live list — otherwise a
        // part outside the run could still hold an older version of the deleted id, and dropping the
        // tombstone would resurrect it.
        let total = lo == 0 && len == self.parts.len();
        // Publish: the merged part is durable before the manifest names it; the pre-flip barrier
        // makes the manifest swap the single
        // linearization point. A crash before it leaves the merged output unreachable: an orphan
        // file, or uncommitted noise past the tail. The INPUTS are not deleted here: retained
        // manifests still name them, so a reader inside the retention window keeps a complete
        // snapshot. They fall to the sweep when the window prunes past their last naming manifest.
        // Every fallible preparation step and the final cancellation checkpoint happen before
        // commit is attempted. Once commit starts, its ordinary crash protocol—not cancellation—
        // decides the outcome.
        let tmp = file_tmp_dir(&self.path);
        crate::vfs::mkdir_all(&tmp)?;
        let member = self.container.lock().expect("container lock poisoned").begin_member(&file)?;
        let location_is_usable = |location: Loc, hash: PieceHash| -> Result<bool> {
            self.fold.verify_location_shape(location).with_context(|| {
                format!("merge input dictionary mapped {hash} to an invalid fold location")
            })?;
            if self.fold.is_punched(location.block_id) {
                return Ok(false);
            }
            self.fold.read_verified(location, hash).with_context(|| {
                format!("merge input dictionary mapped {hash} to invalid fold bytes")
            })?;
            Ok(true)
        };
        let built = crate::part::merge::merge_into_with_control_for_operation(
            member,
            &tmp.join("m"),
            &inputs,
            self.cfg.level,
            total,
            control,
            "part compaction",
            self.read_limits,
            Some(&location_is_usable),
        );
        let (meta, stats, member) = match built {
            Ok(v) => v,
            Err(error) => {
                self.container.lock().expect("container lock poisoned").abandon_open_member();
                let _ = crate::vfs::remove_tree(&tmp);
                return Err(error);
            }
        };
        if let Err(error) = control.check("part compaction") {
            self.container.lock().expect("container lock poisoned").abandon_open_member();
            let _ = crate::vfs::remove_tree(&tmp);
            return Err(error.into());
        }
        let digest = {
            let mut c = self.container.lock().expect("container lock poisoned");
            PieceHash(c.finish_member(member)?).to_hex()
        };
        let _ = crate::vfs::remove_tree(&tmp);
        let prepared = (|| -> Result<(Part, Manifest)> {
            let reader = self
                .container
                .lock()
                .expect("container lock poisoned")
                .extent(&file)
                .expect("the member was staged a moment ago");
            let opened = Part::open_reader_with_limits(
                Box::new(reader),
                self.pcache.clone(),
                self.read_limits,
            )?;
            let mut m = self.manifest.clone();
            m.parts.splice(
                lo..end,
                [PartRef {
                    member: file.clone(),
                    seq_lo: meta.seq_lo,
                    seq_hi: meta.seq_hi,
                    records: meta.n_records,
                    b3: digest,
                }],
            );
            let t = self.fold.sync()?;
            m.fold_seg = t.seg;
            m.fold_off = t.off;
            let mut c = self.container.lock().expect("container lock poisoned");
            m.commit_into_container(&mut c)?;
            sweep_unreachable_container(&mut c, &m, self.read_limits)?;
            Ok((opened, m))
        })();
        let (opened, m) = match prepared {
            Ok(prepared) => prepared,
            Err(error) => {
                // The merged member has already been registered in the staged directory. No
                // unrelated later operation may publish it (or a partly staged manifest). Fold
                // sync may also have advanced in-memory locations, so successful cleanup still
                // requires reopen before this writer can be trusted again.
                return Err(self.discard_staged_and_require_reopen("merge preparation", error));
            }
        };
        let mut c = self.container.lock().expect("container lock poisoned");
        let publication_error = match c.commit() {
            Ok(_) => None,
            Err(error) if c.failed_publication_selected() == Some(true) => Some(error),
            Err(error) => return Err(error),
        }; // <- the linearization point
        drop(c);
        self.manifest = m;
        self.note_manifest_commit();
        self.parts.splice(lo..end, [Arc::new(opened)]);
        if let Some(error) = publication_error {
            return Err(error).context(
                "container selected the merged manifest revision, but its final synchronization failed",
            );
        }
        Ok(Some(stats))
    }

    /// Size-tiered compaction: when parts pile up, fold the oldest run together.
    ///
    /// Merging the OLDEST parts keeps the run contiguous by construction and matches the access
    /// pattern — old parts are cold and stop being rewritten. Bounding part count is not only about
    /// read amplification: a Tier-1 dedup lookup is O(parts), so this is what keeps global dedup
    /// affordable.
    ///
    /// This is the MANUAL dial; [`Store::auto_compact`] is the engine's measured default policy.
    pub fn maybe_compact(
        &mut self,
        trigger: usize,
        run: usize,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        self.maybe_compact_with_control(trigger, run, &crate::control::OperationControl::default())
    }

    /// [`Store::maybe_compact`] with cooperative checkpoints. The final cancellable checkpoint is
    /// immediately before manifest publication in [`Store::merge_range_with_control`].
    pub fn maybe_compact_with_control(
        &mut self,
        trigger: usize,
        run: usize,
        control: &crate::control::OperationControl,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        control.check("part compaction")?;
        if self.parts.len() < trigger {
            return Ok(None);
        }
        self.merge_range_with_control(0, run.min(self.parts.len()), control)
    }

    /// The engine's compaction opinion: a TOTAL merge whenever the live list reaches
    /// [`Store::AUTO_COMPACT_K`] parts. Call it after flushes; it is cheap to call and refuses
    /// below the threshold.
    ///
    /// The classic LSM tradeoff — write amplification against read amplification — collapses
    /// here, because a merge rewrites references and columns and never content. Measured on 20k
    /// real records (examples/compact_bench): the whole policy space lands within 0.008–0.011 ms
    /// per point lookup, so read amp does not discriminate; merge WALL is the only real cost, and
    /// total-at-8 paid 0.7s across the run where tiered(8,4) paid 1.7s for MORE final parts and
    /// no tombstone removal. Total merges are also the only ones allowed to drop tombstones,
    /// so deleted record IDs stop shadowing older versions instead of persisting forever.
    ///
    /// The honest caveat, documented as the dial it is: a total merge costs O(live records) of
    /// wall time, so at some store size a young/old split becomes worth it. That crossover is far
    /// beyond current scale; when it arrives, `maybe_compact` is the young tier's tool and this
    /// policy becomes the old tier's slow beat.
    pub fn auto_compact(&mut self) -> Result<Option<crate::part::merge::MergeStats>> {
        self.auto_compact_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::auto_compact`] with cooperative checkpoints. Its final cancellable checkpoint is
    /// the manifest-publication boundary documented by [`Store::merge_range_with_control`].
    pub fn auto_compact_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<crate::part::merge::MergeStats>> {
        self.ensure_writer_usable()?;
        control.check("part compaction")?;
        if self.parts.len() < Self::AUTO_COMPACT_K {
            return Ok(None);
        }
        self.merge_range_with_control(0, self.parts.len(), control)
    }

    /// Select a contiguous compaction run whose exact physical input fits every supplied budget.
    ///
    /// The widest eligible run wins; ties prefer the oldest run. Contiguity preserves sequence
    /// visibility, and only a plan covering the complete live list may drop tombstones.
    pub fn plan_compaction(&self, budget: CompactionBudget) -> Result<Option<CompactionPlan>> {
        budget.validate()?;
        if self.manifest.parts.len() < 2 {
            return Ok(None);
        }
        let costs: Vec<(u64, u64)> = self
            .manifest
            .parts
            .iter()
            .map(|part| {
                let bytes = self.part_member_bytes(&part.member)?;
                Ok((u64::from(part.records), bytes))
            })
            .collect::<Result<_>>()?;

        let mut best: Option<CompactionPlan> = None;
        for start in 0..costs.len() - 1 {
            let mut rows = 0u64;
            let mut bytes = 0u64;
            for (offset, &(part_rows, part_bytes)) in
                costs[start..].iter().take(budget.max_input_parts).enumerate()
            {
                rows = rows.saturating_add(part_rows);
                bytes = bytes.saturating_add(part_bytes);
                if rows > budget.max_input_rows || bytes > budget.max_input_bytes {
                    break;
                }
                let parts = offset + 1;
                if parts < 2 {
                    continue;
                }
                let plan = CompactionPlan {
                    start_part: start,
                    input_parts: parts,
                    input_rows: rows,
                    input_bytes: bytes,
                    drops_tombstones: start == 0 && parts == costs.len(),
                };
                if best.as_ref().is_none_or(|current| plan.input_parts > current.input_parts) {
                    best = Some(plan);
                }
            }
        }
        if best.is_some() {
            return Ok(best);
        }

        let (start_part, input_rows, input_bytes) = costs
            .windows(2)
            .enumerate()
            .map(|(start, pair)| {
                (start, pair[0].0.saturating_add(pair[1].0), pair[0].1.saturating_add(pair[1].1))
            })
            .min_by_key(|&(start, rows, bytes)| (bytes, rows, start))
            .expect("at least two parts were checked above");
        Err(CompactionError::BudgetTooSmall { start_part, input_rows, input_bytes, budget }.into())
    }

    /// Estimate temporary output space for the current bounded-part-merge plan.
    ///
    /// Input member lengths, section counts/raw bytes, retained-input bytes, and filesystem
    /// availability are exact at this cut. `estimated_stage_bytes` is intentionally not a hard
    /// bound: recompression and merged index encoding can change output size. Callers may apply
    /// their own safety factor; TurnDB exposes the basis instead of hiding policy in a boolean.
    pub fn estimate_compaction_space(
        &self,
        budget: CompactionBudget,
    ) -> Result<Option<CompactionSpaceEstimate>> {
        self.estimate_compaction_space_with_control(
            budget,
            &crate::control::OperationControl::default(),
        )
    }

    /// [`Store::estimate_compaction_space`] with cooperative planning checkpoints.
    pub fn estimate_compaction_space_with_control(
        &self,
        budget: CompactionBudget,
        control: &crate::control::OperationControl,
    ) -> Result<Option<CompactionSpaceEstimate>> {
        control.check("compaction space preflight")?;
        let Some(plan) = self.plan_compaction(budget)? else {
            return Ok(None);
        };
        let end = plan.start_part + plan.input_parts;
        let mut input_sections = 0usize;
        let mut input_raw_section_bytes = 0u64;
        for part in &self.parts[plan.start_part..end] {
            control.check("compaction space preflight")?;
            for (_, _, raw, _) in part.sections() {
                control.check("compaction space preflight")?;
                input_sections = input_sections
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("compaction section count overflow"))?;
                input_raw_section_bytes = input_raw_section_bytes
                    .checked_add(u64::from(raw))
                    .ok_or_else(|| anyhow::anyhow!("compaction raw section byte count overflow"))?;
            }
        }
        // Raw section bytes are the strongest cheap basis before running the merge. Explicit row
        // and section framing allowance plus one MiB covers ordinary metadata variation, but is not
        // represented as an admission guarantee.
        let row_allowance = plan
            .input_rows
            .checked_mul(64)
            .ok_or_else(|| anyhow::anyhow!("compaction row framing estimate overflow"))?;
        let section_allowance = u64::try_from(input_sections)
            .map_err(|_| anyhow::anyhow!("compaction section count exceeds u64"))?
            .checked_mul(256)
            .ok_or_else(|| anyhow::anyhow!("compaction section framing estimate overflow"))?;
        let estimated_stage_bytes = input_raw_section_bytes
            .checked_add(row_allowance)
            .and_then(|bytes| bytes.checked_add(section_allowance))
            .and_then(|bytes| bytes.checked_add(1 << 20))
            .ok_or_else(|| anyhow::anyhow!("compaction stage estimate overflow"))?;
        Ok(Some(CompactionSpaceEstimate {
            plan,
            input_sections,
            input_raw_section_bytes,
            estimated_stage_bytes,
            estimate_is_hard_bound: false,
            retained_input_bytes_after_commit: plan.input_bytes,
            filesystem_available_bytes: crate::sys::filesystem_available_bytes(
                self.fs_probe_path(),
            )
            .with_context(|| {
                format!("measure available filesystem bytes at {}", self.fs_probe_path().display())
            })?,
        }))
    }

    pub fn compact_bounded(
        &mut self,
        budget: CompactionBudget,
    ) -> Result<Option<BoundedCompaction>> {
        self.compact_bounded_with_control(budget, &crate::control::OperationControl::default())
    }

    /// Plan and publish one budget-bounded contiguous compaction run.
    pub fn compact_bounded_with_control(
        &mut self,
        budget: CompactionBudget,
        control: &crate::control::OperationControl,
    ) -> Result<Option<BoundedCompaction>> {
        self.ensure_writer_usable()?;
        control.check("bounded compaction")?;
        let Some(plan) = self.plan_compaction(budget)? else {
            return Ok(None);
        };
        let merge = self
            .merge_range_with_control(plan.start_part, plan.input_parts, control)?
            .expect("a compaction plan always contains at least two parts");
        let output = &self.manifest.parts[plan.start_part];
        let output_bytes = self.part_member_bytes(&output.member)?;
        Ok(Some(BoundedCompaction { plan, output_bytes, merge }))
    }

    /// Newest-wins across the committed parts, then the memtable, which is newer than all of them.
    pub fn get(&self, id: &str) -> Result<Option<Record>> {
        if let Some(v) = self.mem.get(id) {
            return Ok(v.clone());
        }
        verification_integrity("read committed record", read::get(&self.parts, id))
    }

    /// Batch projection used by structured scans. Immutable rows share part-level decoders while
    /// memtable records retain their in-memory projection path.
    pub(crate) fn project_candidates(
        &self,
        candidates: &[crate::scan::ScanCandidate],
        attrs: &HashSet<&str>,
        contents: &HashSet<&str>,
    ) -> Result<Vec<Record>> {
        let mut committed = Vec::new();
        let mut committed_outputs = Vec::new();
        let mut out: Vec<Option<Record>> = vec![None; candidates.len()];
        for (output, candidate) in candidates.iter().enumerate() {
            match candidate {
                crate::scan::ScanCandidate::Committed(row) => {
                    committed.push(row);
                    committed_outputs.push(output);
                }
                crate::scan::ScanCandidate::Memtable(id) => {
                    let record = self.mem.get(id).and_then(Option::as_ref).ok_or_else(|| {
                        anyhow::anyhow!("resolved memtable row {id:?} is no longer live")
                    })?;
                    out[output] = Some(Record {
                        id: record.id.clone(),
                        contents: record
                            .contents
                            .iter()
                            .filter(|content| contents.contains(content.name.as_str()))
                            .cloned()
                            .collect(),
                        attrs: record
                            .attrs
                            .iter()
                            .filter(|(name, _)| attrs.contains(name.as_str()))
                            .cloned()
                            .collect(),
                    });
                }
            }
        }
        for (output, record) in committed_outputs.into_iter().zip(read::project_rows(
            &self.parts,
            &committed,
            attrs,
            contents,
        )?) {
            out[output] = Some(record);
        }
        out.into_iter()
            .map(|record| record.ok_or_else(|| anyhow::anyhow!("projected row was not produced")))
            .collect()
    }

    /// Reconstruct selected content without re-locating an already resolved scan row.
    pub(crate) fn reconstruct_candidate_content(
        &self,
        candidate: &crate::scan::ScanCandidate,
        content: &Content,
    ) -> Result<Vec<u8>> {
        match candidate {
            crate::scan::ScanCandidate::Committed(row) => {
                read::reconstruct_projected_content(&self.parts, &self.fold, row, content)
            }
            crate::scan::ScanCandidate::Memtable(id) => {
                self.mem.get(id).and_then(Option::as_ref).ok_or_else(|| {
                    anyhow::anyhow!("resolved memtable row {id:?} is no longer live")
                })?;
                self.rebuild_projected_content(content)
            }
        }
    }

    /// Byte-exact content for `id`.
    pub fn reconstruct(&self, id: &str) -> Result<Option<Vec<u8>>> {
        self.reconstruct_content(id, BODY_CONTENT)
    }

    /// Byte-exact named content for `id`, without reconstructing any sibling content value.
    pub fn reconstruct_content(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
        // The memtable is newer than every part, so it is consulted first — and it is the ONLY thing
        // this adds over the current manifest revision.
        if let Some(v) = self.mem.get(id) {
            return match v {
                Some(r) => self.rebuild_content(r, name),
                None => Ok(None), // staged deletion
            };
        }
        verification_integrity(
            "reconstruct committed content",
            read::reconstruct_content(&self.parts, &self.fold, id, name),
        )
    }

    /// Where content lives, through BOTH dedup tiers.
    ///
    /// The single answer to "where is this piece" for every caller that needs one — the write path,
    /// the flush path, and the staged-record read path. They disagreed before, and each disagreement
    /// was the same bug wearing a different hat: a piece deduped against a committed part is not in
    /// the in-memory window, and after a crash nothing puts it back there, because the WAL carries no
    /// bytes for content that was already durable.
    fn locate(&self, h: &PieceHash) -> Result<Option<Loc>> {
        locate_verified_piece(&self.parts, &self.fold, h)
    }

    fn rebuild_content(&self, r: &Record, name: &str) -> Result<Option<Vec<u8>>> {
        let Some(content) = r.content(name) else {
            return Ok(None);
        };
        Ok(Some(self.rebuild_projected_content(content)?))
    }

    fn rebuild_projected_content(&self, content: &Content) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        for op in &content.ops {
            match op {
                ContentOp::Lit(b) => out.extend_from_slice(b),
                ContentOp::Piece { hash, .. } => {
                    let loc = self
                        .locate(hash)?
                        .ok_or_else(|| anyhow::anyhow!("piece {hash} not resolvable"))?;
                    self.fold.read_verified_into(loc, *hash, &mut out)?;
                }
            }
        }
        if let Some(expected) = content.identity {
            let got = ContentHash::of(&out);
            if got != expected {
                bail!(
                    "content {:?} reconstructed as {got} but its identity is {expected}",
                    content.name
                );
            }
        }
        Ok(out)
    }

    pub fn memtable_len(&self) -> usize {
        self.mem.len()
    }
    pub fn memtable_bytes(&self) -> usize {
        self.mem_bytes
    }
    /// Hand the fold and parts to a lens. Consumes the store because the query layer takes ownership
    /// of both; the store authority it was opened at is already baked into `parts`.
    pub fn into_parts(self) -> (Arc<Fold>, Vec<Arc<Part>>) {
        (Arc::new(self.fold), self.parts)
    }

    pub fn part_count(&self) -> usize {
        self.parts.len()
    }

    /// Parts referenced by the current manifest revision, oldest to newest — the writer-side twin
    /// of [`ReadStore::parts`].
    pub fn parts(&self) -> &[Arc<Part>] {
        &self.parts
    }

    /// [`ReadStore::scan_ids`], plus the uncommitted memtable — so a writer paging its own store
    /// sees records it has not flushed yet, which is what makes a live backfill possible.
    ///
    /// The memtable is a `BTreeMap`, so its slice of the range overlays resolved committed rows in
    /// id order. Staged deletions remove an id here exactly as a tombstone would.
    pub fn scan_ids(
        &self,
        from: Option<&str>,
        to: Option<&str>,
        limit: usize,
        reverse: bool,
    ) -> Result<Vec<String>> {
        Ok(self
            .scan_candidates(from, to, limit, reverse, usize::MAX, true)?
            .candidates
            .into_iter()
            .map(crate::scan::ScanCandidate::into_id)
            .collect())
    }

    /// Resolve a bounded id range once and retain each live row's storage origin for projection.
    pub(crate) fn scan_candidates(
        &self,
        from: Option<&str>,
        to: Option<&str>,
        limit: usize,
        reverse: bool,
        max_resolution_entries: usize,
        allow_oversized_group: bool,
    ) -> Result<crate::scan::CandidateBatch> {
        check_range(from, to)?;
        if limit == 0 {
            return Ok(crate::scan::CandidateBatch::default());
        }
        let range = (
            from.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Included),
            to.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded),
        );
        let overlay: Box<dyn Iterator<Item = (&str, bool)> + '_> = if reverse {
            Box::new(
                self.mem
                    .range::<str, _>(range)
                    .rev()
                    .map(|(id, value)| (id.as_str(), value.is_some())),
            )
        } else {
            Box::new(
                self.mem.range::<str, _>(range).map(|(id, value)| (id.as_str(), value.is_some())),
            )
        };
        let resolved = read::scan_rows(
            &self.parts,
            overlay,
            read::RowScan {
                from,
                to,
                limit,
                reverse,
                max_resolution_entries,
                allow_oversized_group,
            },
        )?;
        Ok(crate::scan::CandidateBatch {
            candidates: resolved
                .rows
                .into_iter()
                .map(|row| match row.origin {
                    read::RowOrigin::Part { .. } => crate::scan::ScanCandidate::Committed(row),
                    read::RowOrigin::Memtable => crate::scan::ScanCandidate::Memtable(row.id),
                })
                .collect(),
            resolution: crate::scan::ScanResolutionStats {
                physical_rows: resolved.physical_rows,
                superseded_rows: resolved.superseded_rows,
                tombstones: resolved.tombstones,
                memtable_entries: resolved.memtable_entries,
                budget_exhausted: resolved.budget_exhausted,
            },
            resolved_through: resolved.resolved_through,
            has_more: resolved.has_more,
        })
    }

    /// Every live id: committed parts plus the uncommitted memtable.
    ///
    /// Includes staged records, unlike [`ReadStore::ids`], because a writer can see its own writes.
    pub fn ids(&self) -> Result<Vec<String>> {
        let mut all = read::ids(&self.parts)?;
        // Overlay the memtable: a staged put adds an id, a staged delete removes one.
        all.retain(|id| !matches!(self.mem.get(id), Some(None)));
        for (id, v) in &self.mem {
            if v.is_some() && !all.contains(id) {
                all.push(id.clone());
            }
        }
        all.sort();
        all.dedup();
        Ok(all)
    }

    /// Bounded structured paging over the writer's complete read-your-writes view.
    pub fn scan(&self, request: &crate::scan::ScanRequest) -> Result<crate::scan::ScanPage> {
        crate::scan::scan_store(self, request)
    }

    pub(crate) fn candidate_may_match(
        &self,
        candidate: &crate::scan::ScanCandidate,
        predicates: &[crate::scan::Predicate],
    ) -> Result<bool> {
        match candidate {
            crate::scan::ScanCandidate::Memtable(_) => Ok(true),
            crate::scan::ScanCandidate::Committed(row) => match row.origin {
                read::RowOrigin::Part { part, .. } => read::part_may_match(
                    self.parts
                        .get(part)
                        .ok_or_else(|| anyhow::anyhow!("candidate part is outside the store"))?,
                    predicates,
                ),
                read::RowOrigin::Memtable => Ok(true),
            },
        }
    }

    /// Explain a structured scan against the current read-your-writes view without resolving rows
    /// or evaluating predicates.
    pub fn explain_scan(
        &self,
        request: &crate::scan::ScanRequest,
    ) -> Result<crate::scan::ScanExplanation> {
        crate::scan::explain_store(self, request)
    }

    pub(crate) fn scan_physical_scope(
        &self,
        from: Option<&str>,
        to: Option<&str>,
    ) -> Result<crate::scan::ScanPhysicalScope> {
        let mut scope = read::scan_physical_scope(&self.parts, from, to)?;
        let range = (
            from.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Included),
            to.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded),
        );
        scope.memtable_entries_in_bounds = self.mem.range::<str, _>(range).count();
        Ok(scope)
    }

    /// ERASE records: publish tombstones and rewrite until this store no longer references the
    /// records and its old members have been removed.
    ///
    /// This is the compliance path, and it composes three operations that each already existed:
    /// deletes shadow the ids; a TOTAL merge drops the tombstones once nothing remains for them
    /// to shadow; and the re-fold rewrites the fold without the dropped content and rebuilds
    /// every part — so both the bytes AND the columnar metadata (ids, piece lengths, attribute
    /// values) of the erased records are gone when this returns. The re-fold also purges the
    /// retained manifest history, which the erasure story requires: a read view that could still serve
    /// the erased record is not erasure.
    ///
    /// What this does NOT promise, stated because overclaiming here is a liability: media-byte
    /// non-recoverability on arbitrary or copy-on-write filesystems, through WASI, or for copies
    /// already made (replicas and backups). The measurable claims are query absence, logical
    /// file-length reclamation, and the lifecycle event for this operation.
    ///
    /// Ids that do not exist are counted, not errored: a DSAR naming already-gone data is a
    /// normal outcome, and the record should say so rather than fail. When every requested id is
    /// already absent, the operation returns statistics without a transition.
    pub fn erase_ids(&mut self, ids: &[String]) -> Result<ErasureStats> {
        self.erase_ids_with_control(ids, &crate::control::OperationControl::default())
    }

    /// [`Store::erase_ids`] with cancellation during its read-only planning phase.
    ///
    /// Once the atomic tombstone batch is applied, interruption is deliberately deferred until the
    /// total merge and re-fold finish. Returning `cancelled` after logical deletion but before
    /// reclamation would make a retry mistake the ids for previously absent records and falsely
    /// report completion. Erasure therefore either stops before mutation or drives its full store
    /// protocol to completion.
    pub fn erase_ids_with_control(
        &mut self,
        ids: &[String],
        control: &crate::control::OperationControl,
    ) -> Result<ErasureStats> {
        let started = std::time::Instant::now();
        let result = self.erase_ids_inner_with_control(ids, control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Erase,
            started.elapsed(),
            &result,
        );
        result
    }

    fn erase_ids_inner_with_control(
        &mut self,
        ids: &[String],
        control: &crate::control::OperationControl,
    ) -> Result<ErasureStats> {
        self.ensure_writer_usable()?;
        let mut tombstoned = 0usize;
        let mut absent = 0usize;
        let mut delete = Vec::new();
        let mut seen = HashSet::new();
        for id in ids {
            control.check("record erasure")?;
            if seen.insert(id) && self.get(id)?.is_some() {
                delete.push(id);
                tombstoned += 1;
            } else {
                absent += 1;
            }
        }
        if tombstoned == 0 {
            return Ok(ErasureStats {
                requested: ids.len(),
                tombstoned,
                absent,
                remaining: self.ids()?.len(),
                refold: None,
            });
        }
        control.check("record erasure")?;
        let mut batch = Batch::new();
        for id in delete {
            batch.delete(id);
        }
        self.apply(batch)?;
        self.sync()?;
        self.flush()?;
        if self.parts.len() > 1 {
            // TOTAL, so the tombstones can drop — a partial merge would carry them forward.
            self.merge_range(0, self.parts.len())?;
        }
        let refold = self.refold()?;
        Ok(ErasureStats {
            requested: ids.len(),
            tombstoned,
            absent,
            remaining: self.ids()?.len(),
            refold: Some(refold),
        })
    }

    /// Resolve every live program through its owning Part dictionary. One identity may have more
    /// than one physical location, and every owning location must remain live until the Parts that
    /// name it stop deciding records.
    fn live_fold_pieces_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<BTreeMap<Loc, PieceHash>> {
        live_fold_pieces_with_control(&self.parts, &self.fold, control)
    }

    /// Reclaim erased space in place: content-punch every fold block no record resolved by current
    /// authority can reach.
    ///
    /// The cheap half of erasure when a full rewrite is not requested. A re-fold reclaims the same
    /// bytes by rewriting the world — correct, thorough, and O(store); this walks the live
    /// records' piece references, finds blocks nothing reaches, records them in the manifest, and
    /// deallocates their extents. Offsets do not move, so no current part is rebuilt and no record
    /// resolved by current authority loses readable content. An older read view, including one
    /// pinned to a retained manifest revision, may lose readability when this operation punches
    /// bytes that current authority no longer needs.
    ///
    /// **Order matters and is the whole safety argument**: the manifest names the punched blocks
    /// BEFORE the bytes go, so a crash between the two leaves blocks marked punched that are
    /// still readable (harmless — the next call re-punches them), never punched blocks that
    /// nothing accounts for (an ops fire drill: zeros that look exactly like corruption).
    ///
    /// Requires a flushed memtable, for the same reason a re-fold does: staged records reference
    /// content this would otherwise consider unreachable.
    pub fn punch_unreferenced(&mut self) -> Result<ContentPunchStats> {
        self.punch_unreferenced_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::punch_unreferenced`] with cooperative, resumable block checkpoints.
    ///
    /// Cancellation after the manifest declaration may leave some dead blocks declared but not yet
    /// deallocated. That is a safe, durable partial state: reads already treat the blocks as erased,
    /// and a later call retries every still-present declared block.
    pub fn punch_unreferenced_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<ContentPunchStats> {
        let started = std::time::Instant::now();
        let result = self.punch_unreferenced_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::ContentPunch,
            started.elapsed(),
            &result,
        );
        result
    }

    fn punch_unreferenced_inner_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<ContentPunchStats> {
        self.ensure_writer_usable()?;
        control.check("content punching")?;
        if !self.mem.is_empty() {
            bail!("punching requires a flushed memtable; call sync() and flush() first");
        }
        // Every block a present record can still reach through its owning Part dictionary.
        let live_blocks: HashSet<u32> = self
            .live_fold_pieces_with_control(control)?
            .keys()
            .map(|location| location.block_id)
            .collect();
        // ... against every block the fold holds.
        let mut dead: Vec<u32> =
            self.fold.block_ids().into_iter().filter(|b| !live_blocks.contains(b)).collect();
        dead.sort_unstable();
        let already: HashSet<u32> =
            self.manifest.punched.iter().flat_map(|&(lo, hi)| lo..=hi).collect();
        if dead.is_empty() {
            return Ok(ContentPunchStats::default());
        }

        // Record first, punch second. Already-declared blocks stay in `dead`: a crash or
        // cancellation can land after this authority is durable but before every hole is punched,
        // and retrying those blocks is how the operation actually resumes.
        if dead.iter().any(|block| !already.contains(block)) {
            let prepared = (|| -> Result<Manifest> {
                control.check("content punching")?;
                let mut manifest = self.manifest.clone();
                let mut all: Vec<u32> = already.into_iter().chain(dead.iter().copied()).collect();
                all.sort_unstable();
                manifest.punched = to_ranges(&all);
                let tail = self.fold.sync()?;
                manifest.fold_seg = tail.seg;
                manifest.fold_off = tail.off;
                let mut container = self.container.lock().expect("container lock poisoned");
                manifest.commit_into_container(&mut container)?;
                // The declaration is a manifest-revision publication like any other: it prunes
                // the oldest retained revision, so members only that revision pinned must join
                // the free list in the same container state. Every open validates the exact
                // member namespace, and a part no manifest names would otherwise refuse the store.
                sweep_unreachable_container(&mut container, &manifest, self.read_limits)?;
                Ok(manifest)
            })();
            let m = match prepared {
                Ok(manifest) => manifest,
                Err(error) => {
                    return Err(
                        self.discard_staged_and_require_reopen("content-punch preparation", error)
                    );
                }
            };
            let mut c = self.container.lock().expect("container lock poisoned");
            let publication_error = match c.commit() {
                Ok(_) => None,
                Err(error) if c.failed_publication_selected() == Some(true) => Some(error),
                Err(error) => return Err(error),
            }; // the declaration is selected BEFORE any byte is destroyed
            drop(c);
            self.manifest = m;
            self.note_manifest_commit();
            self.fold.declare_punched(&self.manifest.punched);
            if let Some(error) = publication_error {
                return Err(error).context(
                    "container selected the content-punch declaration, but its final synchronization failed",
                );
            }
        }
        // Declare before destroying, the same order the manifest write follows and for the same
        // reason: at no point may a block's bytes be gone while this fold still calls it content.
        self.fold.declare_punched(&self.manifest.punched);

        // A selected declaration whose final publication barrier returned an error is current to
        // this process but not yet safe as crash authority. Obtain a successful barrier before
        // destroying bytes; otherwise a crash could revive the predecessor without the punched
        // declaration while leaving the holes behind.
        self.container.lock().expect("container lock poisoned").acknowledge_current_state()?;

        let punched = self.fold.punch_blocks_with_control(&dead, control)?;
        Ok(ContentPunchStats { blocks_punched: punched.len(), blocks_examined: dead.len() })
    }

    /// Rewrite the fold, keeping only content that live records still reference.
    ///
    /// The only operation that rewrites reachable fold content and rebuilds parts around its new
    /// locations. Content punch can deallocate payloads already declared unreachable; refold moves
    /// the content that remains, which is why this is a separate call rather than a merge flag.
    ///
    /// Requires a flushed memtable — staged records reference the old fold, and rebuilding parts under
    /// them would leave their pieces unresolvable. Returns no-op statistics without a transition
    /// when the current authority references no parts.
    pub fn refold(&mut self) -> Result<refold::RefoldStats> {
        self.refold_with_control(&crate::control::OperationControl::default())
    }

    /// Estimate duplicate-generation space for a future refold without decoding records/content.
    ///
    /// Source and retention bytes are exact. The stage estimate assumes the current logical fold
    /// plus uncompressed part sections and explicit framing allowance; it is conservative planning
    /// evidence, not a hard admission bound.
    pub fn estimate_refold_space(&self) -> Result<Option<RefoldSpaceEstimate>> {
        self.estimate_refold_space_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::estimate_refold_space`] with cooperative source and inventory checkpoints.
    pub fn estimate_refold_space_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<RefoldSpaceEstimate>> {
        control.check("refold space preflight")?;
        if !self.mem.is_empty() {
            bail!("refold space estimation requires a flushed memtable; call sync() and flush() first");
        }
        if self.parts.is_empty() {
            return Ok(None);
        }
        let source_fold_logical_bytes = self.fold.disk_bytes();
        let mut source_part_bytes = 0u64;
        let mut source_part_sections = 0usize;
        let mut source_part_raw_section_bytes = 0u64;
        for (part, part_ref) in self.parts.iter().zip(&self.manifest.parts) {
            control.check("refold space preflight")?;
            source_part_bytes = source_part_bytes
                .checked_add(self.part_member_bytes(&part_ref.member)?)
                .ok_or_else(|| anyhow::anyhow!("refold source part byte count overflow"))?;
            for (_, _, raw, _) in part.sections() {
                control.check("refold space preflight")?;
                source_part_sections = source_part_sections
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("refold section count overflow"))?;
                source_part_raw_section_bytes = source_part_raw_section_bytes
                    .checked_add(u64::from(raw))
                    .ok_or_else(|| anyhow::anyhow!("refold raw section byte count overflow"))?;
            }
        }
        let rows = self.manifest.parts.iter().try_fold(0u64, |rows, part| {
            rows.checked_add(u64::from(part.records))
                .ok_or_else(|| anyhow::anyhow!("refold row count overflow"))
        })?;
        let row_allowance = rows
            .checked_mul(64)
            .ok_or_else(|| anyhow::anyhow!("refold row framing estimate overflow"))?;
        let section_allowance = u64::try_from(source_part_sections)
            .map_err(|_| anyhow::anyhow!("refold section count exceeds u64"))?
            .checked_mul(256)
            .ok_or_else(|| anyhow::anyhow!("refold section framing estimate overflow"))?;
        let estimated_stage_bytes = source_fold_logical_bytes
            .checked_add(source_part_raw_section_bytes)
            .and_then(|bytes| bytes.checked_add(row_allowance))
            .and_then(|bytes| bytes.checked_add(section_allowance))
            .and_then(|bytes| bytes.checked_add(1 << 20))
            .ok_or_else(|| anyhow::anyhow!("refold stage estimate overflow"))?;
        let usage = self.space_usage_with_control(control)?;
        Ok(Some(RefoldSpaceEstimate {
            source_fold_logical_bytes,
            source_part_bytes,
            source_part_sections,
            source_part_raw_section_bytes,
            retained_only_bytes_before: usage.retained_only.logical_bytes,
            estimated_stage_bytes,
            estimate_is_hard_bound: false,
            filesystem_available_bytes: usage.filesystem_available_bytes,
        }))
    }

    /// [`Store::refold`] with cooperative checkpoints before the generation swap.
    ///
    /// Cancellation removes the unpublished generation and rebuilt parts. Once publication is
    /// attempted, cancellation is no longer observed: the crash-safe commit protocol and mandatory
    /// handle/retention cleanup must run to a definite result.
    pub fn refold_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<refold::RefoldStats> {
        let started = std::time::Instant::now();
        let result = self.refold_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Refold,
            started.elapsed(),
            &result,
        );
        result
    }

    fn refold_inner_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<refold::RefoldStats> {
        self.ensure_writer_usable()?;
        control.check("content refold")?;
        if !self.mem.is_empty() {
            bail!("refold requires a flushed memtable; call sync() and flush() first");
        }
        if self.parts.is_empty() {
            return Ok(refold::RefoldStats::default());
        }
        self.refold_in_file(self.container.clone(), control)
    }

    /// The refold's single-file form. The build stages a whole new generation and its rebuilt
    /// parts as uncommitted members; publication is ONE flip carrying the swap, the retained-log
    /// purge, and the sweep's frees. A crash cannot land between the swap and purge because they
    /// are one commit. Time travel does not cross a refold.
    fn refold_in_file(
        &mut self,
        container: std::sync::Arc<std::sync::Mutex<crate::container::Container>>,
        control: &crate::control::OperationControl,
    ) -> Result<refold::RefoldStats> {
        let seqs: Vec<(u64, u64)> =
            self.manifest.parts.iter().map(|p| (p.seq_lo, p.seq_hi)).collect();
        let built_generation = refold::refold_into_container_with_control_and_limits(
            container.clone(),
            &self.parts,
            &seqs,
            &self.fold,
            self.manifest.fold_gen,
            self.cfg,
            control,
            self.read_limits,
        );
        let (new_gen, built, mut stats, nf) = match built_generation {
            Ok(built) => built,
            Err(error) => {
                return match container.lock().expect("container lock poisoned").discard_staged() {
                    Ok(()) => Err(error),
                    Err(cleanup) => {
                        self.requires_reopen = true;
                        Err(cleanup.context(format!(
                            "refold build failed ({error:#}); discarding its isolated staged generation also failed and writer requires reopen"
                        )))
                    }
                };
            }
        };

        let mut m = self.manifest.clone();
        m.parts = built
            .iter()
            .map(|(file, lo, hi, n, b3)| PartRef {
                member: file.clone(),
                seq_lo: *lo,
                seq_hi: *hi,
                records: *n,
                b3: b3.clone(),
            })
            .collect();
        m.fold_gen = new_gen;
        // Block ids are PER GENERATION; the new fold has no holes to declare.
        m.punched.clear();
        let t = nf.tail();
        m.fold_seg = t.seg;
        m.fold_off = t.off;
        if let Err(error) = control.check("content refold publication") {
            return match container.lock().expect("container lock poisoned").discard_staged() {
                Ok(()) => Err(error.into()),
                Err(cleanup) => {
                    self.requires_reopen = true;
                    Err(cleanup.context(format!(
                        "content refold was cancelled ({error}); discarding its isolated staged generation also failed and writer requires reopen"
                    )))
                }
            };
        }
        let staged = (|| -> Result<()> {
            let mut c = container.lock().expect("container lock poisoned");
            m.commit_into_container(&mut c)?;
            // The purge, staged into the SAME commit: every retained manifest except this
            // commit's own goes, because a retained name would keep the superseded generation —
            // deleted content included — readable for MANIFEST_RETAIN more commits.
            for commit in container_retained_commits(&c) {
                if commit != m.commit {
                    c.remove(&format!("MANIFEST.{commit:08}"))?;
                }
            }
            // With no retained pins left, the sweep frees the old generation and every
            // superseded part in the same state that abandons them.
            sweep_unreachable_container(&mut c, &m, self.read_limits)?;
            Ok(())
        })();
        if let Err(error) = staged {
            return match container.lock().expect("container lock poisoned").discard_staged() {
                Ok(()) => Err(error),
                Err(cleanup) => {
                    self.requires_reopen = true;
                    Err(cleanup.context(format!(
                        "refold preparation failed ({error:#}); discarding its isolated staged generation also failed and writer requires reopen"
                    )))
                }
            };
        }
        // Open every newly staged part while the predecessor is still authoritative. After the
        // container-state flip, Store adoption must be a nonfallible pointer/state swap; otherwise
        // a transient extent read can leave this live writer holding the successor manifest, a
        // partial part list, and the predecessor Fold.
        let part_cache_budget = self.pcache.budget();
        let new_cache = Arc::new(SectionCache::new(part_cache_budget));
        let prepared_parts = (|| -> Result<Vec<Arc<Part>>> {
            let mut parts = Vec::new();
            parts.try_reserve_exact(m.parts.len()).context("reserve refolded part handles")?;
            for part in &m.parts {
                let reader = container
                    .lock()
                    .expect("container lock poisoned")
                    .extent(&part.member)
                    .ok_or_else(|| {
                        anyhow::anyhow!("refold staged {} but the container lost it", part.member)
                    })?;
                parts.push(Arc::new(Part::open_reader_with_limits(
                    Box::new(reader),
                    new_cache.clone(),
                    self.read_limits,
                )?));
            }
            Ok(parts)
        })();
        let prepared_parts = match prepared_parts {
            Ok(parts) => parts,
            Err(error) => {
                return match container.lock().expect("container lock poisoned").discard_staged() {
                    Ok(()) => Err(error).context("open staged refold parts before publication"),
                    Err(cleanup) => {
                        self.requires_reopen = true;
                        Err(cleanup.context(format!(
                            "opening staged refold parts failed ({error:#}); discarding them also failed and writer requires reopen"
                        )))
                    }
                };
            }
        };
        let publication_error = {
            let mut c = container.lock().expect("container lock poisoned");
            match c.commit() {
                Ok(_) => None,
                Err(error) if c.failed_publication_selected() == Some(true) => Some(error),
                Err(error) => return Err(error).context("publish the rebuilt fold generation"),
            }
        };

        self.manifest = m;
        self.note_manifest_commit();
        self.retained_commit_count = 1;
        self.pcache = new_cache;
        self.parts = prepared_parts;
        self.fold = nf;
        // Freed in the same flip that abandoned it: there is no stale generation to report.
        stats.stale_generation_left = false;
        if let Some(error) = publication_error {
            return Err(error).context(
                "container selected the refolded manifest revision, but its final synchronization failed",
            );
        }
        Ok(stats)
    }

    /// Return the space this file's history has already abandoned: deallocate the aligned
    /// interior of free extents older than the retention window, in place, offsets unmoved.
    ///
    /// The single-file complement to [`Store::punch_unreferenced`]: that one destroys dead
    /// CONTENT blocks under a manifest declaration; this one destroys extents the sweep already
    /// free-listed — superseded parts, purged manifests, abandoned fold generations — whose only
    /// remaining claim is the free list itself. The grace window (the manifest retention window,
    /// in commits) is what keeps a reader holding a recent superblock exact rather than erroring;
    /// a reader older than that reads zeros and fails checksums — detected, never silent.
    ///
    pub fn punch_free_space(&mut self) -> Result<crate::container::FreePunchStats> {
        self.ensure_writer_usable()?;
        let mut c = self.container.lock().expect("container lock poisoned");
        c.acknowledge_current_state()?;
        c.punch_free_extents(MANIFEST_RETAIN as u64)
    }

    /// Bytes pinned by every open part's section caches, against their shared budget.
    pub fn part_cache_bytes(&self) -> (usize, usize) {
        (self.pcache.bytes(), self.pcache.budget())
    }

    /// Pieces resident in the Tier-0 dedup window. Bounded by the flush interval, not by store size.
    pub fn dedup_window_len(&self) -> usize {
        self.fold.window_len()
    }
    /// Return the in-memory authority fields. `commit == 0` encodes the canonical origin and is not
    /// a manifest revision.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }
    pub fn fold(&self) -> &Fold {
        &self.fold
    }
    pub fn wal_bytes(&self) -> u64 {
        self.wal.bytes()
    }

    /// A constant-work snapshot of operational state. No records or content are decoded.
    pub fn health(&self) -> StoreHealth {
        let fold_cache = self.fold.cache_stats();
        let (part_cache_bytes, part_cache_budget) = self.part_cache_bytes();
        let punched_blocks =
            self.manifest.punched.iter().map(|&(lo, hi)| u64::from(hi) - u64::from(lo) + 1).sum();
        StoreHealth {
            commit: self.manifest.commit,
            fold_generation: self.manifest.fold_gen,
            parts: self.parts.len(),
            part_rows: self.manifest.parts.iter().map(|part| u64::from(part.records)).sum(),
            memtable_entries: self.mem.len(),
            memtable_bytes: self.mem_bytes,
            wal_bytes: self.wal.bytes(),
            wal_frames: self.wal.frame_count(),
            fold_disk_bytes: self.fold.disk_bytes(),
            fold_segments: self.fold.segment_count(),
            fold_cache_hits: fold_cache.hits,
            fold_cache_misses: fold_cache.misses,
            fold_cache_bytes: fold_cache.bytes,
            fold_cache_budget: fold_cache.budget,
            fold_block_target_bytes: self.cfg.block_target,
            fold_segment_max_bytes: self.cfg.seg_max,
            fold_compression_level: self.cfg.level,
            fold_compression_threads: self.cfg.compress_threads,
            part_cache_bytes,
            part_cache_budget,
            max_stored_frame_bytes: self.read_limits.max_stored_frame_bytes,
            max_decoded_frame_bytes: self.read_limits.max_decoded_frame_bytes,
            max_directory_entries: self.read_limits.max_directory_entries,
            max_wal_frames: self.read_limits.max_wal_frames,
            max_fold_blocks: self.read_limits.max_fold_blocks,
            dedup_window_entries: self.fold.window_len(),
            retained_commits: self.retained_commit_count,
            punched_blocks,
        }
    }

    /// Classify container bytes by manifest reachability.
    ///
    /// This is intentionally separate from [`Store::health`]: it performs filesystem traversal and
    /// parses the retained window, so callers opt into its cost. No records, column values, or
    /// content are decoded.
    pub fn space_usage(&self) -> Result<StoreSpaceUsage> {
        self.space_usage_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::space_usage`] with cooperative checks between manifests and filesystem entries.
    pub fn space_usage_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<StoreSpaceUsage> {
        let c = self.container.lock().expect("container lock poisoned");
        container_space_usage(&c, &self.path, &self.manifest, self.read_limits, control)
    }

    /// Discover attribute names/types and named-content columns without decoding stored values.
    pub fn schema(&self) -> Result<crate::schema::Schema> {
        let mut schema = crate::schema::Builder::default();
        schema.add_parts(&self.parts)?;
        for record in self.mem.values().flatten() {
            schema.add_record(record);
        }
        Ok(schema.finish())
    }
}

/// [`store_space_usage`]'s single-file form: members classified by the same reachability rules
/// — current manifest revision, retained manifest revisions, and their fold generations — with the WAL sidecar counted
/// live and the free list counted unclassified: bytes the file holds that no reachable name
/// claims, which is exactly what that bucket means. `total` is the additive total of classified
/// member payload, free extents, and the WAL sidecar. Container superblocks, directory encodings,
/// and alignment padding are structural overhead and are deliberately outside these buckets.
fn container_space_usage(
    c: &crate::container::Container,
    path: &Path,
    live_manifest: &Manifest,
    _read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<StoreSpaceUsage> {
    control.check("store space inventory")?;
    let mut live_members: std::collections::HashSet<String> =
        std::iter::once("MANIFEST".to_string()).collect();
    live_members.extend(live_manifest.parts.iter().map(|p| p.member.clone()));
    let live_prefix = crate::fold::fold_member_prefix(live_manifest.fold_gen);

    let mut retained_members: std::collections::HashSet<String> = Default::default();
    let mut retained_prefixes: std::collections::HashSet<String> = Default::default();
    for commit in container_retained_commits(c) {
        control.check("store space inventory")?;
        let name = format!("MANIFEST.{commit:08}");
        let bytes = c
            .read_file_bounded(&name, MAX_MANIFEST_BYTES)
            .with_context(|| format!("account retained manifest {commit}"))?;
        let m = Manifest::parse(&bytes)
            .with_context(|| format!("account retained manifest {commit}"))?;
        retained_members.insert(name);
        retained_members.extend(m.parts.into_iter().map(|p| p.member));
        retained_prefixes.insert(crate::fold::fold_member_prefix(m.fold_gen));
    }

    let mut usage = StoreSpaceUsage {
        filesystem_available_bytes: crate::sys::filesystem_available_bytes(
            path.parent().unwrap_or_else(|| Path::new(".")),
        )
        .with_context(|| format!("measure available filesystem bytes at {}", path.display()))?,
        ..StoreSpaceUsage::default()
    };
    let add = |amount: &mut SpaceAmount, bytes: u64| {
        amount.members += 1;
        amount.logical_bytes += bytes;
    };
    for name in c.names().map(String::from).collect::<Vec<String>>() {
        control.check("store space inventory")?;
        let len = c.member_len(&name).unwrap_or(0);
        let gen = fold_generation_of_member(&name);
        let is_live = live_members.contains(&name)
            || gen.map(|g| crate::fold::fold_member_prefix(g) == live_prefix).unwrap_or(false);
        let is_retained = retained_members.contains(&name)
            || gen
                .map(|g| retained_prefixes.contains(&crate::fold::fold_member_prefix(g)))
                .unwrap_or(false);
        if is_live {
            add(&mut usage.live, len);
        } else if is_retained {
            add(&mut usage.retained_only, len);
        } else {
            add(&mut usage.unclassified, len);
        }
    }
    let wal = file_wal_path(path);
    if let Ok(meta) = std::fs::metadata(&wal) {
        add(&mut usage.live, meta.len());
    }
    // The free list: bytes present under no reachable name. Zero members — extents are not members.
    usage.unclassified.logical_bytes += c.free_bytes();
    // Totals stay bucket-additive — the accounting identity every consumer of this struct
    // checks. Structural overhead (superblocks, the directory, alignment padding) is uncounted;
    // the file's own length is one stat away for anyone asking the other question.
    usage.total.members =
        usage.live.members + usage.retained_only.members + usage.unclassified.members;
    usage.total.logical_bytes = usage.live.logical_bytes
        + usage.retained_only.logical_bytes
        + usage.unclassified.logical_bytes;
    Ok(usage)
}

/// Exact physical-input bounds for one incremental compaction step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CompactionBudget {
    /// Maximum number of adjacent immutable parts admitted to one work unit.
    pub max_input_parts: usize,
    /// Maximum physical rows across the admitted input parts.
    pub max_input_rows: u64,
    /// Maximum sum of the admitted input part member lengths.
    pub max_input_bytes: u64,
}

impl CompactionBudget {
    /// Reject structurally unusable limits before any maintenance work begins.
    pub fn validate(self) -> std::result::Result<(), CompactionError> {
        if self.max_input_parts < 2 {
            return Err(CompactionError::InvalidBudget(
                "max_input_parts must be at least 2".into(),
            ));
        }
        if self.max_input_rows == 0 {
            return Err(CompactionError::InvalidBudget(
                "max_input_rows must be greater than zero".into(),
            ));
        }
        if self.max_input_bytes == 0 {
            return Err(CompactionError::InvalidBudget(
                "max_input_bytes must be greater than zero".into(),
            ));
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// An exact contiguous input selection from the part list referenced by current authority.
pub struct CompactionPlan {
    /// Zero-based index of the oldest selected part.
    pub start_part: usize,
    /// Number of adjacent parts selected.
    pub input_parts: usize,
    /// Physical rows across the selected part members.
    pub input_rows: u64,
    /// Sum of the selected part members' exact logical lengths.
    pub input_bytes: u64,
    /// Whether this run covers the complete referenced part list and may drop tombstones.
    pub drops_tombstones: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// Space facts and an explicitly advisory stage estimate for one compaction plan.
pub struct CompactionSpaceEstimate {
    pub plan: CompactionPlan,
    pub input_sections: usize,
    pub input_raw_section_bytes: u64,
    pub estimated_stage_bytes: u64,
    pub estimate_is_hard_bound: bool,
    /// Selected inputs remain pinned by the immediately preceding retained manifest after commit.
    pub retained_input_bytes_after_commit: u64,
    pub filesystem_available_bytes: Option<u64>,
}

#[derive(Clone, Copy, Debug)]
/// Evidence returned after one bounded compaction work unit is published.
pub struct BoundedCompaction {
    /// The exact input plan that was executed.
    pub plan: CompactionPlan,
    /// Exact on-disk length of the newly published output part.
    pub output_bytes: u64,
    /// Logical merge counters.
    pub merge: crate::part::merge::MergeStats,
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// A budget that cannot describe or admit a compaction work unit.
pub enum CompactionError {
    /// One or more limits are structurally unusable.
    InvalidBudget(String),
    /// At least two parts exist, but no adjacent pair fits all supplied limits.
    BudgetTooSmall {
        /// Start of a concrete smallest-byte adjacent pair.
        start_part: usize,
        /// Physical rows required by that pair.
        input_rows: u64,
        /// Exact file bytes required by that pair.
        input_bytes: u64,
        /// Limits that rejected the pair.
        budget: CompactionBudget,
    },
}

impl std::fmt::Display for CompactionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompactionError::InvalidBudget(reason) => write!(f, "invalid compaction budget: {reason}"),
            CompactionError::BudgetTooSmall {
                start_part,
                input_rows,
                input_bytes,
                budget,
            } => write!(
                f,
                "no adjacent part pair fits the compaction budget; the smallest-byte pair starts at part {start_part} and needs {input_rows} rows / {input_bytes} bytes, limits are {} rows / {} bytes",
                budget.max_input_rows,
                budget.max_input_bytes
            ),
        }
    }
}

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

/// What [`Store::punch_unreferenced`] did.
#[derive(Clone, Copy, Debug, Default)]
pub struct ContentPunchStats {
    pub blocks_examined: usize,
    /// Fewer than examined when blocks sit in the active segment, which is never punched.
    pub blocks_punched: usize,
}

/// Collapse a sorted id list into inclusive ranges.
fn to_ranges(ids: &[u32]) -> Vec<(u32, u32)> {
    let mut out: Vec<(u32, u32)> = Vec::new();
    for &id in ids {
        match out.last_mut() {
            Some(last) if last.1 + 1 == id => last.1 = id,
            Some(last) if last.1 >= id => {}
            _ => out.push((id, id)),
        }
    }
    out
}

/// What an erasure did.
#[derive(Clone, Copy, Debug)]
pub struct ErasureStats {
    pub requested: usize,
    pub tombstoned: usize,
    /// Named but already gone. A normal outcome, recorded rather than errored.
    pub absent: usize,
    /// Live records remaining after this operation completed.
    pub remaining: usize,
    /// `None` when nothing existed to erase and the store was left untouched.
    pub refold: Option<refold::RefoldStats>,
}

/// A reader over one store authority. No lock, no writer, no daemon. Clones retain the same
/// immutable parts and fold handles, making ownership by concurrent query streams cheap.
#[derive(Clone)]
pub struct ReadStore {
    fold: Arc<Fold>,
    parts: Vec<Arc<Part>>,
    manifest: Manifest,
    read_limits: ReadLimits,
}

/// A read-only store is the authority-pinned read core, with nothing layered on top — so every method here
/// is a direct delegation, and there is no second implementation to keep in step.
impl ReadStore {
    /// Atomic persisted-frame admission governing this immutable handle.
    pub fn read_limits(&self) -> ReadLimits {
        self.read_limits
    }

    pub fn get(&self, id: &str) -> Result<Option<Record>> {
        verification_integrity("read committed record", read::get(&self.parts, id))
    }

    pub(crate) fn project_candidates(
        &self,
        candidates: &[crate::scan::ScanCandidate],
        attrs: &HashSet<&str>,
        contents: &HashSet<&str>,
    ) -> Result<Vec<Record>> {
        let committed: Result<Vec<_>> = candidates
            .iter()
            .map(|candidate| match candidate {
                crate::scan::ScanCandidate::Committed(row) => Ok(row),
                crate::scan::ScanCandidate::Memtable(id) => {
                    bail!("immutable snapshot received memtable row {id:?}")
                }
            })
            .collect();
        read::project_rows(&self.parts, &committed?, attrs, contents)
    }

    pub(crate) fn reconstruct_candidate_content(
        &self,
        candidate: &crate::scan::ScanCandidate,
        content: &Content,
    ) -> Result<Vec<u8>> {
        match candidate {
            crate::scan::ScanCandidate::Committed(row) => {
                read::reconstruct_projected_content(&self.parts, &self.fold, row, content)
            }
            crate::scan::ScanCandidate::Memtable(id) => {
                bail!("immutable snapshot received memtable row {id:?}")
            }
        }
    }

    pub fn reconstruct(&self, id: &str) -> Result<Option<Vec<u8>>> {
        verification_integrity(
            "reconstruct committed content",
            read::reconstruct(&self.parts, &self.fold, id),
        )
    }

    /// Byte-exact named content, if both the record and value are present.
    pub fn reconstruct_content(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
        verification_integrity(
            "reconstruct committed content",
            read::reconstruct_content(&self.parts, &self.fold, id, name),
        )
    }

    /// Distinct committed ids, sorted — the union across parts, newest-wins.
    pub fn ids(&self) -> Result<Vec<String>> {
        read::ids(&self.parts)
    }

    /// Bounded structured paging over this immutable read view.
    pub fn scan(&self, request: &crate::scan::ScanRequest) -> Result<crate::scan::ScanPage> {
        crate::scan::scan_read_store(self, request)
    }

    pub(crate) fn candidate_may_match(
        &self,
        candidate: &crate::scan::ScanCandidate,
        predicates: &[crate::scan::Predicate],
    ) -> Result<bool> {
        let crate::scan::ScanCandidate::Committed(row) = candidate else {
            return Ok(true);
        };
        match row.origin {
            read::RowOrigin::Part { part, .. } => read::part_may_match(
                self.parts
                    .get(part)
                    .ok_or_else(|| anyhow::anyhow!("candidate part is outside the snapshot"))?,
                predicates,
            ),
            read::RowOrigin::Memtable => Ok(true),
        }
    }

    /// Explain a structured scan against this immutable snapshot without resolving rows or
    /// evaluating predicates.
    pub fn explain_scan(
        &self,
        request: &crate::scan::ScanRequest,
    ) -> Result<crate::scan::ScanExplanation> {
        crate::scan::explain_read_store(self, request)
    }

    pub(crate) fn scan_physical_scope(
        &self,
        from: Option<&str>,
        to: Option<&str>,
    ) -> Result<crate::scan::ScanPhysicalScope> {
        read::scan_physical_scope(&self.parts, from, to)
    }

    /// Live ids in `[from, to)`, at most `limit`, id-ordered or reversed — the paged read.
    ///
    /// Only ids inside the range are decoded, so the cost tracks the page rather than the store.
    /// Ids sort lexicographically, so ids designed with the query in mind (a `member/timestamp/…`
    /// prefix) give member-then-time paging with no secondary index.
    pub fn scan_ids(
        &self,
        from: Option<&str>,
        to: Option<&str>,
        limit: usize,
        reverse: bool,
    ) -> Result<Vec<String>> {
        Ok(self
            .scan_candidates(from, to, limit, reverse, usize::MAX, true)?
            .candidates
            .into_iter()
            .map(crate::scan::ScanCandidate::into_id)
            .collect())
    }

    pub(crate) fn scan_candidates(
        &self,
        from: Option<&str>,
        to: Option<&str>,
        limit: usize,
        reverse: bool,
        max_resolution_entries: usize,
        allow_oversized_group: bool,
    ) -> Result<crate::scan::CandidateBatch> {
        check_range(from, to)?;
        let resolved = read::scan_rows(
            &self.parts,
            std::iter::empty::<(&str, bool)>(),
            read::RowScan {
                from,
                to,
                limit,
                reverse,
                max_resolution_entries,
                allow_oversized_group,
            },
        )?;
        Ok(crate::scan::CandidateBatch {
            candidates: resolved
                .rows
                .into_iter()
                .map(crate::scan::ScanCandidate::Committed)
                .collect(),
            resolution: crate::scan::ScanResolutionStats {
                physical_rows: resolved.physical_rows,
                superseded_rows: resolved.superseded_rows,
                tombstones: resolved.tombstones,
                memtable_entries: resolved.memtable_entries,
                budget_exhausted: resolved.budget_exhausted,
            },
            resolved_through: resolved.resolved_through,
            has_more: resolved.has_more,
        })
    }

    /// Hand the fold and parts to a lens. Consumes the store because the query layer takes ownership
    /// of both; the store authority it was opened at is already baked into `parts`.
    pub fn into_parts(self) -> (Arc<Fold>, Vec<Arc<Part>>) {
        (self.fold, self.parts)
    }

    pub fn part_count(&self) -> usize {
        self.parts.len()
    }
    /// Parts referenced by this read view's store authority, oldest to newest.
    pub fn parts(&self) -> &[Arc<Part>] {
        &self.parts
    }
    /// The fold, for tools that scrub or measure it.
    pub fn fold(&self) -> &Fold {
        &self.fold
    }
    /// Return the in-memory authority fields. `commit == 0` encodes the canonical origin and is not
    /// a manifest revision.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Discover this immutable snapshot's physical field universe without decoding stored values.
    pub fn schema(&self) -> Result<crate::schema::Schema> {
        let mut schema = crate::schema::Builder::default();
        schema.add_parts(&self.parts)?;
        Ok(schema.finish())
    }
}

fn approx_bytes(r: &Record) -> usize {
    r.id.len()
        + r.contents
            .iter()
            .map(|content| {
                content.name.len()
                    + content
                        .ops
                        .iter()
                        .map(|o| match o {
                            ContentOp::Lit(b) => b.len() + 8,
                            ContentOp::Piece { .. } => 40,
                        })
                        .sum::<usize>()
            })
            .sum::<usize>()
        + r.attrs.iter().map(|(k, _)| k.len() + 24).sum::<usize>()
}

// Positioned reads are the one thing with no fallback: every read in the engine is "n bytes at
// offset o", and emulating that with seek-then-read is not safe across threads. Unix and WASI both
// provide it. What WASI does NOT provide — advisory locking and hole punching — is degraded
// explicitly in `crate::sys` rather than refused here.

#[cfg(test)]
mod tests {

    #[test]
    fn manifest_promotion_validates_piece_locations_through_each_rows_owning_part() {
        use crate::fold::block::{self, Loc, CODEC_STORED};
        use crate::fold::segment::SegHeader;
        use crate::types::{Content, ContentHash, ContentOp, PieceHash, Record, BODY_CONTENT};
        use std::collections::HashMap;
        use std::sync::Arc;

        let root = std::env::temp_dir().join(format!(
            "turndb-promotion-owning-part-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        let fold_dir = root.join("fold");
        std::fs::create_dir_all(&fold_dir).unwrap();
        let bytes = b"same identity at two physical locations";
        let hash = PieceHash::of(bytes);
        let mut segment = SegHeader { seg: 0, flags: 0, dict_id: [0; 32] }.encode().to_vec();
        let mut frame = Vec::new();
        block::encode(&mut frame, 0, CODEC_STORED, bytes, bytes).unwrap();
        segment.extend_from_slice(&frame);
        block::encode(&mut frame, 1, CODEC_STORED, bytes, bytes).unwrap();
        segment.extend_from_slice(&frame);
        std::fs::write(fold_dir.join("seg-00000000.fold"), segment).unwrap();
        let cfg = crate::fold::FoldCfg::default();
        let fold = crate::fold::Fold::open_read_with_limits(
            &fold_dir,
            cfg,
            &[(0, 0)],
            crate::read_limits::ReadLimits::default(),
        )
        .unwrap();
        let loc0 = Loc { block_id: 0, in_off: 0, raw: bytes.len() as u32 };
        let loc1 = Loc { block_id: 1, in_off: 0, raw: bytes.len() as u32 };
        let record = |id: &str| {
            Record::new(
                id,
                vec![Content::identified(
                    BODY_CONTENT,
                    vec![ContentOp::Piece { hash, len: bytes.len() as u32 }],
                    ContentHash(hash.0),
                )],
                Vec::new(),
            )
            .unwrap()
        };
        let p1_path = root.join("p1.part");
        let p2_path = root.join("p2.part");
        crate::part::build_full(
            &p1_path,
            &[record("owned-by-punched")],
            &[],
            1,
            1,
            3,
            |_| Some(loc0),
            &HashMap::new(),
        )
        .unwrap();
        crate::part::build_full(
            &p2_path,
            &[record("unrelated-readable")],
            &[],
            2,
            2,
            3,
            |_| Some(loc1),
            &HashMap::new(),
        )
        .unwrap();
        let reader = super::ReadStore {
            fold: Arc::new(fold),
            parts: vec![
                Arc::new(crate::part::Part::open(&p1_path).unwrap()),
                Arc::new(crate::part::Part::open(&p2_path).unwrap()),
            ],
            manifest: super::Manifest::default(),
            read_limits: crate::read_limits::ReadLimits::default(),
        };
        let error = super::validate_candidate_records(
            &reader,
            &crate::control::OperationControl::default(),
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("ERASED"), "{error:#}");
        std::fs::remove_dir_all(root).ok();
    }

    #[test]
    fn content_reachability_preserves_every_owning_location_for_one_piece_identity() {
        use crate::fold::block::{self, Loc, CODEC_STORED};
        use crate::fold::segment::SegHeader;
        use crate::types::{Content, ContentHash, ContentOp, PieceHash, Record, BODY_CONTENT};
        use std::collections::HashMap;
        use std::sync::Arc;

        let root = std::env::temp_dir().join(format!(
            "turndb-reachability-owning-part-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        let fold_dir = root.join("fold");
        std::fs::create_dir_all(&fold_dir).unwrap();
        let bytes = b"one identity stored at two locations";
        let hash = PieceHash::of(bytes);
        let mut segment = SegHeader { seg: 0, flags: 0, dict_id: [0; 32] }.encode().to_vec();
        let mut frame = Vec::new();
        block::encode(&mut frame, 0, CODEC_STORED, bytes, bytes).unwrap();
        segment.extend_from_slice(&frame);
        block::encode(&mut frame, 1, CODEC_STORED, bytes, bytes).unwrap();
        segment.extend_from_slice(&frame);
        std::fs::write(fold_dir.join("seg-00000000.fold"), segment).unwrap();
        let fold = crate::fold::Fold::open_read_with_limits(
            &fold_dir,
            crate::fold::FoldCfg::default(),
            &[],
            crate::read_limits::ReadLimits::default(),
        )
        .unwrap();
        let loc0 = Loc { block_id: 0, in_off: 0, raw: bytes.len() as u32 };
        let loc1 = Loc { block_id: 1, in_off: 0, raw: bytes.len() as u32 };
        let record = |id: &str| {
            Record::new(
                id,
                vec![Content::identified(
                    BODY_CONTENT,
                    vec![ContentOp::Piece { hash, len: bytes.len() as u32 }],
                    ContentHash(hash.0),
                )],
                Vec::new(),
            )
            .unwrap()
        };
        let p1_path = root.join("p1.part");
        let p2_path = root.join("p2.part");
        crate::part::build_full(
            &p1_path,
            &[record("row-at-block-zero")],
            &[],
            1,
            1,
            3,
            |_| Some(loc0),
            &HashMap::new(),
        )
        .unwrap();
        crate::part::build_full(
            &p2_path,
            &[record("unrelated-row-at-block-one")],
            &[],
            2,
            2,
            3,
            |_| Some(loc1),
            &HashMap::new(),
        )
        .unwrap();
        let parts = vec![
            Arc::new(crate::part::Part::open(&p1_path).unwrap()),
            Arc::new(crate::part::Part::open(&p2_path).unwrap()),
        ];
        let live = super::live_fold_pieces_with_control(
            &parts,
            &fold,
            &crate::control::OperationControl::default(),
        )
        .unwrap();
        assert_eq!(live.len(), 2, "identity-keyed reachability would collapse one location");
        assert_eq!(live.get(&loc0), Some(&hash));
        assert_eq!(live.get(&loc1), Some(&hash));
        assert_eq!(
            live.keys().map(|loc| loc.block_id).collect::<std::collections::BTreeSet<_>>(),
            std::collections::BTreeSet::from([0, 1]),
            "content punch must retain both blocks named by their owning live rows"
        );
        std::fs::remove_dir_all(root).ok();
    }

    #[cfg(any(target_os = "linux", target_os = "windows"))]
    #[test]
    fn punched_crc_exemption_names_only_segments_that_contain_declared_blocks() {
        let root = std::env::temp_dir().join(format!(
            "turndb-punched-segments-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        std::fs::create_dir_all(&root).unwrap();
        let path = root.join("store.turndb");
        let cfg = crate::fold::FoldCfg {
            block_target: 4 * 1024,
            seg_max: 16 * 1024,
            ..Default::default()
        };
        let noise = |seed: u64, len: usize| {
            let mut out = Vec::with_capacity(len);
            let mut hash = blake3::hash(&seed.to_le_bytes());
            while out.len() < len {
                out.extend_from_slice(hash.as_bytes());
                hash = blake3::hash(hash.as_bytes());
            }
            out.truncate(len);
            out
        };

        let mut store = super::Store::open_file(&path, cfg).unwrap();
        store.put("dead", &[super::Span::Piece(&noise(1, 6 * 1024))], vec![]).unwrap();
        store.sync().unwrap();
        store.flush().unwrap();
        for index in 0..8u64 {
            store
                .put(
                    &format!("live:{index}"),
                    &[super::Span::Piece(&noise(10 + index, 6 * 1024))],
                    vec![],
                )
                .unwrap();
        }
        store.sync().unwrap();
        store.flush().unwrap();
        store.delete("dead").unwrap();
        store.sync().unwrap();
        store.flush().unwrap();
        store.merge_range(0, store.part_count()).unwrap().unwrap();
        assert!(store.punch_unreferenced().unwrap().blocks_punched > 0);

        let container = crate::container::Container::open_internal(&path).unwrap();
        let segments = container
            .names()
            .filter(|name| name.ends_with(".fold"))
            .map(String::from)
            .collect::<std::collections::HashSet<_>>();
        let ignored = super::verified_punched_fold_members(
            &container,
            cfg,
            crate::read_limits::ReadLimits::default(),
            &crate::control::OperationControl::default(),
        )
        .unwrap();
        assert!(!ignored.is_empty(), "at least one segment contains a punched block");
        assert!(
            ignored.is_subset(&segments) && ignored.len() < segments.len(),
            "unaffected segments must retain their outer CRC: ignored={ignored:?}, segments={segments:?}"
        );
        drop(container);
        store.close().unwrap();
        std::fs::remove_dir_all(root).ok();
    }

    fn persisted_manifest() -> super::Manifest {
        super::Manifest { commit: 1, fold_off: 48, ..Default::default() }
    }

    fn manifest_bytes_with_part(member: &str) -> Vec<u8> {
        super::Manifest {
            parts: vec![super::PartRef {
                member: member.into(),
                seq_lo: 1,
                seq_hi: 1,
                records: 1,
                b3: "00".repeat(32),
            }],
            next_seq: 1,
            ..persisted_manifest()
        }
        .encode()
        .unwrap()
    }

    #[test]
    fn manifest_part_names_cannot_escape_the_store_root() {
        for hostile in
            ["../secret.part", "/absolute/secret.part", "nested/secret.part", "..\\secret.part"]
        {
            let error =
                super::Manifest::parse(&manifest_bytes_with_part(hostile)).unwrap_err().to_string();
            assert!(error.contains("canonical name"), "{hostile:?}: {error}");
        }
        assert!(
            super::Manifest::parse(&manifest_bytes_with_part("part-00000001.part")).is_ok(),
            "an ordinary current manifest is accepted"
        );
    }

    #[test]
    fn manifest_semantics_reject_ambiguous_or_malformed_authority() {
        let part = super::PartRef {
            member: "part-00000001.part".into(),
            seq_lo: 2,
            seq_hi: 1,
            records: 1,
            b3: "00".repeat(32),
        };
        let inverted = super::Manifest { parts: vec![part.clone()], ..persisted_manifest() };
        assert!(super::Manifest::parse(&inverted.encode().unwrap()).is_err());

        let duplicate = super::Manifest {
            parts: vec![
                super::PartRef { seq_lo: 1, seq_hi: 1, ..part.clone() },
                super::PartRef { seq_lo: 2, seq_hi: 2, ..part.clone() },
            ],
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&duplicate.encode().unwrap()).is_err());

        let bad_digest = super::Manifest {
            parts: vec![super::PartRef {
                seq_lo: 1,
                seq_hi: 1,
                b3: "not-a-blake3-digest".into(),
                ..part
            }],
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&bad_digest.encode().unwrap()).is_err());

        let overlapping = super::Manifest {
            parts: vec![
                super::PartRef {
                    member: "part-00000001-00000003.part".into(),
                    seq_lo: 1,
                    seq_hi: 3,
                    records: 1,
                    b3: "00".repeat(32),
                },
                super::PartRef {
                    member: "part-00000003-00000004.part".into(),
                    seq_lo: 3,
                    seq_hi: 4,
                    records: 1,
                    b3: "11".repeat(32),
                },
            ],
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&overlapping.encode().unwrap()).is_err());

        let stale_cursor = super::Manifest {
            parts: vec![super::PartRef {
                member: "part-00000001-00000007.part".into(),
                seq_lo: 1,
                seq_hi: 7,
                records: 1,
                b3: "22".repeat(32),
            }],
            next_seq: 6,
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&stale_cursor.encode().unwrap()).is_err());
        let current_cursor = super::Manifest { next_seq: 7, ..stale_cursor };
        assert!(super::Manifest::parse(&current_cursor.encode().unwrap()).is_ok());
        let ahead_cursor = super::Manifest { next_seq: 8, ..current_cursor };
        assert!(super::Manifest::parse(&ahead_cursor.encode().unwrap()).is_err());

        let zero_sequence = super::Manifest {
            parts: vec![super::PartRef {
                member: "part-00000000.part".into(),
                seq_lo: 0,
                seq_hi: 0,
                records: 0,
                b3: "33".repeat(32),
            }],
            next_seq: 0,
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&zero_sequence.encode().unwrap()).is_err());

        let gap = super::Manifest {
            parts: vec![
                super::PartRef {
                    member: "part-00000001.part".into(),
                    seq_lo: 1,
                    seq_hi: 1,
                    records: 1,
                    b3: "44".repeat(32),
                },
                super::PartRef {
                    member: "part-00000003.part".into(),
                    seq_lo: 3,
                    seq_hi: 3,
                    records: 1,
                    b3: "55".repeat(32),
                },
            ],
            next_seq: 3,
            ..persisted_manifest()
        };
        assert!(super::Manifest::parse(&gap.encode().unwrap()).is_err());

        let punched = super::Manifest { punched: vec![(5, 9), (9, 12)], ..Default::default() };
        assert!(super::Manifest::parse(&punched.encode().unwrap()).is_err());
    }

    #[test]
    fn manifest_origin_and_fold_tail_have_one_canonical_shape() {
        assert!(super::Manifest::parse(&super::Manifest::default().encode().unwrap()).is_err());
        let origin = persisted_manifest();
        assert!(super::Manifest::parse(&origin.encode().unwrap()).is_ok());

        let false_origin = super::Manifest { prev: Some("00".repeat(32)), ..origin.clone() };
        assert!(super::Manifest::parse(&false_origin.encode().unwrap()).is_err());
        let missing_predecessor = super::Manifest { commit: 2, ..origin.clone() };
        assert!(super::Manifest::parse(&missing_predecessor.encode().unwrap()).is_err());
        let unsupported_cursor = super::Manifest { next_seq: 1, ..origin.clone() };
        assert!(super::Manifest::parse(&unsupported_cursor.encode().unwrap()).is_err());
        let impossible_tail = super::Manifest { fold_seg: 1, fold_off: 0, ..origin };
        assert!(super::Manifest::parse(&impossible_tail.encode().unwrap()).is_err());
    }

    #[test]
    fn container_fold_sidecars_obey_explicit_read_limits_without_advisory_fallback() {
        let root = std::env::temp_dir().join(format!(
            "turndb-sidecar-limits-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        std::fs::create_dir_all(&root).unwrap();
        let path = root.join("store.turndb");
        let cfg =
            crate::fold::FoldCfg { block_target: 1, seg_max: 16 * 1024, ..Default::default() };
        let mut store = super::Store::open_file(&path, cfg).unwrap();
        for index in 0..1_200u32 {
            let bytes = index.to_le_bytes();
            store
                .put(&format!("id:{index:04}"), &[super::Span::Piece(&bytes)], Vec::new())
                .unwrap();
        }
        store.sync().unwrap();
        store.flush().unwrap();
        store.close().unwrap();

        let container = crate::container::Container::open(&path).unwrap();
        let manifest = super::Manifest::parse(
            &container.read_file_bounded("MANIFEST", super::MAX_MANIFEST_BYTES).unwrap(),
        )
        .unwrap();
        let sidecar_len = container
            .names()
            .filter(|name| name.ends_with(".dir"))
            .filter_map(|name| container.member_len(name))
            .max()
            .expect("the small-segment fixture must produce a directory sidecar");
        assert!(sidecar_len > 1);

        let strict = crate::read_limits::ReadLimits {
            max_stored_frame_bytes: sidecar_len - 1,
            ..Default::default()
        };
        let error = super::open_fold_from_container(&container, &manifest, cfg, &path, strict)
            .err()
            .expect("an over-budget sidecar must refuse rather than fall back");
        assert_eq!(crate::error::classify(&error), crate::error::ErrorClass::ResourceExhausted);
        assert!(matches!(
            error.downcast_ref::<crate::read_limits::ReadAdmissionError>(),
            Some(crate::read_limits::ReadAdmissionError::StoredFrameTooLarge { frame, .. })
                if frame.contains("fold directory sidecar")
        ));

        let nearest = crate::read_limits::ReadLimits {
            max_stored_frame_bytes: sidecar_len,
            ..Default::default()
        };
        super::open_fold_from_container(&container, &manifest, cfg, &path, nearest)
            .expect("the inclusive sidecar ceiling must admit the exact current fold");
        std::fs::remove_dir_all(root).ok();
    }

    /// The bug this exists to prevent: corruption that still PARSES. A shortened `fold_off` here
    /// would have become a false authority boundary and hidden durable fold bytes with no error.
    #[test]
    fn a_flipped_byte_that_still_parses_is_refused() {
        let d = std::env::temp_dir().join(format!("turndb-mancrc-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let m = super::Manifest { fold_off: 4096, next_seq: 9, ..Default::default() };
        let mut b = m.encode().unwrap();
        let at = b.windows(4).position(|w| w == b"4096").expect("fold_off literal in the JSON");
        b[at] = b'1'; // now claims fold_off 1096 — valid JSON, wrong bytes
        let err = super::Manifest::parse(&b).unwrap_err().to_string();
        assert!(err.contains("checksum"), "must refuse via the checksum, got: {err}");
        std::fs::remove_dir_all(&d).ok();
    }

    /// Damage to the trailer must never demote a manifest to unchecked JSON.
    #[test]
    fn a_damaged_trailer_is_refused() {
        let d = std::env::temp_dir().join(format!("turndb-mantrail-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let mut b = super::Manifest::default().encode().unwrap();
        let at = b.len() - 14; // the 'c' of the final "crc32=XXXXXXXX" line
        b[at] = b'x';
        assert!(super::Manifest::parse(&b).is_err(), "the required trailer must be exact");
        std::fs::remove_dir_all(&d).ok();
    }

    #[test]
    fn unchecked_or_pre_epoch_manifest_bytes_are_refused() {
        let old = br#"{"parts":[],"fold_seg":0,"fold_off":0,"next_seq":0}"#;
        assert!(super::Manifest::parse(old).is_err(), "bare JSON is not a current manifest");

        let current = super::Manifest { draft_epoch: 0, ..Default::default() };
        let error = super::Manifest::parse(&current.encode().unwrap()).unwrap_err().to_string();
        assert!(error.contains("draft epoch"), "{error}");

        let mut value = serde_json::to_value(super::Manifest::default()).unwrap();
        value.as_object_mut().unwrap().insert("discarded_field".into(), true.into());
        let mut unknown = serde_json::to_vec(&value).unwrap();
        let crc = crc32fast::hash(&unknown);
        unknown.extend_from_slice(format!("\ncrc32={crc:08x}").as_bytes());
        let error = format!("{:#}", super::Manifest::parse(&unknown).unwrap_err());
        assert!(
            error.contains("unknown field"),
            "a checksummed unknown field must refuse: {error}"
        );
    }
}