turndb 0.1.2

A content-addressed columnar store for AI traces: byte-exact, embedded, and readable by the CLI and the npm package over the same directory.
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
//! The store: WAL, memtable, flush, manifest, recovery — the layer that turns a fold and some parts
//! into a database.
//!
//! # Substrate
//!
//! A store is a **directory**, and reading one requires nothing but the files. 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 Unix 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.)
//!
//! [`Store::open_read`] takes no lock, replays nothing, and is safe to run
//! concurrently with a writer — parts are immutable and the fold is append-only, so a reader pinned to
//! a manifest sees a consistent store with no coordination at all.
//!
//! # The commit point
//!
//! The manifest is the only one. It names the live parts, the fold tail, and the log cursor;
//! everything else — the block directory, the dedup index, part contents — is derived. It is written
//! tmp + fsync + rename + fsync-dir, so a crash either sees the old manifest or the new one.
//!
//! # Ordering, and why recovery is simple
//!
//! ```text
//! put    -> fold.put (no fsync)  +  WAL append
//! sync   -> WAL fsync                        <- the ACK point
//! flush  -> fold.sync -> write part -> commit manifest -> truncate WAL
//! ```
//! Recovery does not try to work out how far the fold got. It **truncates the fold to the tail the
//! manifest committed** and replays the log, which carries the bytes of every piece that was new.
//! Anything the fold wrote past that tail is discarded and regenerated, so there is no window in
//! which a part could reference content that never landed.

pub mod container_store;
pub mod read;
pub mod refold;
pub mod wal;

pub use container_store::ContainerStore;

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, BodyOp, Content, ContentHash, PieceHash, Record, BODY_CONTENT};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::Read;
use std::path::{Component, 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 disk or a pack 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,
        }
    }
}

/// 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,
}

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,
        }
    }
}

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, 1 + 32); // present whole-content identity
        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) => {
                    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(_)))
        .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) => {
                    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)]
pub struct PartRef {
    pub file: String,
    pub seq_lo: u64,
    pub seq_hi: u64,
    pub records: u32,
    /// BLAKE3 of the part file's 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. Absent in manifests written before the chain existed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub b3: Option<String>,
}

/// How many committed manifests are RETAINED beside the live one, as `MANIFEST.<commit>`.
///
/// Retention is what turns the commit point into a log: every file a retained manifest names
/// survives the sweep, so a reader holding any manifest in the window sees its whole snapshot on
/// disk, and a corrupt `MANIFEST` is recoverable by explicit promotion instead of surgery. The
/// window is a count of COMMITS, not time — each flush, merge, or re-fold advances it by one.
pub const MANIFEST_RETAIN: usize = 4;

/// The committed state of the store. Small, atomic, and the only source of truth about what is live.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Manifest {
    pub parts: Vec<PartRef>,
    /// Which fold generation is live. A re-fold writes a new one and names it here, so the swap IS the
    /// manifest commit. Absent in stores written before re-folding existed, which serde reads as 0 —
    /// the original `fold/` directory, needing no migration.
    #[serde(default)]
    pub fold_gen: u32,
    pub fold_seg: u32,
    pub fold_off: u32,
    pub next_seq: u64,
    /// Monotonic commit counter — the retained log's namespace. `next_seq` cannot serve here: it
    /// only advances at flush, and merges and re-folds commit without flushing. Absent in stores
    /// written before the log existed, which serde reads as 0.
    #[serde(default)]
    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. Absent in manifests written before punching existed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub punched: Vec<(u32, u32)>,
    /// BLAKE3 of the PREVIOUS manifest's exact bytes, hex — the commit log as a hash chain, at
    /// zero marginal cost. Absent on a store's first commit and in manifests written before the
    /// chain existed.
    ///
    /// 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.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prev: Option<String>,
}

fn safe_part_file_name(name: &str) -> bool {
    if name.is_empty() || name.contains('\\') {
        return false;
    }
    let mut components = Path::new(name).components();
    matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
}

fn valid_blake3_hex(value: &str) -> bool {
    value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}

/// Read the one small authoritative file through a hard allocation boundary. Metadata is checked
/// first for the common/sparse-file case and `take(max + 1)` closes a concurrent-growth race.
pub(crate) fn read_manifest_file(path: &Path) -> Result<Vec<u8>> {
    let file = File::open(path)?;
    let announced = file.metadata()?.len();
    if announced > MAX_MANIFEST_BYTES {
        bail!(
            "MANIFEST at {} is {announced} bytes, exceeding the supported {MAX_MANIFEST_BYTES}-byte limit",
            path.display()
        );
    }
    let capacity =
        usize::try_from(announced).context("MANIFEST length does not fit this platform")?;
    let mut bytes = Vec::new();
    bytes.try_reserve_exact(capacity).context("reserve MANIFEST buffer")?;
    file.take(MAX_MANIFEST_BYTES + 1).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > MAX_MANIFEST_BYTES {
        bail!(
            "MANIFEST at {} grew past the supported {MAX_MANIFEST_BYTES}-byte limit while reading",
            path.display()
        );
    }
    Ok(bytes)
}

impl Manifest {
    /// A MISSING manifest is a new store. An UNREADABLE one is an error.
    ///
    /// These were conflated, and the orphan sweep made the conflation destructive: a transient EACCES
    /// or EIO yielded an empty manifest, and the sweep then unlinked every part it did not name. One
    /// unreadable byte turned a live store into an empty directory.
    #[cfg(test)]
    fn load(dir: &Path) -> Result<Manifest> {
        Self::load_with_limits(dir, ReadLimits::default())
    }

    fn load_with_limits(dir: &Path, read_limits: ReadLimits) -> Result<Manifest> {
        let path = dir.join("MANIFEST");
        match read_manifest_file(&path) {
            Ok(b) => Manifest::parse(&b),
            Err(e)
                if e.downcast_ref::<std::io::Error>()
                    .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
            {
                // A missing manifest is a new store — UNLESS a commit log exists, in which case
                // this store has committed before and `MANIFEST` was lost. Opening it as new
                // would be the destructive conflation all over again, one deletion further
                // upstream: an empty manifest followed by the sweep.
                let retained = list_retained_with_limits(dir, read_limits)?;
                if retained.is_empty() {
                    Ok(Manifest::default())
                } else {
                    bail!(
                        "MANIFEST is missing but {} retained commits exist at {} — a damaged \
                         store, not a new one; recover_manifest() can promote the newest intact copy",
                        retained.len(),
                        dir.display()
                    )
                }
            }
            Err(e) => Err(e.context(format!(
                "cannot read {} — refusing to treat an unreadable manifest as an empty store",
                path.display()
            ))),
        }
    }

    /// Parse manifest bytes, verifying the checksum trailer when one is present.
    ///
    /// The manifest is the one file whose corruption used to be able to DESTROY data with no error
    /// anywhere: it is parsed JSON, so a flipped bit that still parses — a shortened `fold_off`, a
    /// wrong generation — was believed, and recovery then truncated durable fold bytes to match it.
    /// Every other structure in the store refuses corruption; this closes the last gap.
    ///
    /// A manifest written before the trailer existed is bare compact JSON and is accepted as-is:
    /// the trailer is recognised by SHAPE (a final line `crc32=XXXXXXXX`), which compact JSON cannot
    /// end with. Corruption cannot demote a checksummed manifest to a legacy one either way it
    /// lands: mangling the trailer leaves trailing bytes that JSON parsing refuses, and mangling
    /// the payload fails the checksum.
    fn parse(bytes: &[u8]) -> Result<Manifest> {
        let payload = match checksum_trailer(bytes) {
            Some((payload, want)) => {
                let got = crc32fast::hash(payload);
                if got != want {
                    bail!(
                        "MANIFEST fails its checksum (crc32 {got:08x}, recorded {want:08x}) — \
                         refusing to open from a corrupt commit point"
                    );
                }
                payload
            }
            None => bytes,
        };
        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")?;
        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> {
        let mut files = HashSet::with_capacity(self.parts.len());
        for part in &self.parts {
            if !safe_part_file_name(&part.file) {
                bail!("MANIFEST part file {:?} is not one store-local path component", part.file);
            }
            if !files.insert(part.file.as_str()) {
                bail!("MANIFEST names part file {:?} more than once", part.file);
            }
            if part.seq_lo > part.seq_hi {
                bail!(
                    "MANIFEST part {:?} has inverted sequence range {}..{}",
                    part.file,
                    part.seq_lo,
                    part.seq_hi
                );
            }
            if part.b3.as_deref().is_some_and(|digest| !valid_blake3_hex(digest)) {
                bail!("MANIFEST part {:?} carries an invalid BLAKE3 digest", part.file);
            }
        }
        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)
    }

    /// tmp + fsync + rename + fsync-dir: a crash sees either the old manifest or the new one.
    ///
    /// Bumps the commit counter, and writes the retained copy `MANIFEST.<commit>` BEFORE the
    /// rename: if the live manifest is later corrupted, the copy of the very state it carried is
    /// what recovery promotes. A crash between the copy and the rename leaves a retained manifest
    /// describing a commit that never took effect. That residue is NOT the old state plus a
    /// counter bump — the caller mutates the manifest before committing, so the copy names files
    /// (a new part, a moved fold tail) the live manifest does not. Data-before-pointers makes
    /// those files durable, but the commit's authority is the rename that never happened:
    /// whatever the crashed commit acknowledged is still in the WAL, and writer open durably
    /// removes the residue before replaying it, precisely so the counters this manifest restarts
    /// cannot re-create a file name the residue still claims a digest for.
    ///
    /// One directory fsync at the end covers both dirents. Pruning runs last and is best-effort —
    /// a retained manifest that outlives its window is swept space, never a correctness problem,
    /// because it is OLDER than live: everything it pins, the live chain pins or has aged out.
    #[cfg(test)]
    fn commit(&mut self, dir: &Path) -> Result<()> {
        self.commit_with_limits(dir, ReadLimits::default())
    }

    fn commit_with_limits(&mut self, dir: &Path, read_limits: ReadLimits) -> Result<()> {
        // Admission precedes the first mutation. A commit creates one retained name and one
        // temporary name before the rename, so reserve both against the current directory count.
        let retained_before = list_retained_with_limits(dir, read_limits)?;
        let directory_entries = count_directory_entries(dir, read_limits, "store directory")?;
        read_limits.admit_directory_entries(
            "store directory during manifest commit",
            directory_entries.saturating_add(2),
        )?;
        self.commit += 1;
        // Chain onto whatever is being replaced. Hashed from disk rather than from memory,
        // because the chain's claim is about the BYTES a verifier can read back.
        self.prev = read_manifest_file(&dir.join("MANIFEST"))
            .ok()
            .map(|b| blake3::hash(&b).to_hex().to_string());
        let bytes = self.encode()?;
        {
            let p = retained_path(dir, self.commit);
            let f = crate::vfs::create(&p)?;
            crate::vfs::write_all_at(&f, &p, &bytes, 0)?;
            crate::vfs::sync_file(&f, &p)?;
        }
        let tmp = dir.join("MANIFEST.tmp");
        let f = crate::vfs::create(&tmp)?;
        crate::vfs::write_all_at(&f, &tmp, &bytes, 0)?;
        crate::vfs::sync_file(&f, &tmp)?;
        drop(f);
        crate::vfs::rename(&tmp, &dir.join("MANIFEST"))?;
        crate::vfs::sync_dir(dir)?;
        for c in retained_before {
            if c + (MANIFEST_RETAIN as u64) <= self.commit {
                let _ = crate::vfs::unlink(&retained_path(dir, c));
            }
        }
        Ok(())
    }

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

/// The `(payload, recorded crc32)` of a checksummed manifest, or `None` for one written before the
/// trailer existed. Recognition is by exact shape — a final line `crc32=` plus eight hex digits —
/// so a legacy manifest (compact JSON, which cannot end that way) is never misread as checksummed,
/// and a checksummed one whose trailer is damaged falls through to JSON parsing, which refuses the
/// trailing bytes rather than silently accepting the payload unverified.
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()?;
    let want = u32::from_str_radix(hex, 16).ok()?;
    Some((&bytes[..pos], want))
}

fn retained_path(dir: &Path, commit: u64) -> PathBuf {
    dir.join(format!("MANIFEST.{commit:08}"))
}

/// Retained commits on disk, ascending. Parsed NUMERICALLY, the same rule as segment names:
/// lexicographic order breaks past the padding width. `MANIFEST.tmp` does not match.
fn list_retained(dir: &Path) -> Result<Vec<u64>> {
    list_retained_with_limits(dir, ReadLimits::default())
}

fn list_retained_with_limits(dir: &Path, read_limits: ReadLimits) -> Result<Vec<u64>> {
    let read_limits = read_limits.validate()?;
    let mut out = Vec::new();
    let rd = std::fs::read_dir(dir).with_context(|| {
        format!("read store directory {} for retained manifests", dir.display())
    })?;
    let mut visited = 0u64;
    for e in rd {
        visited = visited.saturating_add(1);
        read_limits.admit_directory_entries("store directory", visited)?;
        let e = e?;
        let name = e.file_name().to_string_lossy().to_string();
        if let Some(rest) = name.strip_prefix("MANIFEST.") {
            if !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()) {
                if let Ok(n) = rest.parse::<u64>() {
                    out.push(n);
                }
            }
        }
    }
    out.sort_unstable();
    Ok(out)
}

fn count_directory_entries(
    dir: &Path,
    read_limits: ReadLimits,
    label: &'static str,
) -> Result<u64> {
    let mut visited = 0u64;
    for entry in std::fs::read_dir(dir)? {
        visited = visited.saturating_add(1);
        read_limits.admit_directory_entries(label, visited)?;
        entry?;
    }
    Ok(visited)
}

/// The snapshot commits currently available to [`Store::open_read_at`], ascending.
pub fn retained_commits(dir: &Path) -> Result<Vec<u64>> {
    list_retained(dir)
}

/// [`retained_commits`] with explicit directory-entry admission.
pub fn retained_commits_with_limits(dir: &Path, read_limits: ReadLimits) -> Result<Vec<u64>> {
    list_retained_with_limits(dir, read_limits)
}

/// Parse manifest bytes from an external source (a pack), trailer verification included.
pub(crate) fn manifest_from_bytes(b: &[u8]) -> Result<Manifest> {
    Manifest::parse(b)
}

/// Open a READER over a pack — the store in one file, served through bounded extents.
///
/// Everything [`ReadStore`] can do over a directory it does here identically: same manifest, same
/// parts, same fold, same version resolution. There is no writer role to take — a pack is
/// immutable by definition — and no retry loop to need, because nothing can sweep files out from
/// under an open handle on an immutable artifact.
pub fn open_read_pack(path: &Path, cfg: FoldCfg) -> Result<ReadStore> {
    open_read_pack_with_limits(path, cfg, ReadLimits::default())
}

/// Open a packed reader with explicit frame and persistent object-count admission.
pub fn open_read_pack_with_limits(
    path: &Path,
    cfg: FoldCfg,
    read_limits: ReadLimits,
) -> Result<ReadStore> {
    let read_limits = read_limits.validate()?;
    let pack = crate::pack::Pack::open(path)?;
    let manifest = Manifest::parse(&pack.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?;

    let fold_rel = if manifest.fold_gen == 0 {
        "fold".to_string()
    } else {
        format!("fold-{:04}", manifest.fold_gen)
    };
    let mut segs = Vec::new();
    let mut dict_files = Vec::new();
    for name in pack.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) {
            let extent = pack.file(&name).expect("name came from this pack's TOC");
            let segment_len = crate::readat::ReadAt::len(&extent)?;
            segs.push(crate::fold::SegmentInput {
                seg: n,
                reader: Arc::new(extent) as Arc<dyn crate::readat::ReadAt>,
                // Advisory: an overlarge sidecar is ignored and the segment is scanned instead.
                sidecar: pack
                    .read_file_bounded(
                        &format!("{fold_rel}/seg-{n:08}.dir"),
                        crate::fold::segment::max_dir_sidecar_bytes(segment_len)
                            .min(read_limits.max_stored_frame_bytes),
                    )
                    .ok(),
            });
        } else if rest.starts_with("zdict-") && rest.ends_with(".zd") {
            dict_files.push(pack.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?);
        }
    }
    let fold = Fold::open_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 = pack.file(&p.file).ok_or_else(|| {
            anyhow::anyhow!("pack manifest names {} but the pack does not hold it", p.file)
        })?;
        parts.push(Arc::new(Part::open_reader_with_limits(
            Box::new(ext),
            pcache.clone(),
            read_limits,
        )?));
    }
    Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
}

/// Open a READER over a container — the store in one **mutable** file.
///
/// Identical in every observable way to opening the directory it was checkpointed from: same
/// manifest, same parts, same fold, same version resolution. The difference from a pack is only
/// that the file this reads can still grow — a container names its state in a superblock rather
/// than a footer at EOF, so appending does not invalidate the state a reader already resolved.
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> {
    let read_limits = read_limits.validate()?;
    let container = crate::container::Container::open(path)?;
    let manifest = Manifest::parse(&container.read_file_bounded("MANIFEST", MAX_MANIFEST_BYTES)?)?;

    let fold_rel = if manifest.fold_gen == 0 {
        "fold".to_string()
    } else {
        format!("fold-{:04}", manifest.fold_gen)
    };
    let mut segs = Vec::new();
    let mut dict_files = Vec::new();
    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) {
            let extent = container.extent(&name).expect("name came from this directory");
            let segment_len = crate::readat::ReadAt::len(&extent)?;
            segs.push(crate::fold::SegmentInput {
                seg: n,
                reader: Arc::new(extent) as Arc<dyn crate::readat::ReadAt>,
                sidecar: container
                    .read_file_bounded(
                        &format!("{fold_rel}/seg-{n:08}.dir"),
                        crate::fold::segment::max_dir_sidecar_bytes(segment_len)
                            .min(read_limits.max_stored_frame_bytes),
                    )
                    .ok(),
            });
        } else if rest.starts_with("zdict-") && rest.ends_with(".zd") {
            dict_files.push(container.read_file_bounded(&name, crate::fold::MAX_DICTIONARY_BYTES)?);
        }
    }
    let fold = Fold::open_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 = container.extent(&p.file).ok_or_else(|| {
            anyhow::anyhow!(
                "container manifest names {} but the container does not hold it",
                p.file
            )
        })?;
        parts.push(Arc::new(Part::open_reader_with_limits(
            Box::new(ext),
            pcache.clone(),
            read_limits,
        )?));
    }
    Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
}

/// Which single-file form a path holds.
///
/// Told apart by magic rather than by extension, because the extension is the user's to choose and
/// the magic is the format's. Both forms answer reads identically; they differ in whether the file
/// can still grow.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SingleFileKind {
    /// Sealed: footer at EOF, immutable, writer-less by definition.
    Pack,
    /// Growable: alternating superblocks at the head, appended beyond the committed tail.
    Container,
}

/// Classify a single-file store by its magic.
///
/// The two forms carry their magic in different places, which is the addressing difference that
/// separates them: a container is superblock-addressed, so its magic is the first eight bytes; a
/// pack is footer-addressed, so its magic begins the footer at EOF. Checking only one position
/// finds only one form.
///
/// A path that is not a regular file, or that carries neither magic, is reported as `None` rather
/// than guessed at — callers that also accept directories dispatch on that.
pub fn single_file_kind(path: &Path) -> Option<SingleFileKind> {
    if !path.is_file() {
        return None;
    }
    let f = std::fs::File::open(path).ok()?;
    let len = f.metadata().ok()?.len();

    let mut magic = [0u8; 8];
    if len >= crate::container::REGION_START
        && crate::sys::read_exact_at(&f, &mut magic, 0).is_ok()
        && &magic == crate::container::MAGIC
    {
        return Some(SingleFileKind::Container);
    }
    if len >= crate::pack::FOOTER_LEN
        && crate::sys::read_exact_at(&f, &mut magic, len - crate::pack::FOOTER_LEN).is_ok()
        && &magic == crate::pack::MAGIC
    {
        return Some(SingleFileKind::Pack);
    }
    None
}

/// Open a READER over whichever single-file form the path holds.
///
/// The one entry a consumer needs when it has a `.turndb` and does not care which form produced
/// it. A directory is refused here — [`Store::open_read`] is that path.
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> {
    match single_file_kind(path) {
        Some(SingleFileKind::Container) => open_read_container_with_limits(path, cfg, read_limits),
        Some(SingleFileKind::Pack) => open_read_pack_with_limits(path, cfg, read_limits),
        None => bail!("{} is not a turndb pack or container (no recognised magic)", path.display()),
    }
}

/// Checkpoint a store directory into a container, creating it or growing one that exists.
///
/// This is the directory→file transition, and it is incremental by construction: parts and rolled
/// fold segments are immutable and uniquely named, so a member already present under the same name
/// and length is skipped rather than rewritten. Only `MANIFEST` and the live segment are restaged
/// every time.
///
/// The source must be quiescent — a non-empty WAL means writes exist that no manifest names yet,
/// exactly the condition [`crate::pack::write`] refuses for the same reason.
pub fn checkpoint_into_container(dir: &Path, out: &Path) -> Result<CheckpointStats> {
    let wal = dir.join("WAL");
    if wal.metadata().map(|m| m.len()).unwrap_or(0) != 0 {
        bail!("checkpoint refuses a store with a non-empty WAL: settle it with sync and flush");
    }
    let manifest = Manifest::load_with_limits(dir, ReadLimits::default())?;
    let mut container = if out.exists() {
        crate::container::Container::open(out)?
    } else {
        crate::container::Container::create(out)?
    };

    let mut names: Vec<String> = vec!["MANIFEST".to_string()];
    for p in &manifest.parts {
        names.push(p.file.clone());
    }
    let fold_rel = if manifest.fold_gen == 0 {
        "fold".to_string()
    } else {
        format!("fold-{:04}", manifest.fold_gen)
    };
    let fold_path = refold::fold_dir(dir, manifest.fold_gen);
    let mut fold_names: Vec<String> = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&fold_path) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            let keep = name.ends_with(".fold")
                || name.ends_with(".dir")
                || (name.starts_with("zdict-") && name.ends_with(".zd"));
            if keep {
                fold_names.push(format!("{fold_rel}/{name}"));
            }
        }
    }
    fold_names.sort();
    names.extend(fold_names);

    let mut ingested = 0u64;
    let mut skipped = 0usize;
    for name in &names {
        let src = dir.join(name);
        let src_len = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0);
        // MANIFEST and the live segment change in place; an immutable member of the same length is
        // already the same bytes, because parts and rolled segments are never rewritten.
        let immutable = name != "MANIFEST" && !name.ends_with(".dir");
        if immutable {
            if let Some(existing) = container.extent(name) {
                if crate::readat::ReadAt::len(&existing)? == src_len {
                    skipped += 1;
                    continue;
                }
            }
        }
        ingested += container.ingest(name, &src)?;
    }
    let seq = container.commit()?;
    Ok(CheckpointStats {
        members: container.len(),
        ingested_bytes: ingested,
        skipped_members: skipped,
        commit_seq: seq,
        free_bytes: container.free_bytes(),
    })
}

/// What one [`checkpoint_into_container`] moved.
#[derive(Clone, Copy, Debug)]
pub struct CheckpointStats {
    /// Members the container holds after the checkpoint.
    pub members: usize,
    /// Bytes written into the container by this call.
    pub ingested_bytes: u64,
    /// Members already present byte-for-byte and therefore not rewritten.
    pub skipped_members: usize,
    /// The container's committed sequence after this call.
    pub commit_seq: u64,
    /// Bytes now superseded inside the container, reclaimable only by rewriting it.
    pub free_bytes: u64,
}

fn load_retained(dir: &Path, commit: u64) -> Result<Manifest> {
    let p = retained_path(dir, commit);
    let b = read_manifest_file(&p).with_context(|| {
        format!("no retained manifest {} — the retention window has moved past it", p.display())
    })?;
    Manifest::parse(&b).with_context(|| format!("retained manifest {} is corrupt", p.display()))
}

/// Delete every file that no manifest — live or retained — names. THE deletion path: flush, merge,
/// re-fold, and writer open all converge here, so there is exactly one place that decides
/// reachability. A file a retained manifest names is a live snapshot's file and survives; it is
/// swept only when the window prunes past its last naming manifest.
///
/// A retained manifest that fails its checksum (a torn copy from a crash) pins nothing — it can
/// describe no snapshot anyone can open.
fn sweep_unreachable_with_limits(dir: &Path, read_limits: ReadLimits) -> Result<()> {
    let mut keep: Vec<Manifest> = vec![Manifest::load_with_limits(dir, read_limits)?];
    for c in list_retained_with_limits(dir, read_limits)? {
        if let Ok(m) = load_retained(dir, c) {
            keep.push(m);
        }
    }
    let live_parts: HashSet<&str> =
        keep.iter().flat_map(|m| m.parts.iter().map(|p| p.file.as_str())).collect();
    let live_gens: HashSet<u32> = keep.iter().map(|m| m.fold_gen).collect();
    let rd = std::fs::read_dir(dir)
        .with_context(|| format!("read store directory {} for orphan cleanup", dir.display()))?;
    let mut visited = 0u64;
    for e in rd {
        visited = visited.saturating_add(1);
        read_limits.admit_directory_entries("store directory", visited)?;
        let e = e?;
        let n = e.file_name().to_string_lossy().to_string();
        if n.starts_with("part-") && n.ends_with(".part") && !live_parts.contains(n.as_str()) {
            let _ = crate::vfs::unlink(&e.path());
        }
        if e.path().is_dir() {
            if let Some(g) = refold::parse_fold_gen(&n) {
                if !live_gens.contains(&g) {
                    let _ = crate::vfs::remove_tree(&e.path());
                }
            }
        }
    }
    Ok(())
}

fn cleanup_refold_stage(dir: &Path, generation: u32, built: &[refold::RefoldedPart]) {
    let fold = refold::fold_dir(dir, generation);
    if fold.exists() {
        let _ = crate::vfs::remove_tree(&fold);
    }
    for (file, ..) in built {
        let path = dir.join(file);
        if path.exists() {
            let _ = crate::vfs::unlink(&path);
        }
    }
}

/// What [`verify_chain`] checked.
#[derive(Clone, Copy, Debug, Default)]
pub struct ChainReport {
    /// Retained manifest files parsed and checked. Zero is an explicit empty/new-store result.
    pub retained_manifests: usize,
    /// prev-links verified across the retained window (newest retained == live MANIFEST included).
    pub links: usize,
    /// part digests verified against their files, across every retained manifest.
    pub part_digests: usize,
    /// parts whose manifest entry predates digests — reported, because "verified" must never
    /// silently include "had nothing to verify".
    pub undigested: usize,
}

/// Evidence returned by a complete committed-store verification pass.
#[derive(Clone, Copy, Debug, Default)]
pub struct StoreVerification {
    pub chain: ChainReport,
    pub fold: crate::fold::FoldScrub,
    pub parts: usize,
    pub part_sections: usize,
    /// Distinct live records in the committed snapshot, reconstructed below.
    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,
    /// Legacy values carrying no whole-value identity. Reconstruction still checks every piece.
    pub unidentified_content_values: usize,
}

/// Verify the manifest hash chain and every part pin it carries, across the retained window.
///
/// Catches what the per-section checksums cannot: a part swapped for another valid part, a
/// manifest restored out of order, a file replaced wholesale. Each of those is internally
/// consistent and only the chain notices. Verifiable across the retained window; silent about
/// commits whose bytes have been pruned.
pub fn verify_chain(dir: &Path) -> Result<ChainReport> {
    verify_chain_with_control(dir, &crate::control::OperationControl::default())
}

/// [`verify_chain`] with cooperative checks between retained manifests and part digests.
pub fn verify_chain_with_control(
    dir: &Path,
    control: &crate::control::OperationControl,
) -> Result<ChainReport> {
    verify_chain_with_limits_and_control(dir, ReadLimits::default(), control)
}

/// [`verify_chain_with_control`] with explicit directory-entry admission.
pub fn verify_chain_with_limits_and_control(
    dir: &Path,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<ChainReport> {
    let mut report = ChainReport::default();
    let commits = list_retained_with_limits(dir, read_limits)?;
    report.retained_manifests = commits.len();
    let mut prev_bytes: Option<Vec<u8>> = None;
    for &c in &commits {
        control.check("manifest verification")?;
        let bytes = read_manifest_file(&retained_path(dir, c))?;
        let m =
            Manifest::parse(&bytes).with_context(|| format!("retained manifest {c} is corrupt"))?;
        if let (Some(want), Some(pb)) = (&m.prev, &prev_bytes) {
            let got = blake3::hash(pb).to_hex().to_string();
            if *want != got {
                bail!("manifest chain broken: commit {c} names prev {want} but commit {} hashes to {got}", c - 1);
            }
            report.links += 1;
        }
        for p in &m.parts {
            control.check("manifest verification")?;
            match &p.b3 {
                Some(want) => {
                    let got = hash_file_with_control(
                        &dir.join(&p.file),
                        control,
                        "manifest verification",
                    )
                    .with_context(|| format!("part {} named by commit {c}", p.file))?
                    .to_hex()
                    .to_string();
                    if *want != got {
                        bail!("part {} drifted from the digest commit {c} pinned", p.file);
                    }
                    report.part_digests += 1;
                }
                None => report.undigested += 1,
            }
        }
        prev_bytes = Some(bytes);
    }
    // The live MANIFEST must be byte-identical to its retained copy — same commit, same bytes.
    if let (Some(&newest), Some(pb)) = (commits.last(), &prev_bytes) {
        let live = read_manifest_file(&dir.join("MANIFEST"))?;
        if live != *pb {
            bail!("MANIFEST diverges from its retained copy at commit {newest}");
        }
        report.links += 1;
    }
    Ok(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
        }
    })
}

/// Complete the one narrowly recognizable first-commit crash window.
///
/// This intentionally checks only manifest syntax because it runs before the ordinary writer open
/// performs the same fold/part validation it would perform had the rename landed. It is private so
/// operator recovery cannot bypass [`recover_manifest`]'s exclusive whole-candidate validation.
#[cfg(test)]
fn complete_first_commit(dir: &Path) -> Result<u64> {
    complete_first_commit_with_limits(dir, ReadLimits::default())
}

fn complete_first_commit_with_limits(dir: &Path, read_limits: ReadLimits) -> Result<u64> {
    if Manifest::load_with_limits(dir, read_limits).is_ok() {
        bail!("MANIFEST at {} is intact — refusing to roll back a healthy store", dir.display());
    }
    for c in list_retained_with_limits(dir, read_limits)?.into_iter().rev() {
        if load_retained(dir, c).is_err() {
            continue;
        }
        let bytes = read_manifest_file(&retained_path(dir, c))?;
        promote_manifest_with_limits(dir, c, &bytes, read_limits)?;
        return Ok(c);
    }
    bail!("MANIFEST at {} is damaged and no retained manifest is intact", dir.display());
}

/// Explicit bounds for checked operator recovery.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RecoveryOptions {
    /// 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 recovery.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RecoveryReport {
    pub commit: u64,
    pub rollback_commits: u64,
    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 RecoveryError {
    Healthy(PathBuf),
    RollbackLimit { needed: u64, allowed: u64 },
    NoUsableCandidate { examined: usize, reason: String },
}

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

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

/// Recover a damaged manifest after validating the complete candidate, and — on Unix — only after
/// excluding writers.
///
/// This is an explicit offline operator action, never an automatic fallback. In the common case,
/// the newest retained copy carries the same commit as the damaged live manifest and no data is
/// abandoned. Falling back farther requires an explicit [`RecoveryOptions::max_rollback_commits`]
/// allowance. Before publication, TurnDB validates the candidate's exact committed fold prefix,
/// every named part and section, every visible content program, and every available whole-value
/// identity. A healthy store is refused unconditionally. A concurrently open writer is refused only
/// where the writer lock is enforced: recovery takes that lock for every fold generation, and on
/// `wasm32-wasip1` the lock always succeeds, so a live writer is neither detected nor refused and
/// recovery can promote a manifest underneath one. There the exclusion is the embedder's to provide
/// for recovery exactly as for ordinary writes — see
/// [the writer lock](https://github.com/turndb/turndb/blob/main/FORMAT.md#the-writer-lock).
pub fn recover_manifest(
    dir: &Path,
    cfg: FoldCfg,
    options: RecoveryOptions,
) -> Result<RecoveryReport> {
    recover_manifest_with_control(dir, cfg, options, &crate::control::OperationControl::default())
}

/// [`recover_manifest`] with cooperative cancellation before manifest promotion.
///
/// Candidate discovery and complete validation are read-only. The last cancellation checkpoint is
/// immediately before `promote_manifest`; once promotion begins, its crash-safe protocol owns the
/// outcome and recovery will not report cancellation after changing the live commit point.
pub fn recover_manifest_with_control(
    dir: &Path,
    cfg: FoldCfg,
    options: RecoveryOptions,
    control: &crate::control::OperationControl,
) -> Result<RecoveryReport> {
    recover_manifest_with_limits_and_control(dir, cfg, options, ReadLimits::default(), control)
}

/// [`recover_manifest_with_control`] with explicit frame and object-count admission during
/// validation.
pub fn recover_manifest_with_limits_and_control(
    dir: &Path,
    cfg: FoldCfg,
    options: RecoveryOptions,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<RecoveryReport> {
    let read_limits = read_limits.validate()?;
    control.check("manifest recovery")?;
    let _locks = recovery_locks(dir, read_limits, control)?;
    control.check("manifest recovery")?;
    if Manifest::load_with_limits(dir, read_limits).is_ok() {
        return Err(RecoveryError::Healthy(dir.to_path_buf()).into());
    }
    let commits = list_retained_with_limits(dir, read_limits)?;
    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 recovery validation")?;
        examined += 1;
        let manifest = match load_retained(dir, c) {
            Ok(manifest) => manifest,
            Err(error) => {
                last_reason = error.to_string();
                continue;
            }
        };
        match validate_recovery_candidate(dir, cfg, manifest, read_limits, control) {
            Ok(mut report) => {
                let rollback_commits = newest.saturating_sub(c);
                if rollback_commits > options.max_rollback_commits {
                    return Err(RecoveryError::RollbackLimit {
                        needed: rollback_commits,
                        allowed: options.max_rollback_commits,
                    }
                    .into());
                }
                let bytes = read_manifest_file(&retained_path(dir, c))?;
                // No cancellation checkpoint after this point. Promotion can change MANIFEST and
                // prune newer retained manifests, so its actual outcome must be reported.
                control.check("manifest recovery publication")?;
                promote_manifest_with_limits(dir, c, &bytes, read_limits)?;
                report.commit = c;
                report.rollback_commits = rollback_commits;
                return Ok(report);
            }
            Err(error) => {
                if matches!(
                    crate::error::classify(&error),
                    crate::error::ErrorClass::Cancelled
                        | crate::error::ErrorClass::ResourceExhausted
                ) {
                    return Err(error);
                }
                last_reason = error.to_string();
            }
        }
    }
    Err(RecoveryError::NoUsableCandidate { examined, reason: last_reason }.into())
}

fn recovery_locks(
    dir: &Path,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<Vec<File>> {
    let mut folds = Vec::new();
    let mut visited = 0u64;
    for entry in std::fs::read_dir(dir)
        .with_context(|| format!("read store directory {} for recovery", dir.display()))?
    {
        visited = visited.saturating_add(1);
        read_limits.admit_directory_entries("store directory", visited)?;
        control.check("manifest recovery locking")?;
        let entry = entry?;
        if entry.path().is_dir()
            && refold::parse_fold_gen(&entry.file_name().to_string_lossy()).is_some()
        {
            folds.push(entry.path());
        }
    }
    folds.sort();
    folds
        .into_iter()
        .map(|path| {
            control.check("manifest recovery locking")?;
            crate::fold::acquire_writer_lock(&path)
        })
        .collect()
}

fn validate_recovery_candidate(
    dir: &Path,
    cfg: FoldCfg,
    manifest: Manifest,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<RecoveryReport> {
    control.check("manifest recovery validation")?;
    let fold_dir = refold::fold_dir(dir, manifest.fold_gen);
    let fold = match manifest.fold_tail() {
        Some(tail) => {
            Fold::open_read_at_with_limits(&fold_dir, cfg, tail, &manifest.punched, read_limits)?
        }
        None => Fold::open_read_with_limits(&fold_dir, cfg, &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 recovery validation")?;
        let path = dir.join(&part_ref.file);
        if let Some(want) = &part_ref.b3 {
            let got = hash_file_with_control(&path, control, "manifest recovery validation")?
                .to_hex()
                .to_string();
            if &got != want {
                bail!(
                    "candidate commit {} names part {} with the wrong digest",
                    manifest.commit,
                    part_ref.file
                );
            }
        }
        let part = Arc::new(Part::open_in_with_limits(&path, pcache.clone(), read_limits)?);
        part_sections += part.verify_sections_with_control(control)?;
        parts.push(part);
    }
    let reader = ReadStore { fold: Arc::new(fold), parts, manifest, read_limits };
    let ids = reader.ids()?;
    let mut content_values = 0usize;
    for id in &ids {
        control.check("manifest recovery validation")?;
        let record = reader.get(id)?.expect("ids returns visible records");
        for content in record.contents {
            control.check("manifest recovery validation")?;
            let mut identity = blake3::Hasher::new();
            for op in content.ops {
                control.check("manifest recovery validation")?;
                match op {
                    BodyOp::Lit(bytes) => {
                        identity.update(&bytes);
                    }
                    BodyOp::Piece { hash, len } => {
                        let mut loc = None;
                        for part in reader.parts.iter().rev() {
                            if let Some(found) = part.lookup_piece(&hash)? {
                                loc = Some(found);
                                break;
                            }
                        }
                        let loc = loc.ok_or_else(|| {
                            anyhow::anyhow!(
                                "candidate record {id:?} references absent piece {hash}"
                            )
                        })?;
                        let bytes = reader.fold.read_verified(loc, hash)?;
                        if bytes.len() != len as usize {
                            bail!(
                                "candidate record {id:?} says piece {hash} is {len} bytes but it is {}",
                                bytes.len()
                            );
                        }
                        identity.update(&bytes);
                    }
                }
            }
            if let Some(want) = content.identity {
                let got = ContentHash(identity.finalize().into());
                if got != want {
                    bail!(
                        "candidate record {id:?} content {:?} has identity {got}, expected {want}",
                        content.name
                    );
                }
            }
            content_values += 1;
        }
    }
    Ok(RecoveryReport {
        records: ids.len(),
        content_values,
        parts: reader.parts.len(),
        part_sections,
        fold_segments: scrub.segments,
        fold_blocks: scrub.blocks,
        fold_bytes: scrub.bytes,
        ..RecoveryReport::default()
    })
}

fn hash_file_with_control(
    path: &Path,
    control: &crate::control::OperationControl,
    operation: &'static str,
) -> Result<blake3::Hash> {
    use std::io::Read;

    let mut file = File::open(path)?;
    let mut hasher = blake3::Hasher::new();
    let mut buf = vec![0u8; 1 << 20];
    loop {
        control.check(operation)?;
        let read = file.read(&mut buf)?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
    }
    Ok(hasher.finalize())
}

fn promote_manifest_with_limits(
    dir: &Path,
    commit: u64,
    bytes: &[u8],
    read_limits: ReadLimits,
) -> Result<()> {
    // Recovery stages one temporary name before publication. If MANIFEST is absent, the rename
    // also leaves one additional persistent root entry. Reserve that worst case before changing
    // the supplied directory; the abandonment pruning below only removes entries, so the
    // reservation is not affected by it.
    let directory_entries = count_directory_entries(dir, read_limits, "store directory")?;
    read_limits.admit_directory_entries(
        "store directory during manifest recovery",
        directory_entries.saturating_add(1),
    )?;
    // Abandonment becomes durable BEFORE the new timeline publishes. The reverse order left a
    // window where the promoted MANIFEST and the abandoned newer retained manifests were both
    // durable: a crash there resurrected the abandoned timeline, a re-run of recovery would see
    // the chain diverge, treat the store as damaged, and — because the resurrected commits are
    // genuine descendants that can validate — promote the exact history the operator authorized
    // abandoning. Pruning first converges instead: a crash before the rename leaves the damaged
    // manifest and fewer candidates, and re-running recovery promotes the same target. The
    // unlinks are propagated, not best-effort — an abandonment that cannot be made durable must
    // not be reported as one.
    let mut abandoned = false;
    for retained in list_retained_with_limits(dir, read_limits)? {
        if retained > commit {
            crate::vfs::unlink(&retained_path(dir, retained))?;
            abandoned = true;
        }
    }
    if abandoned {
        crate::vfs::sync_dir(dir)?;
    }
    let tmp = dir.join("MANIFEST.tmp");
    let f = crate::vfs::create(&tmp)?;
    crate::vfs::write_all_at(&f, &tmp, bytes, 0)?;
    crate::vfs::sync_file(&f, &tmp)?;
    drop(f);
    crate::vfs::rename(&tmp, &dir.join("MANIFEST"))?;
    crate::vfs::sync_dir(dir)?;
    Ok(())
}

pub struct Store {
    dir: PathBuf,
    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,
}

/// 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 {
    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,
}

/// File bytes in one reachability class.
///
/// `logical_bytes` is portable file length. `allocated_bytes` measures filesystem blocks and is
/// `None` where the platform cannot report sparse allocation honestly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpaceAmount {
    pub files: usize,
    pub logical_bytes: u64,
    pub allocated_bytes: Option<u64>,
}

impl Default for SpaceAmount {
    fn default() -> Self {
        SpaceAmount {
            files: 0,
            logical_bytes: 0,
            allocated_bytes: if cfg!(unix) { Some(0) } else { None },
        }
    }
}

/// 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 because an embedder may have
/// placed an unrelated file in the directory and TurnDB has no authority to delete it.
#[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>,
}

/// Exact progress of upgrading the current live immutable-part set to this build's format.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FormatMigrationStatus {
    pub target_part_version: u8,
    pub live_parts: usize,
    pub current_parts: usize,
    pub legacy_parts: usize,
    pub legacy_rows: u64,
    pub legacy_bytes: u64,
    /// Unique legacy parts pinned only by retained manifests, not counted in `legacy_parts`.
    pub retained_legacy_parts: usize,
    pub retained_legacy_rows: u64,
    pub retained_legacy_bytes: u64,
}

/// Exact source facts and an advisory stage estimate for one resumable migration step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FormatMigrationPlan {
    pub part_index: usize,
    pub source_part_version: u8,
    pub seq_lo: u64,
    pub seq_hi: u64,
    pub input_rows: u64,
    pub input_bytes: u64,
    pub input_sections: usize,
    pub input_raw_section_bytes: u64,
    pub estimated_stage_bytes: u64,
    pub estimate_is_hard_bound: bool,
    pub retained_input_bytes_after_commit: u64,
    pub filesystem_available_bytes: Option<u64>,
}

/// Evidence returned after atomically publishing one migrated part.
#[derive(Clone, Copy, Debug)]
pub struct FormatMigrationStep {
    pub plan: FormatMigrationPlan,
    pub output_bytes: u64,
    pub remaining_legacy_parts: usize,
    pub rewrite: crate::part::merge::MergeStats,
}

/// 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;

    /// Open for writing. Takes the writer lock (through the fold) and recovers.
    ///
    /// **On Unix** that lock is `flock` and the kernel enforces it. **On `wasm32-wasip1` it is not
    /// enforced at all** — WASI has no advisory locking, so the lock file is created and gates
    /// nothing, and the single-writer invariant becomes the embedder's: at most one open writer per
    /// store directory, across every process and every instance. See `src/sys.rs` and FORMAT.md.
    pub fn open(dir: &Path, cfg: FoldCfg) -> Result<Store> {
        Self::open_with_options(dir, StoreOptions { fold: cfg, ..StoreOptions::default() })
    }

    /// Open a writer with explicit runtime admission policy.
    pub fn open_with_limits(dir: &Path, cfg: FoldCfg, write_limits: WriteLimits) -> Result<Store> {
        Self::open_with_options(
            dir,
            StoreOptions { fold: cfg, write_limits, ..StoreOptions::default() },
        )
    }

    /// Open a writer with explicit storage, cache, and admission configuration.
    pub fn open_with_options(dir: &Path, options: StoreOptions) -> Result<Store> {
        let recovery_started = std::time::Instant::now();
        let StoreOptions { fold: cfg, write_limits, read_limits, part_cache_bytes } = options;
        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);
        }
        crate::vfs::mkdir_all(dir)?;
        let manifest = match Manifest::load_with_limits(dir, read_limits) {
            Ok(m) => m,
            Err(e) => {
                // A crash inside the FIRST commit is the one state where MANIFEST can be
                // legitimately absent beside a commit log: the retained copy lands before the
                // rename, and commit 1 has no previous manifest to leave behind. A log of exactly
                // [1] with no MANIFEST is that signature — an intact copy COMPLETES the commit
                // (data before pointers makes promotion indistinguishable from the crash landing
                // a moment later), a torn copy VOIDS it (nothing was published). Every other
                // missing-manifest shape means a manifest that once existed is gone, and stays a
                // refusal. Found by the DST harness at the first flush's commit window.
                let retained = list_retained_with_limits(dir, read_limits)?;
                if !dir.join("MANIFEST").exists() && retained == [1] {
                    if load_retained(dir, 1).is_ok() {
                        complete_first_commit_with_limits(dir, read_limits)?;
                    } else {
                        crate::vfs::unlink(&retained_path(dir, 1))?;
                        crate::vfs::sync_dir(dir)?;
                    }
                    verification_integrity(
                        "open committed manifest",
                        Manifest::load_with_limits(dir, read_limits),
                    )?
                } else {
                    return verification_integrity("open committed manifest", Err(e));
                }
            }
        };

        // The live MANIFEST is the only commit point, so a retained name it does not dominate is
        // residue, not state. Two shapes exist. A retained commit NEWER than live is a commit
        // that never took effect — a crash between the commit protocol's retained copy and its
        // rename; whatever it acknowledged is still in the WAL and replays below. A retained
        // manifest from ANOTHER FOLD GENERATION is a re-fold's purge that lost a race with a
        // crash, and keeps content the re-fold exists to erase readable. Left in place, either
        // shape pins files this manifest's counters will re-create by name, so a later flush
        // would truncate a file a retained manifest still claims a digest for — and verification
        // would report an inconsistency in a store that is behaving correctly. Removal is durable
        // and precedes the sweep, which then collects whatever only these names pinned. A torn
        // retained copy parses as nothing, pins nothing, and is left for window pruning.
        let mut reconciled = false;
        for c in list_retained_with_limits(dir, read_limits)? {
            let stale_timeline = c > manifest.commit;
            let stale_generation = !stale_timeline
                && load_retained(dir, c).map(|m| m.fold_gen != manifest.fold_gen).unwrap_or(false);
            if stale_timeline || stale_generation {
                crate::vfs::unlink(&retained_path(dir, c))?;
                reconciled = true;
            }
        }
        if reconciled {
            crate::vfs::sync_dir(dir)?;
        }

        let root_entries = count_directory_entries(dir, read_limits, "store directory")?;
        let fold_path = refold::fold_dir(dir, manifest.fold_gen);
        let additions = u64::from(!fold_path.exists()) + u64::from(!dir.join("WAL").exists());
        read_limits.admit_directory_entries(
            "store directory during writer open",
            root_entries.saturating_add(additions),
        )?;

        // Recovery is a truncate, not a negotiation: whatever the fold wrote past the committed tail
        // is discarded, and the log regenerates it. The punched declaration rides in with the tail
        // because recovery needs it DURING the scan: a crash mid-punch can leave a declared block's
        // payload partially zeroed, and without the declaration that frame reads as a torn write
        // and the committed tail as lost durable bytes.
        let mut fold = verification_integrity(
            "open committed fold",
            Fold::open_at_with_limits(
                &fold_path,
                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 {
            parts.push(Arc::new(verification_integrity(
                "open committed part",
                Part::open_in_with_limits(&dir.join(&p.file), pcache.clone(), read_limits),
            )?));
        }

        // A part file or fold generation no manifest names was written by a flush, merge, or
        // re-fold that crashed before committing, or has aged out of the retention window. Either
        // way it is unreachable. Safe to unlink even with readers attached: Unix keeps their open
        // mappings alive.
        sweep_unreachable_with_limits(dir, read_limits)?;
        // Crash litter: builder spools and staging files are all *.tmp, and every one of them is
        // pre-commit garbage. Swept ONLY at writer open, not at flush — an external packer's
        // staging file must not race a live writer's flush.
        let rd = std::fs::read_dir(dir)
            .with_context(|| format!("read store directory {} for temp cleanup", dir.display()))?;
        let mut visited = 0u64;
        for e in rd {
            visited = visited.saturating_add(1);
            read_limits.admit_directory_entries("store directory", visited)?;
            let e = e?;
            if e.file_name().to_string_lossy().ends_with(".tmp") && e.path().is_file() {
                let _ = crate::vfs::unlink(&e.path());
            }
        }

        let wal_path = dir.join("WAL");
        let retained_commit_count = list_retained_with_limits(dir, read_limits)?.len();
        let replay = Wal::replay_state_with_limits(&wal_path, read_limits)?;
        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;
        for f in replay.frames {
            // Re-fold every piece this frame introduced. Content already below the committed tail
            // dedups; content discarded by the truncate is written again.
            for (h, bytes) in &f.novel {
                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,
            ..crate::observability::StoreMetrics::default()
        };
        let recovery_duration = recovery_started.elapsed();
        metrics.open_recovery.observe_success(recovery_duration);
        let mut events = crate::observability::EventJournal::default();
        let recovery_result: Result<()> = Ok(());
        events.observe(
            crate::observability::LifecycleOperation::OpenRecovery,
            recovery_duration,
            &recovery_result,
        );
        Ok(Store {
            dir: dir.to_path_buf(),
            fold,
            parts,
            manifest,
            mem,
            mem_bytes,
            wal,
            cfg,
            write_limits,
            read_limits,
            retained_commit_count,
            pcache,
            metrics,
            events,
        })
    }

    /// 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);
    }

    fn admit_store_directory_growth(&self, additional: u64, operation: &str) -> Result<()> {
        let current = count_directory_entries(&self.dir, self.read_limits, "store directory")?;
        self.read_limits.admit_directory_entries(
            format!("store directory during {operation}"),
            current.saturating_add(additional),
        )?;
        Ok(())
    }

    /// 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::OpenRecovery => {
                self.metrics.open_recovery.observe(duration, result)
            }
            LifecycleOperation::Sync => self.metrics.sync.observe(duration, result),
            LifecycleOperation::Flush => self.metrics.flush.observe(duration, result),
            LifecycleOperation::Compaction => self.metrics.compaction.observe(duration, result),
            LifecycleOperation::Backup => self.metrics.backup.observe(duration, result),
            LifecycleOperation::Verification => self.metrics.verification.observe(duration, result),
            LifecycleOperation::Punch => self.metrics.punch.observe(duration, result),
            LifecycleOperation::Refold => self.metrics.refold.observe(duration, result),
            LifecycleOperation::Erase => self.metrics.erase.observe(duration, result),
            LifecycleOperation::FormatMigration => {
                self.metrics.format_migration.observe(duration, result)
            }
        }
        self.events.observe(operation, duration, result);
    }

    /// Verify the retained manifest chain, all live immutable-part sections, and every fold frame.
    ///
    /// This covers the committed snapshot only. A writer that wants the report to include staged
    /// work must sync and flush 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")?;
        let chain = verification_integrity(
            "verify retained manifest chain",
            verify_chain_with_limits_and_control(&self.dir, self.read_limits, control),
        )?;
        let fold =
            verification_integrity("verify fold frames", self.fold.scrub_with_control(control))?;
        let mut part_sections = 0usize;
        for part in &self.parts {
            control.check("store verification")?;
            let sections = verification_integrity(
                "verify immutable part sections",
                part.verify_sections_with_control(control),
            )?;
            part_sections = part_sections
                .checked_add(sections)
                .ok_or_else(|| anyhow::anyhow!("verified part section count overflow"))?;
        }
        // Reconstruct every named value in the committed snapshot. Section and frame checks prove
        // the storage containers; this proves the references inside them resolve to the exact
        // content identities the records claim. Deliberately use the committed read core rather
        // than `Store::ids`/`Store::reconstruct_content`, which include staged memtable state.
        let ids = verification_integrity("enumerate committed records", read::ids(&self.parts))?;
        let mut content_values = 0usize;
        let mut content_bytes = 0u64;
        let mut content_identities = 0usize;
        let mut unidentified_content_values = 0usize;
        for id in &ids {
            control.check("store verification")?;
            let record =
                verification_integrity("decode committed record", read::get(&self.parts, id))?
                    .ok_or_else(|| {
                        anyhow::Error::new(crate::error::IntegrityError::new(
                            "decode committed record",
                            anyhow::anyhow!("live id {id:?} disappeared during verification"),
                        ))
                    })?;
            for content in &record.contents {
                control.check("store verification")?;
                let bytes = verification_integrity(
                    "reconstruct committed content",
                    read::reconstruct_content(&self.parts, &self.fold, id, &content.name),
                )?
                .ok_or_else(|| {
                    anyhow::Error::new(crate::error::IntegrityError::new(
                        "reconstruct committed content",
                        anyhow::anyhow!(
                            "record {id:?} lost named content {:?} during verification",
                            content.name
                        ),
                    ))
                })?;
                content_values = content_values
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("verified content value count overflow"))?;
                content_bytes = content_bytes
                    .checked_add(bytes.len() as u64)
                    .ok_or_else(|| anyhow::anyhow!("verified content byte count overflow"))?;
                match content.identity {
                    Some(want) => {
                        let got = crate::types::ContentHash::of(&bytes);
                        if got != want {
                            return Err(crate::error::IntegrityError::new(
                                "verify committed content identity",
                                anyhow::anyhow!(
                                    "record {id:?} content {:?} hashes to {got} but claims {want}",
                                    content.name
                                ),
                            )
                            .into());
                        }
                        content_identities =
                            content_identities.checked_add(1).ok_or_else(|| {
                                anyhow::anyhow!("verified content identity count overflow")
                            })?;
                    }
                    None => {
                        unidentified_content_values =
                            unidentified_content_values.checked_add(1).ok_or_else(|| {
                                anyhow::anyhow!("unidentified content value count overflow")
                            })?;
                    }
                }
            }
        }
        Ok(StoreVerification {
            chain,
            fold,
            parts: self.parts.len(),
            part_sections,
            records: ids.len(),
            content_values,
            content_bytes,
            content_identities,
            unidentified_content_values,
        })
    }

    /// Exact file-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 = std::fs::metadata(self.dir.join(&part.file))
                .with_context(|| format!("measure live part {}", part.file))?
                .len();
            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 live, dead, and block-reclaimable folded content for a settled snapshot.
    ///
    /// This walks visible record programs and reads each fold block header, but never decompresses
    /// content. 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 = self.live_fold_pieces_with_control(control)?;
        let live_block_ids: HashSet<u32> =
            live_pieces.values().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.values() {
            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)
    }

    /// Open for reading only: no lock, no replay, no daemon.
    ///
    /// Sees exactly the committed manifest — uncommitted records in some writer's memtable are
    /// invisible, which is the correct snapshot. Safe alongside a live writer because parts are
    /// immutable and the fold is append-only.
    pub fn open_read(dir: &Path, cfg: FoldCfg) -> Result<ReadStore> {
        Self::open_read_with_limits(dir, cfg, ReadLimits::default())
    }

    /// Open the published snapshot with explicit frame and object-count admission.
    pub fn open_read_with_limits(
        dir: &Path,
        cfg: FoldCfg,
        read_limits: ReadLimits,
    ) -> Result<ReadStore> {
        let read_limits = read_limits.validate()?;
        // Reading the manifest and opening the fold generation plus parts it names is not atomic. A
        // writer may commit a merge or re-fold and unlink the replaced files in between, or commit a
        // flush whose new part names fold blocks a reader scanned just before they landed. The
        // manifest IS the linearization point, so every attempt starts from one manifest and opens the
        // fold and parts belonging to that exact snapshot. Once open, Unix keeps all of those handles
        // alive through a later unlink.
        //
        // Bounded, because a manifest naming a genuinely absent part must eventually surface as an
        // error rather than spin.
        let mut last: Option<anyhow::Error> = None;
        for _ in 0..8 {
            let manifest = Manifest::load_with_limits(dir, read_limits)?;
            let fold_path = refold::fold_dir(dir, manifest.fold_gen);
            // The manifest's punched ranges ride into the open. A live record never references a
            // punched block — `punch_unreferenced` walks live visibility to decide — but the scan
            // itself needs the declaration to step over a mid-punch frame a crash left behind, and
            // if a stale `Loc` ever reaches one, it is then named as erasure rather than as a
            // failing disk.
            let fold = match manifest.fold_tail().map_or_else(
                || Fold::open_read_with_limits(&fold_path, cfg, &manifest.punched, read_limits),
                |tail| {
                    Fold::open_read_at_with_limits(
                        &fold_path,
                        cfg,
                        tail,
                        &manifest.punched,
                        read_limits,
                    )
                },
            ) {
                Ok(fold) => fold,
                Err(e) => {
                    let gone = e
                        .downcast_ref::<std::io::Error>()
                        .map(|io| io.kind() == std::io::ErrorKind::NotFound)
                        .unwrap_or(false)
                        || !fold_path.exists();
                    if !gone {
                        return Err(e);
                    }
                    last = Some(e);
                    continue;
                }
            };
            let pcache = SectionCache::shared();
            let mut parts = Vec::with_capacity(manifest.parts.len());
            let mut missed = false;
            for p in &manifest.parts {
                match Part::open_in_with_limits(&dir.join(&p.file), pcache.clone(), read_limits) {
                    Ok(part) => parts.push(Arc::new(part)),
                    Err(e) => {
                        let gone = e
                            .downcast_ref::<std::io::Error>()
                            .map(|io| io.kind() == std::io::ErrorKind::NotFound)
                            .unwrap_or(false)
                            || !dir.join(&p.file).exists();
                        if !gone {
                            return Err(e);
                        }
                        last = Some(e);
                        missed = true;
                        break;
                    }
                }
            }
            if !missed {
                // A re-fold commit changes the address space itself: the new parts' Locs are only
                // meaningful against the new fold generation. If that swap happened while this
                // attempt was opening files, retry even when every individual open succeeded.
                if Manifest::load_with_limits(dir, read_limits)?.fold_gen != manifest.fold_gen {
                    last = Some(anyhow::anyhow!(
                        "fold generation changed while opening a reader snapshot"
                    ));
                    continue;
                }
                return Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits });
            }
        }
        Err(last.unwrap_or_else(|| {
            anyhow::anyhow!("manifest snapshot names storage that does not exist")
        }))
    }

    /// Open a READER on a retained snapshot: the store exactly as commit `commit` left it.
    ///
    /// Only commits still inside the retention window exist — [`retained_commits`] lists them, and
    /// a re-fold empties the list on purpose (time travel must not resurrect erased content).
    ///
    /// No retry loop, unlike [`Store::open_read`], deliberately: the files a LIVE manifest names
    /// can be superseded while opening them, but a retained snapshot's files are pinned on disk by
    /// its manifest, and the one way they vanish is the window advancing past it — a real error,
    /// reported as one.
    pub fn open_read_at(dir: &Path, cfg: FoldCfg, commit: u64) -> Result<ReadStore> {
        Self::open_read_at_with_limits(dir, cfg, commit, ReadLimits::default())
    }

    /// Open a retained snapshot with explicit frame and object-count admission.
    pub fn open_read_at_with_limits(
        dir: &Path,
        cfg: FoldCfg,
        commit: u64,
        read_limits: ReadLimits,
    ) -> Result<ReadStore> {
        let read_limits = read_limits.validate()?;
        let manifest = load_retained(dir, commit)?;
        let fold_dir = refold::fold_dir(dir, manifest.fold_gen);
        // Erasure is declared by the LIVE manifest, not by the retained one. Punching commits a new
        // manifest, so a retained copy predates every punch that followed it and declares nothing —
        // which is exactly how a deliberate erasure came to be reported as a checksum failure.
        // `punched` is cumulative, so the live copy is the whole truth about what is gone. Loaded
        // BEFORE the fold opens, because the open's own scan is a consumer: a crash mid-punch can
        // leave a declared block's payload partially zeroed, and only the declaration lets the scan
        // step over it.
        //
        // The load is PROPAGATED, not tolerated. Treating an unreadable live manifest as "nothing
        // was erased" is the same false fallback this whole fix exists to remove: the reader would
        // proceed with no declaration and report a punched payload as checksum corruption, which is
        // the misattribution, arrived at by a different route. An unreadable manifest is an error
        // and not an empty one — the store's existing rule, and it applies with more force here,
        // because this manifest is the ONLY authority for telling erasure from damage.
        let live = Manifest::load_with_limits(dir, read_limits).with_context(|| {
            format!(
                "retained snapshot at commit {commit} needs the live manifest in {} to tell erased \
                 blocks from damaged ones, and it could not be read",
                dir.display()
            )
        })?;
        // Guarded on the generation because block ids are per generation: applying one generation's
        // punched ranges to another would name live blocks. A re-fold purges the retained log, so a
        // mismatch should be unreachable — and if it happens anyway, there is no surviving authority
        // for the old generation's erasures (a re-fold clears `punched`, having rewritten the world
        // without the erased content). No authority means refuse, for the same reason as above.
        if live.fold_gen != manifest.fold_gen {
            bail!(
                "retained snapshot at commit {commit} is fold generation {} but the live manifest is \
                 {}, so no erasure declaration covers it",
                manifest.fold_gen,
                live.fold_gen
            );
        }
        let fold = match manifest.fold_tail() {
            Some(tail) => {
                Fold::open_read_at_with_limits(&fold_dir, cfg, tail, &live.punched, read_limits)?
            }
            None => Fold::open_read_with_limits(&fold_dir, cfg, &live.punched, read_limits)?,
        };
        let pcache = SectionCache::shared();
        let mut parts = Vec::with_capacity(manifest.parts.len());
        for p in &manifest.parts {
            parts.push(Arc::new(Part::open_in_with_limits(
                &dir.join(&p.file),
                pcache.clone(),
                read_limits,
            )?));
        }
        Ok(ReadStore { fold: Arc::new(fold), parts, manifest, read_limits })
    }

    /// 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 live part's dictionary  — everything ever committed, 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 already sits below the tail that recovery truncates to. 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 = 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);
            crate::fold::Put { hash, loc, deduped: true }
        } else {
            self.fold.put_hashed(b, hash)?
        };
        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<()> {
        let input = [ContentSpans::new(BODY_CONTENT, spans.to_vec())];
        input_record_admission_bytes(
            id,
            &input,
            &attrs,
            self.write_limits,
            self.read_limits,
            None,
        )?;
        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(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<()> {
        // 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,
        )?;
        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(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(BodyOp::Lit(b.to_vec()));
                }
                Span::Piece(b) => {
                    identity.update(b);
                    let put = self.fold_piece(b)?;
                    if !put.deduped {
                        // new content: the log must carry the bytes, because recovery discards
                        // anything the fold wrote past the committed tail
                        novel.push((put.hash, b.to_vec()));
                    }
                    ops.push(BodyOp::Piece { hash: put.hash, len: b.len() as u32 });
                }
            }
        }
        Ok(Content::identified(name, ops, ContentHash(identity.finalize().into())))
    }

    fn stage_record(&mut self, rec: Record, novel: Vec<(PieceHash, Vec<u8>)>) -> Result<()> {
        self.wal.append(self.manifest.next_seq, &rec, &novel)?;
        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 commit marker goes to the log in one append. Replay applies the members only when
    /// the marker sealed 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<()> {
        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());
        }
        self.wal.admit_additional_frames(batch.items.len() as u64 + 1)?;
        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(BodyOp::Lit(b.clone()));
                                }
                                OwnedSpan::Piece(b) => {
                                    identity.update(b);
                                    let put = self.fold_piece(b)?;
                                    if !put.deduped {
                                        novel.push((put.hash, b.clone()));
                                    }
                                    ops.push(BodyOp::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,
                    ));
                }
            }
        }
        self.wal.append_batch(self.manifest.next_seq, &framed)?;
        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<()> {
        delete_admission_bytes(id, self.write_limits, self.read_limits, None)?;
        self.wal.admit_additional_frames(1)?;
        self.wal.append_tomb(self.manifest.next_seq, 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 WAL fsync begins, cancellation is no longer observed: returning cancellation after the
    /// writes became durable would misreport the acknowledgement outcome.
    pub fn sync_with_control(&mut self, control: &crate::control::OperationControl) -> Result<()> {
        let started = std::time::Instant::now();
        let result = (|| {
            control.check("store sync")?;
            self.wal.sync()
        })();
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Sync,
            started.elapsed(),
            &result,
        );
        result
    }

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

    /// [`Store::backup`] with cooperative cancellation before atomic artifact publication.
    ///
    /// Sync/flush may publish an equivalent immutable representation of earlier accepted writes in
    /// the source store. Cancellation never publishes the backup destination.
    pub fn backup_with_control(
        &mut self,
        out: &Path,
        control: &crate::control::OperationControl,
    ) -> Result<crate::pack::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::pack::BackupStats> {
        control.check("backup")?;
        crate::pack::ensure_destination_available(out)?;
        self.sync_with_control(control)?;
        self.flush_with_control(control)?;
        control.check("backup")?;
        let stats =
            crate::pack::write_committed_with_control(&self.dir, out, self.read_limits, control)?;
        Ok(crate::pack::BackupStats {
            files: stats.files,
            bytes: stats.bytes,
            commit: self.manifest.commit,
        })
    }

    /// Seal the memtable into 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 and memtable remain unchanged. An unpublished part is removed. Once manifest commit
    /// 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>> {
        control.check("memtable flush")?;
        if self.mem.is_empty() {
            return Ok(None);
        }
        self.admit_store_directory_growth(3, "memtable flush")?;
        let tail = self.fold.sync()?;
        let seq = self.manifest.next_seq + 1;
        let file = format!("part-{seq:08}.part");
        let path = self.dir.join(&file);
        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 tiers, exactly as the write path does.
        //
        // A Tier-0-only resolve is correct only while the process that staged the records is still
        // alive: `fold_piece` notes a Tier-1 hit into the window, so the window covers it. After a
        // CRASH it does not. Replay re-folds only pieces the WAL carried bytes for, and a Tier-1 hit
        // carries none by design — the content was already durable in an older part. Those pieces are
        // then in no window at all, and a Tier-0-only resolve would fail here on every subsequent
        // flush attempt, permanently: records unreadable, WAL growing without bound. On the
        // high-duplication corpora this engine exists for, that is nearly every record after the
        // first flush.
        let mut locs: HashMap<PieceHash, Loc> = HashMap::new();
        for r in &recs {
            control.check("memtable flush planning")?;
            for content in &r.contents {
                for op in &content.ops {
                    control.check("memtable flush planning")?;
                    let BodyOp::Piece { hash, .. } = op else { continue };
                    if locs.contains_key(hash) {
                        continue;
                    }
                    let loc = self.locate(hash)?.ok_or_else(|| {
                        anyhow::anyhow!(
                            "staged piece {hash} is in neither the fold window nor any live part"
                        )
                    })?;
                    locs.insert(*hash, loc);
                }
            }
        }
        let meta = match part::build_full_with_limits(
            &path,
            &recs,
            &tombs,
            seq,
            seq,
            self.cfg.level,
            |h| locs.get(h).copied(),
            &HashMap::new(),
            self.read_limits,
        ) {
            Ok(meta) => meta,
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };

        if let Err(error) = control.check("memtable flush") {
            let _ = crate::vfs::unlink(&path);
            return Err(error.into());
        }
        let digest = match hash_file_with_control(&path, control, "memtable flush") {
            Ok(hash) => hash.to_hex().to_string(),
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };

        let mut m = self.manifest.clone();
        m.parts.push(PartRef {
            file: file.clone(),
            seq_lo: seq,
            seq_hi: seq,
            records: meta.n_records,
            b3: Some(digest),
        });
        m.fold_seg = tail.seg;
        m.fold_off = tail.off;
        m.next_seq = seq;
        if let Err(error) = control.check("memtable flush publication") {
            let _ = crate::vfs::unlink(&path);
            return Err(error.into());
        }
        m.commit_with_limits(&self.dir, self.read_limits)?; // <- the linearization point

        self.parts.push(Arc::new(Part::open_in_with_limits(
            &path,
            self.pcache.clone(),
            self.read_limits,
        )?));
        self.manifest = m;
        self.note_manifest_commit();
        // The commit may have pruned a retained manifest; whatever only it named is now sweepable.
        sweep_unreachable_with_limits(&self.dir, self.read_limits)?;
        self.mem.clear();
        self.mem_bytes = 0;
        // Release Tier 0 — but only HERE, after the part is committed and open. Sealing 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.seal_window();
        // 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 live parts into one, and publish it 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 the live 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::Compaction,
            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>> {
        control.check("part compaction")?;
        if len < 2 || lo + len > self.parts.len() {
            return Ok(None);
        }
        self.admit_store_directory_growth(3, "part compaction")?;
        let inputs: Vec<Arc<Part>> = self.parts[lo..lo + len].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[lo + len - 1].seq_hi;
        let file = format!("part-{seq_lo:08}-{seq_hi:08}.part");
        debug_assert!(
            !self.manifest.parts.iter().any(|p| p.file == file),
            "merge output {file} collides with a live part"
        );
        let path = self.dir.join(&file);
        // 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();
        let (meta, stats) = match crate::part::merge::merge_opts_with_control_and_limits(
            &path,
            &inputs,
            self.cfg.level,
            total,
            control,
            self.read_limits,
        ) {
            Ok(built) => built,
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };

        // Publish: the merged part is durable (part::build fsyncs) before the manifest names it, and
        // the manifest swap is the single linearization point. A crash before it leaves the merged
        // file as an unreachable orphan. The INPUTS are not deleted here: retained manifests still
        // name them, so a reader inside the retention window keeps a complete snapshot on disk.
        // 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, and the output must remain available to any retained manifest that
        // may have landed.
        let digest = match hash_file_with_control(&path, control, "part compaction output hashing")
            .map(|hash| hash.to_hex().to_string())
        {
            Ok(digest) => digest,
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };
        if let Err(error) = control.check("part compaction") {
            let _ = crate::vfs::unlink(&path);
            return Err(error.into());
        }
        let mut m = self.manifest.clone();
        m.parts.splice(
            lo..lo + len,
            [PartRef {
                file: file.clone(),
                seq_lo: meta.seq_lo,
                seq_hi: meta.seq_hi,
                records: meta.n_records,
                b3: Some(digest),
            }],
        );
        m.commit_with_limits(&self.dir, self.read_limits)?;

        self.parts.splice(
            lo..lo + len,
            [Arc::new(Part::open_in_with_limits(&path, self.pcache.clone(), self.read_limits)?)],
        );
        self.manifest = m;
        self.note_manifest_commit();
        sweep_unreachable_with_limits(&self.dir, self.read_limits)?;
        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 settlement. Total merges are also the only ones allowed to drop tombstones,
    /// so deletes actually settle instead of shadowing 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>> {
        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 = std::fs::metadata(self.dir.join(&part.file))
                    .with_context(|| format!("measure compaction input {}", part.file))?
                    .len();
                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-compaction plan.
    ///
    /// Input file 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.dir)
                .with_context(|| {
                    format!("measure available filesystem bytes at {}", self.dir.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>> {
        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 = std::fs::metadata(self.dir.join(&output.file))
            .with_context(|| format!("measure compaction output {}", output.file))?
            .len();
        Ok(Some(BoundedCompaction { plan, output_bytes, merge }))
    }

    /// Report exact live-part format migration progress without decoding rows or content.
    pub fn format_migration_status(&self) -> Result<FormatMigrationStatus> {
        self.format_migration_status_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::format_migration_status`] with cooperative part checkpoints.
    pub fn format_migration_status_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<FormatMigrationStatus> {
        control.check("format migration status")?;
        let mut status = FormatMigrationStatus {
            target_part_version: crate::part::PART_VERSION,
            live_parts: self.parts.len(),
            ..FormatMigrationStatus::default()
        };
        for (part, part_ref) in self.parts.iter().zip(&self.manifest.parts) {
            control.check("format migration status")?;
            if part.format_version() == crate::part::PART_VERSION {
                status.current_parts = status
                    .current_parts
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("current format part count overflow"))?;
                continue;
            }
            status.legacy_parts = status
                .legacy_parts
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("legacy format part count overflow"))?;
            status.legacy_rows = status
                .legacy_rows
                .checked_add(u64::from(part_ref.records))
                .ok_or_else(|| anyhow::anyhow!("legacy format row count overflow"))?;
            status.legacy_bytes = status
                .legacy_bytes
                .checked_add(std::fs::metadata(self.dir.join(&part_ref.file))?.len())
                .ok_or_else(|| anyhow::anyhow!("legacy format byte count overflow"))?;
        }
        let live_files: HashSet<&str> =
            self.manifest.parts.iter().map(|part| part.file.as_str()).collect();
        let mut retained_seen = HashSet::new();
        for commit in list_retained_with_limits(&self.dir, self.read_limits)? {
            control.check("format migration status")?;
            let manifest = load_retained(&self.dir, commit)
                .with_context(|| format!("inspect migration state at retained commit {commit}"))?;
            for part_ref in manifest.parts {
                control.check("format migration status")?;
                if live_files.contains(part_ref.file.as_str())
                    || !retained_seen.insert(part_ref.file.clone())
                {
                    continue;
                }
                let path = self.dir.join(&part_ref.file);
                let part = Part::open_in_with_limits(&path, self.pcache.clone(), self.read_limits)?;
                if part.format_version() == crate::part::PART_VERSION {
                    continue;
                }
                status.retained_legacy_parts = status
                    .retained_legacy_parts
                    .checked_add(1)
                    .ok_or_else(|| anyhow::anyhow!("retained legacy part count overflow"))?;
                status.retained_legacy_rows = status
                    .retained_legacy_rows
                    .checked_add(u64::from(part_ref.records))
                    .ok_or_else(|| anyhow::anyhow!("retained legacy row count overflow"))?;
                status.retained_legacy_bytes = status
                    .retained_legacy_bytes
                    .checked_add(std::fs::metadata(path)?.len())
                    .ok_or_else(|| anyhow::anyhow!("retained legacy byte count overflow"))?;
            }
        }
        Ok(status)
    }

    /// Preflight the oldest remaining live legacy part for one resumable migration step.
    pub fn estimate_format_migration_space(&self) -> Result<Option<FormatMigrationPlan>> {
        self.estimate_format_migration_space_with_control(
            &crate::control::OperationControl::default(),
        )
    }

    /// [`Store::estimate_format_migration_space`] with cooperative section checkpoints.
    pub fn estimate_format_migration_space_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<FormatMigrationPlan>> {
        control.check("format migration preflight")?;
        if !self.mem.is_empty() {
            bail!(
                "format migration preflight requires a flushed memtable; call sync() and flush() first"
            );
        }
        let Some(part_index) =
            self.parts.iter().position(|part| part.format_version() < crate::part::PART_VERSION)
        else {
            return Ok(None);
        };
        let part = &self.parts[part_index];
        let part_ref = &self.manifest.parts[part_index];
        let input_bytes = std::fs::metadata(self.dir.join(&part_ref.file))?.len();
        let mut input_sections = 0usize;
        let mut input_raw_section_bytes = 0u64;
        for (_, _, raw, _) in part.sections() {
            control.check("format migration preflight")?;
            input_sections = input_sections
                .checked_add(1)
                .ok_or_else(|| anyhow::anyhow!("migration section count overflow"))?;
            input_raw_section_bytes = input_raw_section_bytes
                .checked_add(u64::from(raw))
                .ok_or_else(|| anyhow::anyhow!("migration raw section byte count overflow"))?;
        }
        let input_rows = u64::from(part_ref.records);
        let row_allowance = input_rows
            .checked_mul(64)
            .ok_or_else(|| anyhow::anyhow!("migration row framing estimate overflow"))?;
        let section_allowance = u64::try_from(input_sections)
            .map_err(|_| anyhow::anyhow!("migration section count exceeds u64"))?
            .checked_mul(256)
            .ok_or_else(|| anyhow::anyhow!("migration 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!("migration stage estimate overflow"))?;
        Ok(Some(FormatMigrationPlan {
            part_index,
            source_part_version: part.format_version(),
            seq_lo: part_ref.seq_lo,
            seq_hi: part_ref.seq_hi,
            input_rows,
            input_bytes,
            input_sections,
            input_raw_section_bytes,
            estimated_stage_bytes,
            estimate_is_hard_bound: false,
            retained_input_bytes_after_commit: input_bytes,
            filesystem_available_bytes: crate::sys::filesystem_available_bytes(&self.dir)
                .with_context(|| {
                    format!("measure available filesystem bytes at {}", self.dir.display())
                })?,
        }))
    }

    /// Atomically rewrite the oldest remaining live legacy part in the current format.
    ///
    /// Each call is one durable progress unit. Cancellation removes its unpublished output; after
    /// publication, reopening observes the migrated part and a later call resumes with the next.
    /// Content bytes are not rewritten, and unavailable legacy identities remain unavailable.
    pub fn migrate_format_step(&mut self) -> Result<Option<FormatMigrationStep>> {
        self.migrate_format_step_with_control(&crate::control::OperationControl::default())
    }

    /// [`Store::migrate_format_step`] with cooperative checkpoints before publication.
    pub fn migrate_format_step_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<FormatMigrationStep>> {
        let started = std::time::Instant::now();
        let result = self.migrate_format_step_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::FormatMigration,
            started.elapsed(),
            &result,
        );
        result
    }

    fn migrate_format_step_inner_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<Option<FormatMigrationStep>> {
        let Some(plan) = self.estimate_format_migration_space_with_control(control)? else {
            return Ok(None);
        };
        self.admit_store_directory_growth(3, "format migration")?;
        let input = self.parts[plan.part_index].clone();
        let file = format!(
            "part-mv{}-{:08}-{:08}.part",
            crate::part::PART_VERSION,
            plan.seq_lo,
            plan.seq_hi
        );
        let path = self.dir.join(&file);
        if path.exists() {
            bail!("format migration staging path already exists: {}", path.display());
        }
        let (meta, rewrite) = match crate::part::merge::merge_opts_with_control_for_operation(
            &path,
            &[input],
            self.cfg.level,
            false,
            control,
            "format migration",
            self.read_limits,
        ) {
            Ok(built) => built,
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };
        let digest = match hash_file_with_control(&path, control, "format migration") {
            Ok(hash) => hash.to_hex().to_string(),
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error);
            }
        };
        if let Err(error) = control.check("format migration publication") {
            let _ = crate::vfs::unlink(&path);
            return Err(error.into());
        }
        let output_bytes = match std::fs::metadata(&path) {
            Ok(metadata) => metadata.len(),
            Err(error) => {
                let _ = crate::vfs::unlink(&path);
                return Err(error.into());
            }
        };
        let mut manifest = self.manifest.clone();
        manifest.parts[plan.part_index] = PartRef {
            file,
            seq_lo: meta.seq_lo,
            seq_hi: meta.seq_hi,
            records: meta.n_records,
            b3: Some(digest),
        };
        manifest.commit_with_limits(&self.dir, self.read_limits)?;
        self.parts[plan.part_index] =
            Arc::new(Part::open_in_with_limits(&path, self.pcache.clone(), self.read_limits)?);
        self.manifest = manifest;
        self.note_manifest_commit();
        sweep_unreachable_with_limits(&self.dir, self.read_limits)?;
        let remaining_legacy_parts = self
            .parts
            .iter()
            .filter(|part| part.format_version() < crate::part::PART_VERSION)
            .count();
        Ok(Some(FormatMigrationStep { plan, output_bytes, remaining_legacy_parts, rewrite }))
    }

    /// 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 committed read core.
        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>> {
        if let Some(l) = self.fold.lookup(*h) {
            return Ok(Some(l));
        }
        for p in self.parts.iter().rev() {
            if let Some(l) = p.lookup_piece(h)? {
                return Ok(Some(l));
            }
        }
        Ok(None)
    }

    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 {
                BodyOp::Lit(b) => out.extend_from_slice(b),
                BodyOp::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 manifest snapshot 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()
    }

    /// The live parts, 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)
    }

    /// 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: tombstone, settle, and rewrite until this store no longer references the
    /// records and its old logical files 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 commit log, which the erasure story REQUIRES: a snapshot 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 (packs, replicas, 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.
    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> {
        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),
        })
    }

    fn live_fold_pieces_with_control(
        &self,
        control: &crate::control::OperationControl,
    ) -> Result<HashMap<PieceHash, Loc>> {
        let visible = read::visibility(&self.parts)?;
        let mut pieces: HashMap<PieceHash, Loc> = HashMap::new();
        for (part_index, rows) in visible.rows.iter().enumerate() {
            for &row in rows {
                control.check("content reachability")?;
                for content in self.parts[part_index].record(row)?.contents {
                    for operation in content.ops {
                        let BodyOp::Piece { hash, len } = operation else { continue };
                        if let Some(existing) = pieces.get(&hash) {
                            if existing.raw != len {
                                bail!(
                                    "live piece {hash} has inconsistent lengths {} and {len}",
                                    existing.raw
                                );
                            }
                            continue;
                        }
                        let location = self.locate(&hash)?.ok_or_else(|| {
                            anyhow::anyhow!("live record references absent piece {hash}")
                        })?;
                        if location.raw != len {
                            bail!(
                                "live piece {hash} is {} bytes but its record says {len}",
                                location.raw
                            );
                        }
                        pieces.insert(hash, location);
                    }
                }
            }
        }
        Ok(pieces)
    }

    /// Reclaim erased space IN PLACE: punch every fold block no live record can reach.
    ///
    /// The cheap half of erasure, and the one a sealed store wants. 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 part is rebuilt and no reader is
    /// disturbed.
    ///
    /// **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<PunchStats> {
        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<PunchStats> {
        let started = std::time::Instant::now();
        let result = self.punch_unreferenced_inner_with_control(control);
        self.observe_lifecycle(
            crate::observability::LifecycleOperation::Punch,
            started.elapsed(),
            &result,
        );
        result
    }

    fn punch_unreferenced_inner_with_control(
        &mut self,
        control: &crate::control::OperationControl,
    ) -> Result<PunchStats> {
        control.check("content punching")?;
        if !self.mem.is_empty() {
            bail!("punching requires a flushed memtable; call sync() and flush() first");
        }
        // Every block a live record can still reach, via the piece dictionaries of live rows.
        let live_blocks: HashSet<u32> = self
            .live_fold_pieces_with_control(control)?
            .values()
            .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(PunchStats::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)) {
            control.check("content punching")?;
            self.admit_store_directory_growth(2, "content punching")?;
            let mut m = self.manifest.clone();
            let mut all: Vec<u32> = already.into_iter().chain(dead.iter().copied()).collect();
            all.sort_unstable();
            m.punched = to_ranges(&all);
            m.commit_with_limits(&self.dir, self.read_limits)?;
            self.manifest = m;
            self.note_manifest_commit();
        }
        // 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);

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

    /// Rewrite the fold, keeping only content that live records still reference.
    ///
    /// The ONLY operation that touches content. Everything else asserts it does not, which is why this
    /// is a separate call rather than a flag: a reader of the merge path should never have to wonder.
    ///
    /// Requires a flushed memtable — staged records reference the old fold, and rebuilding parts under
    /// them would leave their pieces unresolvable.
    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(std::fs::metadata(self.dir.join(&part_ref.file))?.len())
                .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 manifest commit 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> {
        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.admit_store_directory_growth(self.parts.len() as u64 + 3, "content refold")?;
        let seqs: Vec<(u64, u64)> =
            self.manifest.parts.iter().map(|p| (p.seq_lo, p.seq_hi)).collect();
        let (new_gen, built, mut stats) = refold::refold_with_control_and_limits(
            &self.dir,
            &self.parts,
            &seqs,
            &self.fold,
            self.manifest.fold_gen,
            self.cfg,
            control,
            self.read_limits,
        )?;

        // Data before pointers, exactly as everywhere else: the new fold and the new parts are durable
        // before the manifest names either, and the manifest swap is the instant it takes effect.
        let new_dir = refold::fold_dir(&self.dir, new_gen);
        let prepared = (|| -> Result<Manifest> {
            let mut m = self.manifest.clone();
            m.parts = built
                .iter()
                .map(|(file, lo, hi, n)| {
                    control.check("content refold")?;
                    Ok(PartRef {
                        file: file.clone(),
                        seq_lo: *lo,
                        seq_hi: *hi,
                        records: *n,
                        b3: Some(
                            hash_file_with_control(
                                &self.dir.join(file),
                                control,
                                "content refold output hashing",
                            )?
                            .to_hex()
                            .to_string(),
                        ),
                    })
                })
                .collect::<Result<_>>()?;
            m.fold_gen = new_gen;
            // Block ids are PER GENERATION. The new fold was rewritten without erased content and
            // therefore has no holes inherited from the old generation.
            m.punched.clear();
            let f = Fold::open_with_limits(&new_dir, self.cfg, self.read_limits)?;
            let t = f.tail();
            m.fold_seg = t.seg;
            m.fold_off = t.off;
            control.check("content refold")?;
            Ok(m)
        })();
        let mut m = match prepared {
            Ok(manifest) => manifest,
            Err(error) => {
                cleanup_refold_stage(&self.dir, new_gen, &built);
                return Err(error);
            }
        };
        // No cancellation checkpoint after this call begins. A failed commit can have durably
        // written its retained copy, so staged files must remain for ordinary recovery.
        m.commit_with_limits(&self.dir, self.read_limits)?;

        // Everything past here is cleanup: a crash leaves orphans, which open() sweeps.
        let old_gen = self.manifest.fold_gen;
        self.manifest = m;
        // PURGE the retained log down to this commit alone. Erasure semantics trump snapshots: a
        // re-fold exists to make dropped content unreachable in this store, and a retained manifest would keep the old
        // generation — deleted records included — readable for MANIFEST_RETAIN more commits.
        // Time travel does not cross a re-fold, by design; that is the point of running one.
        //
        // The unlinks are durable and propagated, because they are the erasure claim, not window
        // pruning: a swallowed failure or a lost dirent would leave the old generation readable
        // through a name this method just promised was gone. The re-fold itself is already
        // committed when this runs, so an error here means "committed, but the purge is
        // incomplete — reopen the store", and reopening completes it: writer open durably removes
        // retained manifests from any other fold generation.
        for c in list_retained_with_limits(&self.dir, self.read_limits)? {
            if c != self.manifest.commit {
                crate::vfs::unlink(&retained_path(&self.dir, c)).with_context(|| {
                    format!(
                        "re-fold committed, but purging retained manifest {c} failed — reopen \
                         the store to complete the purge"
                    )
                })?;
            }
        }
        crate::vfs::sync_dir(&self.dir)?;
        self.retained_commit_count = 1;
        let part_cache_budget = self.pcache.budget();
        self.pcache = Arc::new(SectionCache::new(part_cache_budget));
        self.parts.clear();
        for p in &self.manifest.parts {
            self.parts.push(Arc::new(Part::open_in_with_limits(
                &self.dir.join(&p.file),
                self.pcache.clone(),
                self.read_limits,
            )?));
        }
        self.fold = Fold::open_at_with_limits(
            &new_dir,
            self.cfg,
            self.manifest.fold_tail(),
            // Empty by construction — a new generation has no punched declaration, which is what
            // `m.punched.clear()` above committed.
            &self.manifest.punched,
            self.read_limits,
        )?;
        sweep_unreachable_with_limits(&self.dir, self.read_limits)?;
        // Reported, not swallowed. Claiming `bytes_reclaimed()` while the old generation still
        // occupies the disk would be a stat that says the opposite of the truth. The re-fold itself
        // is already committed and correct; this is only honest about what is left behind.
        if refold::fold_dir(&self.dir, old_gen).exists() {
            stats.stale_generation_left = true;
        }
        Ok(stats)
    }

    /// 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()
    }
    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,
        }
    }

    /// Walk the store directory once and classify every regular file 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> {
        store_space_usage(&self.dir, &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())
    }
}

fn store_space_usage(
    dir: &Path,
    live_manifest: &Manifest,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<StoreSpaceUsage> {
    control.check("store space inventory")?;
    let mut live_files: HashSet<PathBuf> =
        [PathBuf::from("MANIFEST"), PathBuf::from("WAL")].into_iter().collect();
    live_files.extend(live_manifest.parts.iter().map(|part| PathBuf::from(&part.file)));
    let live_fold = fold_relative_dir(dir, live_manifest.fold_gen)?;

    let mut retained_files = HashSet::new();
    let mut retained_folds = HashSet::new();
    for commit in list_retained_with_limits(dir, read_limits)? {
        control.check("store space inventory")?;
        let retained_path = retained_path(dir, commit);
        retained_files.insert(relative_store_path(dir, &retained_path)?);
        let manifest = load_retained(dir, commit)
            .with_context(|| format!("account retained manifest {commit}"))?;
        retained_files.extend(manifest.parts.iter().map(|part| PathBuf::from(&part.file)));
        retained_folds.insert(fold_relative_dir(dir, manifest.fold_gen)?);
    }

    let mut usage = StoreSpaceUsage {
        filesystem_available_bytes: crate::sys::filesystem_available_bytes(dir)
            .with_context(|| format!("measure available filesystem bytes at {}", dir.display()))?,
        ..StoreSpaceUsage::default()
    };
    let reachability = SpaceReachability {
        live_files: &live_files,
        live_fold: &live_fold,
        retained_files: &retained_files,
        retained_folds: &retained_folds,
    };
    account_store_files(dir, dir, &reachability, &mut usage, read_limits, control)?;
    Ok(usage)
}

fn fold_relative_dir(dir: &Path, generation: u32) -> Result<PathBuf> {
    relative_store_path(dir, &refold::fold_dir(dir, generation))
}

fn relative_store_path(dir: &Path, path: &Path) -> Result<PathBuf> {
    path.strip_prefix(dir)
        .map(Path::to_path_buf)
        .with_context(|| format!("{} is outside store {}", path.display(), dir.display()))
}

struct SpaceReachability<'a> {
    live_files: &'a HashSet<PathBuf>,
    live_fold: &'a Path,
    retained_files: &'a HashSet<PathBuf>,
    retained_folds: &'a HashSet<PathBuf>,
}

fn account_store_files(
    root: &Path,
    start: &Path,
    reachability: &SpaceReachability<'_>,
    usage: &mut StoreSpaceUsage,
    read_limits: ReadLimits,
    control: &crate::control::OperationControl,
) -> Result<()> {
    let mut directories = vec![start.to_path_buf()];
    let mut visited = 0u64;
    while let Some(dir) = directories.pop() {
        for entry in std::fs::read_dir(&dir)
            .with_context(|| format!("read store space directory {}", dir.display()))?
        {
            visited = visited.saturating_add(1);
            read_limits.admit_directory_entries("store filesystem inventory", visited)?;
            control.check("store space inventory")?;
            let entry = entry?;
            let file_type = entry.file_type()?;
            if file_type.is_dir() {
                directories.push(entry.path());
            } else if file_type.is_file() {
                let relative = relative_store_path(root, &entry.path())?;
                let metadata = entry.metadata()?;
                add_space(&mut usage.total, &metadata)?;
                let live = reachability.live_files.contains(&relative)
                    || relative.starts_with(reachability.live_fold);
                let retained = reachability.retained_files.contains(&relative)
                    || reachability.retained_folds.iter().any(|fold| relative.starts_with(fold));
                if live {
                    add_space(&mut usage.live, &metadata)?;
                } else if retained {
                    add_space(&mut usage.retained_only, &metadata)?;
                } else {
                    add_space(&mut usage.unclassified, &metadata)?;
                }
            }
        }
    }
    Ok(())
}

fn add_space(amount: &mut SpaceAmount, metadata: &std::fs::Metadata) -> Result<()> {
    amount.files =
        amount.files.checked_add(1).ok_or_else(|| anyhow::anyhow!("store file count overflow"))?;
    amount.logical_bytes = amount
        .logical_bytes
        .checked_add(metadata.len())
        .ok_or_else(|| anyhow::anyhow!("store logical byte count overflow"))?;
    amount.allocated_bytes = match (amount.allocated_bytes, crate::sys::allocated_bytes(metadata)) {
        (Some(total), Some(bytes)) => Some(
            total
                .checked_add(bytes)
                .ok_or_else(|| anyhow::anyhow!("store allocated byte count overflow"))?,
        ),
        _ => None,
    };
    Ok(())
}

/// 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 file 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 current live part list.
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 files.
    pub input_rows: u64,
    /// Sum of the selected files' exact on-disk lengths.
    pub input_bytes: u64,
    /// Whether this run covers the complete live list and may settle 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 PunchStats {
    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 the committed state. 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 committed 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 manifest snapshot.
    pub fn scan(&self, request: &crate::scan::ScanRequest) -> Result<crate::scan::ScanPage> {
        crate::scan::scan_read_store(self, request)
    }

    /// 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 manifest snapshot 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()
    }
    /// The live parts, oldest to newest — for tools that walk them (verification, inspection).
    pub fn parts(&self) -> &[Arc<Part>] {
        &self.parts
    }
    /// The fold, for tools that scrub or measure it.
    pub fn fold(&self) -> &Fold {
        &self.fold
    }
    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 {
                            BodyOp::Lit(b) => b.len() + 8,
                            BodyOp::Piece { .. } => 40,
                        })
                        .sum::<usize>()
            })
            .sum::<usize>()
        + r.attrs.iter().map(|(k, _)| k.len() + 24).sum::<usize>()
}

/// Reject a store directory that is obviously not one, before doing anything destructive.
pub fn looks_like_store(dir: &Path) -> bool {
    dir.join("MANIFEST").exists() || dir.join("fold").exists()
}

// 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(not(any(unix, target_os = "wasi")))]
compile_error!(
    "turndb needs positioned file reads (pread). Unix and WASI provide them; \
     wasm32-unknown-unknown has no filesystem at all — build for wasm32-wasip1 instead."
);

#[cfg(test)]
mod tests {
    fn manifest_bytes_with_part(file: &str) -> Vec<u8> {
        serde_json::to_vec(&super::Manifest {
            parts: vec![super::PartRef {
                file: file.into(),
                seq_lo: 1,
                seq_hi: 1,
                records: 1,
                b3: None,
            }],
            next_seq: 2,
            ..Default::default()
        })
        .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("store-local path component"), "{hostile:?}: {error}");
        }
        assert!(
            super::Manifest::parse(&manifest_bytes_with_part("part-00000001.part")).is_ok(),
            "an ordinary legacy manifest remains accepted"
        );
    }

    #[test]
    fn manifest_semantics_reject_ambiguous_or_malformed_authority() {
        let part = super::PartRef {
            file: "part-00000001.part".into(),
            seq_lo: 2,
            seq_hi: 1,
            records: 1,
            b3: None,
        };
        let inverted = super::Manifest { parts: vec![part.clone()], ..Default::default() };
        assert!(super::Manifest::parse(&serde_json::to_vec(&inverted).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() },
            ],
            ..Default::default()
        };
        assert!(super::Manifest::parse(&serde_json::to_vec(&duplicate).unwrap()).is_err());

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

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

    #[test]
    fn manifest_size_is_refused_before_reading_a_sparse_body() {
        let d = std::env::temp_dir().join(format!("turndb-manifest-limit-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let path = d.join("MANIFEST");
        std::fs::File::create(&path).unwrap().set_len(super::MAX_MANIFEST_BYTES + 1).unwrap();
        let error = format!("{:#}", super::Manifest::load(&d).unwrap_err());
        std::fs::remove_dir_all(d).ok();
        assert!(error.contains("exceeding") && error.contains("limit"), "{error}");
    }

    /// The bug this exists to prevent: corruption that still PARSES. A shortened `fold_off` here
    /// would have been believed, and recovery would then have truncated durable fold bytes to
    /// match it — data destroyed by one flipped bit with no error anywhere.
    #[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 mut m = super::Manifest { fold_off: 4096, next_seq: 9, ..Default::default() };
        m.commit(&d).unwrap();

        let mut b = std::fs::read(d.join("MANIFEST")).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
        std::fs::write(d.join("MANIFEST"), &b).unwrap();

        let err = super::Manifest::load(&d).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 not demote a checksummed manifest to a trusted legacy one.
    #[test]
    fn a_damaged_trailer_is_not_read_as_legacy() {
        let d = std::env::temp_dir().join(format!("turndb-mantrail-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let mut m = super::Manifest::default();
        m.commit(&d).unwrap();

        let mut b = std::fs::read(d.join("MANIFEST")).unwrap();
        let at = b.len() - 14; // the 'c' of the final "crc32=XXXXXXXX" line
        b[at] = b'x';
        std::fs::write(d.join("MANIFEST"), &b).unwrap();

        assert!(
            super::Manifest::load(&d).is_err(),
            "trailing bytes must fail JSON parsing, not be ignored"
        );
        std::fs::remove_dir_all(&d).ok();
    }

    /// The retained log: every commit leaves a copy, the window prunes, recovery promotes.
    #[test]
    fn the_commit_log_retains_prunes_and_recovers() {
        let d = std::env::temp_dir().join(format!("turndb-manlog-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let mut m = super::Manifest::default();
        for i in 1..=6u32 {
            m.fold_off = i * 100; // distinguishable states
            m.commit(&d).unwrap();
        }
        assert_eq!(m.commit, 6);
        assert_eq!(
            super::list_retained(&d).unwrap(),
            vec![3, 4, 5, 6],
            "window of {} commits",
            super::MANIFEST_RETAIN
        );

        // Bit rot in MANIFEST: open refuses; recovery promotes the newest copy — same commit,
        // nothing lost.
        let mut b = std::fs::read(d.join("MANIFEST")).unwrap();
        b[10] ^= 0xFF;
        std::fs::write(d.join("MANIFEST"), &b).unwrap();
        assert!(super::Manifest::load(&d).is_err());
        assert_eq!(super::complete_first_commit(&d).unwrap(), 6);
        assert_eq!(super::Manifest::load(&d).unwrap().fold_off, 600);

        // MANIFEST *and* the newest copies damaged: recovery rolls back to the newest intact one
        // and truncates the log to it — the abandoned copies cannot be promoted later.
        let mut b = std::fs::read(d.join("MANIFEST")).unwrap();
        b[10] ^= 0xFF;
        std::fs::write(d.join("MANIFEST"), &b).unwrap();
        std::fs::write(super::retained_path(&d, 6), b"garbage").unwrap();
        std::fs::write(super::retained_path(&d, 5), b"garbage").unwrap();
        assert_eq!(super::complete_first_commit(&d).unwrap(), 4);
        assert_eq!(super::Manifest::load(&d).unwrap().fold_off, 400);
        assert_eq!(
            super::list_retained(&d).unwrap(),
            vec![3, 4],
            "the abandoned timeline is cleared"
        );

        // An intact store refuses rollback.
        assert!(
            super::complete_first_commit(&d).is_err(),
            "recovery of a healthy store must refuse"
        );

        // A MISSING manifest beside a commit log is damage, not a new store.
        std::fs::remove_file(d.join("MANIFEST")).unwrap();
        assert!(super::Manifest::load(&d).is_err(), "missing MANIFEST + commit log must refuse");
        assert_eq!(super::complete_first_commit(&d).unwrap(), 4);
        assert_eq!(super::Manifest::load(&d).unwrap().fold_off, 400);
        std::fs::remove_dir_all(&d).ok();
    }

    #[test]
    fn manifest_roundtrips() {
        let d = std::env::temp_dir().join(format!("turndb-man-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        let mut m = super::Manifest {
            parts: vec![super::PartRef {
                file: "p.part".into(),
                seq_lo: 1,
                seq_hi: 1,
                records: 7,
                b3: None,
            }],
            fold_seg: 2,
            fold_off: 4096,
            next_seq: 9,
            fold_gen: 3,
            commit: 0,
            prev: None,
            punched: Vec::new(),
        };
        m.commit(&d).unwrap();
        let got = super::Manifest::load(&d).unwrap();
        assert_eq!(got.parts.len(), 1);
        assert_eq!(got.fold_off, 4096);
        assert_eq!(got.fold_gen, 3);
        assert_eq!(got.next_seq, 9);
        assert_eq!(got.commit, 1, "commit() must advance the commit counter");
        assert!(!d.join("MANIFEST.tmp").exists(), "staging file must not survive a commit");
        std::fs::remove_dir_all(&d).ok();
    }

    #[test]
    fn format_migration_is_one_part_atomic_resumable_and_content_preserving() {
        let d = std::env::temp_dir().join(format!(
            "turndb-migration-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        std::fs::create_dir_all(&d).unwrap();
        let mut fold =
            crate::fold::Fold::open(&d.join("fold"), crate::fold::FoldCfg::default()).unwrap();
        fold.sync().unwrap();
        let tail = fold.tail();
        drop(fold);
        let mut part_refs = Vec::new();
        for (seq, id) in [(1, "legacy-one"), (2, "legacy-two")] {
            let file = format!("legacy-{seq}.part");
            let meta = crate::part::build_revision_one_fixture(&d.join(&file), seq, id).unwrap();
            part_refs.push(super::PartRef {
                file,
                seq_lo: meta.seq_lo,
                seq_hi: meta.seq_hi,
                records: meta.n_records,
                b3: None,
            });
        }
        let mut manifest = super::Manifest {
            parts: part_refs,
            fold_seg: tail.seg,
            fold_off: tail.off,
            next_seq: 2,
            ..super::Manifest::default()
        };
        manifest.commit(&d).unwrap();

        let mut store = super::Store::open(&d, crate::fold::FoldCfg::default()).unwrap();
        let before = store.format_migration_status().unwrap();
        assert_eq!(before.legacy_parts, 2);
        assert_eq!(before.current_parts, 0);
        let plan = store.estimate_format_migration_space().unwrap().unwrap();
        assert_eq!(plan.source_part_version, 1);
        assert_eq!(plan.input_rows, 1);
        assert!(!plan.estimate_is_hard_bound);

        let cancellation = crate::control::CancellationToken::new();
        cancellation.cancel();
        let error = store
            .migrate_format_step_with_control(&crate::control::OperationControl {
                deadline: None,
                cancellation: Some(cancellation),
            })
            .unwrap_err();
        assert!(error.downcast_ref::<crate::control::OperationInterrupted>().is_some());
        assert_eq!(store.format_migration_status().unwrap().legacy_parts, 2);

        let step = store.migrate_format_step().unwrap().unwrap();
        assert_eq!(step.plan.part_index, plan.part_index);
        assert_eq!(step.plan.source_part_version, plan.source_part_version);
        assert_eq!((step.plan.seq_lo, step.plan.seq_hi), (plan.seq_lo, plan.seq_hi));
        assert_eq!(step.plan.input_bytes, plan.input_bytes);
        assert_eq!(step.rewrite.inputs, 1);
        assert_eq!(step.remaining_legacy_parts, 1);
        assert!(step.output_bytes <= plan.estimated_stage_bytes);
        let record = store.get("legacy-one").unwrap().unwrap();
        assert_eq!(record.contents[0].name, crate::types::BODY_CONTENT);
        assert_eq!(record.contents[0].identity, None, "migration must not invent identity");
        assert_eq!(record.contents[0].ops, [crate::BodyOp::Lit(b"legacy".to_vec())]);
        drop(store);

        let mut reopened = super::Store::open(&d, crate::fold::FoldCfg::default()).unwrap();
        let midway = reopened.format_migration_status().unwrap();
        assert_eq!(midway.legacy_parts, 1);
        assert_eq!(midway.current_parts, 1);
        assert_eq!(midway.retained_legacy_parts, 1);
        let resumed = reopened.migrate_format_step().unwrap().unwrap();
        assert_eq!(resumed.remaining_legacy_parts, 0);
        assert!(reopened.migrate_format_step().unwrap().is_none());
        let after = reopened.format_migration_status().unwrap();
        assert_eq!(after.legacy_parts, 0);
        assert_eq!(after.current_parts, 2);
        assert_eq!(after.retained_legacy_parts, 2);
        assert!(after.retained_legacy_bytes > 0);
        assert_eq!(reopened.get("legacy-one").unwrap().unwrap(), record);
        assert!(reopened.get("legacy-two").unwrap().is_some());
        std::fs::remove_dir_all(&d).ok();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn punching_retries_blocks_already_declared_before_a_crash() {
        let d = std::env::temp_dir().join(format!(
            "turndb-punch-resume-{}-{}",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
        ));
        let cfg = crate::fold::FoldCfg { block_target: 1, ..Default::default() };
        let mut store = super::Store::open(&d, cfg).unwrap();
        let old = vec![0x41; 64 * 1024];
        let live = vec![0x42; 64 * 1024];
        store.put("k", &[super::Span::Piece(&old)], vec![]).unwrap();
        store.sync().unwrap();
        store.flush().unwrap();
        store.put("k", &[super::Span::Piece(&live)], vec![]).unwrap();
        store.sync().unwrap();
        store.flush().unwrap();

        let live_block = store.locate(&crate::PieceHash::of(&live)).unwrap().unwrap().block_id;
        let dead: Vec<u32> =
            store.fold.block_ids().into_iter().filter(|&block| block != live_block).collect();
        assert!(!dead.is_empty());

        // The durable state left by a crash immediately after "record first, punch second".
        let mut manifest = store.manifest.clone();
        manifest.punched = super::to_ranges(&dead);
        manifest.commit(&d).unwrap();
        store.manifest = manifest;
        store.fold.declare_punched(&store.manifest.punched);

        let stats = store.punch_unreferenced().unwrap();
        assert_eq!(stats.blocks_examined, dead.len());
        assert_eq!(stats.blocks_punched, dead.len(), "declared blocks must be retried");
        assert_eq!(store.reconstruct("k").unwrap().unwrap(), live);
        std::fs::remove_dir_all(&d).ok();
    }
}

#[cfg(test)]
mod compat_tests {
    /// A manifest written before fold generations existed must still load, naming generation 0 — the
    /// original `fold/` directory. Otherwise this change would silently orphan every existing store.
    #[test]
    fn a_manifest_without_fold_gen_reads_as_generation_zero() {
        let d = std::env::temp_dir().join(format!("turndb-oldman-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(
            d.join("MANIFEST"),
            br#"{"parts":[],"fold_seg":0,"fold_off":48,"next_seq":4}"#,
        )
        .unwrap();
        let m = super::Manifest::load(&d).unwrap();
        assert_eq!(m.fold_gen, 0, "a pre-generation manifest must mean the original fold/");
        assert_eq!(m.next_seq, 4);
        assert_eq!(super::refold::fold_dir(&d, m.fold_gen), d.join("fold"));
        std::fs::remove_dir_all(&d).ok();
    }
}