revault_lockbox_api 0.0.59

reVault lockbox API to create and manage lockboxes
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
use super::metric_timer::MetricTimer as Instant;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Cursor, Read, SeekFrom, Write};
use std::path::Path;
use std::sync::{Arc, Mutex};

use super::file_handles::LockboxFileReader;
use super::file_import_pipeline::{
    CompressionFrameWrite, FileImportPipeline, ParallelCompressionJob, ParallelCompressionResult,
    PreparedCompressionFrame,
};
use super::Lockbox;
use crate::compression::{
    decode_compression_frame, validate_compression_frame_lengths, COMPRESSION_NONE,
    ZSTD_BULK_IMPORT_LEVEL, ZSTD_DEFAULT_LEVEL,
};
use crate::compression_frame_manifest::{CompressionFrameManifest, CompressionFrameSlice};
use crate::constants::{
    DEFAULT_FILE_PERMISSIONS, DEFAULT_MAX_PAGE_BODY_BYTES, DEFAULT_MAX_PAGE_LOGICAL_BYTES,
};
use crate::crypto::strong_checksum;
use crate::file_chunk::{CompressionFrameSegment, FileChunk, PendingFileChunk};
use crate::file_format::decode_compression_frame_segment_payload_view;
use crate::lockbox_path::LockboxPath;
use crate::node_kind::NodeKind;
use crate::page::{PageObject, PageObjectKind, DEFAULT_PAGE_BYTES};
use crate::page_buffer::{SensitiveBytes, ZeroizingBytes};
use crate::page_object_packer::PageObjectPacker;
use crate::security::validate_permissions;
use crate::toc_entry::TocEntry;
use crate::{Error, Result, WorkloadProfile};
use sha2::{Digest, Sha256};
use zeroize::Zeroize;

#[cfg(any(unix, windows))]
fn open_host_file_nofollow(source: &Path) -> Result<std::fs::File> {
    use cap_fs_ext::{FollowSymlinks, OpenOptionsFollowExt};
    use cap_std::fs::{Dir, OpenOptions};
    let parent = source
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let name = source
        .file_name()
        .ok_or_else(|| Error::UnsupportedHostPath(source.display().to_string()))?;
    let directory = Dir::open_ambient_dir(parent, cap_std::ambient_authority())
        .map_err(|err| Error::Io(format!("open {}: {err}", parent.display())))?;
    let mut options = OpenOptions::new();
    options.read(true).follow(FollowSymlinks::No);
    let file = directory
        .open_with(name, &options)
        .map_err(|err| Error::Io(format!("open {}: {err}", source.display())))?;
    if !file
        .metadata()
        .map_err(|err| Error::Io(err.to_string()))?
        .is_file()
    {
        return Err(Error::UnsupportedHostPath(source.display().to_string()));
    }
    Ok(file.into_std())
}

#[cfg(not(any(unix, windows)))]
fn open_host_file_nofollow(source: &Path) -> Result<std::fs::File> {
    // Hosted WASM delegates filesystem operations to the native host. Do not
    // replace the native no-follow guarantee with an unchecked path open.
    Err(Error::UnsupportedHostPath(source.display().to_string()))
}

// A verified native slice can be written directly while its zeroizing cache
// allocation stays alive. Vec-returning APIs copy shared slices only when needed.
#[cfg(any(test, feature = "native-block-layout"))]
pub(super) enum NativeReadBytes {
    Owned(Vec<u8>),
    SensitiveOwned(SensitiveBytes),
    Shared {
        frame: Arc<super::CachedCompressionFrame>,
        range: std::ops::Range<usize>,
        source_guard: Option<(u64, u64)>,
    },
}

#[cfg(any(test, feature = "native-block-layout"))]
impl NativeReadBytes {
    fn for_internal_write(self, sensitive: bool) -> Self {
        match self {
            Self::Owned(bytes) => Self::SensitiveOwned(SensitiveBytes::new(bytes, sensitive)),
            other => other,
        }
    }
    fn ensure_current(&self, storage: &crate::storage::StorageBackend) -> Result<()> {
        if let Self::Shared {
            source_guard: Some((required_end, revision)),
            ..
        } = self
        {
            if *required_end > storage.current_len()? {
                return Err(Error::Truncated);
            }
            if *revision == u64::MAX || *revision != storage.write_revision() {
                return Err(Error::CorruptRecord);
            }
        }
        Ok(())
    }

    fn into_vec(self, storage: &crate::storage::StorageBackend) -> Result<Vec<u8>> {
        match self {
            Self::Owned(bytes) => Ok(bytes),
            Self::SensitiveOwned(bytes) => Ok(bytes.into_vec()),
            shared @ Self::Shared { .. } => {
                let mut bytes = ZeroizingBytes::new(shared.to_vec());
                // Owned results keep the original cache-hit check after copying.
                shared.ensure_current(storage)?;
                Ok(std::mem::take(&mut *bytes))
            }
        }
    }
}

#[cfg(any(test, feature = "native-block-layout"))]
impl std::ops::Deref for NativeReadBytes {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        match self {
            Self::Owned(bytes) => bytes,
            Self::SensitiveOwned(bytes) => bytes,
            Self::Shared { frame, range, .. } => &frame.data[range.clone()],
        }
    }
}

const SMALL_FILE_PACKING_LIMIT: usize = 1024 * 1024;
const SMALL_FILE_COMPRESSION_FRAME_BYTES: usize = 4 * 1024;
const BULK_IMPORT_SMALL_FILE_COMPRESSION_FRAME_BYTES: usize = 2 * 1024 * 1024;
pub(super) const FILE_COMPRESSION_FRAME_BYTES: usize = 2 * 1024 * 1024;
const MAX_SEGMENT_BYTES: usize = DEFAULT_MAX_PAGE_BODY_BYTES - 64 * 1024;
const DECODED_COMPRESSION_FRAME_CACHE_BYTES: usize = 64 * 1024 * 1024;

// An immutable, fully verified slice of a raw frame. Keeping the page alive
// shares its existing zeroizing payload rather than duplicating plaintext.
pub(super) struct VerifiedFileRange {
    page: Arc<crate::page::DecodedPage>,
    object_index: usize,
    range: std::ops::Range<usize>,
}

impl VerifiedFileRange {
    pub(super) fn with_bytes<R>(&self, f: impl FnOnce(&[u8]) -> R) -> Result<R> {
        self.page.objects[self.object_index].with_payload(|payload| f(&payload[self.range.clone()]))
    }
}

fn validate_frame_segment(
    decoded: &crate::file_format::payload::DecodedFileChunkView<'_>,
    chunk: &FileChunk,
    segment: &CompressionFrameSegment,
    expected_total_len: u64,
) -> Result<()> {
    let manifest_slice_missing = decoded.manifest.as_ref().is_some_and(|manifest| {
        manifest
            .slice_for(
                &chunk.stored_path,
                chunk.file_offset,
                chunk.compression_frame_offset,
                chunk.len,
            )
            .filter(|slice| slice.total_len == 0 || slice.total_len == expected_total_len)
            .is_none()
    });
    if decoded.compression_frame_id != chunk.compression_frame_id
        || decoded.compression_frame_len != chunk.compression_frame_len
        || decoded.compressed_len != chunk.compressed_len
        || decoded.compression != chunk.compression
        || decoded.compression_frame_digest != chunk.compression_frame_digest
        || manifest_slice_missing
        || decoded.segment_offset != segment.segment_offset
        || decoded.data.len() as u64 != segment.segment_len
    {
        return Err(Error::CorruptRecord);
    }
    Ok(())
}

#[cfg(test)]
mod range_integrity_tests {
    use super::*;

    #[test]
    fn legacy_writer_rejects_native_preparation_before_mutating_storage() {
        let mut archive = Lockbox::create(b"prepared layout mismatch test");
        let path = LockboxPath::new("/native").unwrap();
        let prepared = FileImportPipeline::new(3, 1)
            .with_native_blocks(true)
            .prepare(&[CompressionFrameWrite {
                path: &path,
                permissions: 0o600,
                total_len: 11,
                file_offset: 0,
                data: b"test bytes!",
            }]);
        let before = archive.to_bytes();
        let sequence = archive.sequence;
        let mut chunks = Vec::new();
        {
            let mut writer = FilePageWriter::new(&mut archive);
            writer.native_blocks = false;
            assert!(writer
                .write_prepared_compression_frame(prepared, &mut chunks)
                .is_err());
        }
        assert!(chunks.is_empty());
        assert_eq!(archive.sequence, sequence);
        assert_eq!(archive.to_bytes(), before);
    }

    #[test]
    fn partial_frame_read_checks_bytes_outside_the_requested_range() {
        let lb = Lockbox::create(b"range integrity test");
        let mut stored = vec![42; 4096];
        let chunk = FileChunk {
            #[cfg(test)]
            block_frame: None,
            stored_path: LockboxPath::new("/test").unwrap(),
            file_offset: 0,
            len: stored.len() as u64,
            compression_frame_offset: 0,
            compression_frame_len: stored.len() as u64,
            compressed_len: stored.len() as u64,
            compression: COMPRESSION_NONE,
            compression_frame_id: 1,
            compression_frame_digest: strong_checksum(&stored),
            segments: Vec::new(),
        };
        assert_eq!(
            lb.read_checked_frame_slice(&chunk, &(0..8), &stored, Vec::new())
                .unwrap(),
            vec![42; 8]
        );
        stored[4095] ^= 1;
        assert!(matches!(
            lb.read_checked_frame_slice(&chunk, &(0..8), &stored, Vec::new()),
            Err(Error::CorruptRecord)
        ));
    }
}

/// Ordering used by `Lockbox::stream_content`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ContentStreamOrder {
    /// Stream by lockbox path and logical file offset.
    #[default]
    Logical,
    /// Stream stored content chunks by physical page offset where possible.
    Physical,
}
/// Options for streaming lockbox file content without extracting to disk.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ContentStreamOptions {
    /// Logical or physical order in which chunks are yielded.
    pub order: ContentStreamOrder,
}

/// Metadata for one streamed content range.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentChunk {
    /// Logical lockbox path containing this range.
    pub path: LockboxPath,
    /// Byte offset within the logical file.
    pub file_offset: u64,
    /// Number of logical bytes in the range.
    pub len: u64,
    /// Backing file offset when the chunk has physical storage.
    pub physical_offset: Option<u64>,
    /// Whether the range is a sparse zero-filled hole.
    pub sparse: bool,
}

impl<State> Lockbox<State> {
    pub(crate) fn rewrite_shared_compression_frames_before_removal(
        &mut self,
        entry: &TocEntry,
    ) -> Result<()> {
        if entry.deleted || entry.node_kind != NodeKind::File || entry.chunks.is_empty() {
            return Ok(());
        }
        let removed_compression_frames = entry
            .chunks
            .iter()
            .map(|chunk| chunk.compression_frame_id)
            .collect::<BTreeSet<_>>();
        let mut shared = BTreeSet::new();
        for other in self.toc_entries.values() {
            if other.deleted || other.path == entry.path || other.node_kind != NodeKind::File {
                continue;
            }
            if other
                .chunks
                .iter()
                .any(|chunk| removed_compression_frames.contains(&chunk.compression_frame_id))
            {
                for chunk in &other.chunks {
                    if removed_compression_frames.contains(&chunk.compression_frame_id) {
                        shared.insert(chunk.compression_frame_id);
                    }
                }
            }
        }
        if shared.is_empty() {
            return Ok(());
        }

        let mut groups: BTreeMap<u64, Vec<SharedCompressionFrameSurvivor>> = BTreeMap::new();
        for other in self.toc_entries.values() {
            if other.deleted || other.path == entry.path || other.node_kind != NodeKind::File {
                continue;
            }
            for chunk in &other.chunks {
                if shared.contains(&chunk.compression_frame_id) {
                    let data = self.read_file_chunk_compression_frame(other.len, chunk)?;
                    groups.entry(chunk.compression_frame_id).or_default().push(
                        SharedCompressionFrameSurvivor {
                            path: other.path.clone(),
                            permissions: other.permissions,
                            total_len: other.len,
                            file_offset: chunk.file_offset,
                            data,
                        },
                    );
                }
            }
        }

        let mut replacement_indices: Vec<(LockboxPath, u64, usize)> = Vec::new();
        let mut replacements: Vec<(LockboxPath, u64, FileChunk)> = Vec::new();
        {
            let mut writer = FilePageWriter::new(self);
            let mut written = Vec::new();
            for (old_compression_frame_id, survivors) in &groups {
                let writes = survivors
                    .iter()
                    .map(|survivor| CompressionFrameWrite {
                        path: &survivor.path,
                        permissions: survivor.permissions,
                        total_len: survivor.total_len,
                        file_offset: survivor.file_offset,
                        data: &survivor.data,
                    })
                    .collect::<Vec<_>>();
                let indices = writer.write_compression_frame_bundle(&writes, &mut written)?;
                for (survivor, chunk_index) in survivors.iter().zip(indices) {
                    replacement_indices.push((
                        survivor.path.clone(),
                        *old_compression_frame_id,
                        chunk_index,
                    ));
                }
            }
            writer.finish(&mut written)?;
            replacements.extend(replacement_indices.into_iter().map(
                |(path, old_compression_frame_id, chunk_index)| {
                    (path, old_compression_frame_id, written[chunk_index].clone())
                },
            ));
        }

        let mut by_path: BTreeMap<LockboxPath, Vec<(u64, FileChunk)>> = BTreeMap::new();
        for (path, old_compression_frame_id, chunk) in replacements {
            by_path
                .entry(path)
                .or_default()
                .push((old_compression_frame_id, chunk));
        }
        let mut dirty = Vec::new();
        for (path, chunks) in by_path {
            if let Some(live) = self.toc_entries.get_mut(path.as_str()) {
                let replaced_compression_frames = chunks
                    .iter()
                    .map(|(old_compression_frame_id, _)| *old_compression_frame_id)
                    .collect::<BTreeSet<_>>();
                live.chunks.retain(|chunk| {
                    !replaced_compression_frames.contains(&chunk.compression_frame_id)
                });
                live.chunks
                    .extend(chunks.into_iter().map(|(_, chunk)| chunk));
                live.chunks.sort_by_key(|chunk| chunk.file_offset);
                if let Some(first) = live.chunks.first().and_then(|chunk| chunk.segments.first()) {
                    live.record_offset = first.page_offset;
                    live.record_len = first.page_len;
                    live.record_object_id = first.object_id;
                }
                dirty.push(live.path.clone());
            }
        }
        self.mark_toc_dirty_paths(dirty.iter());
        self.rebuild_record_ref_counts();
        Ok(())
    }

    pub(crate) fn validate_replace_intent(&self, path: &LockboxPath, replace: bool) -> Result<()> {
        super::mutation::validate_new_name(path.as_str())?;
        let exists = self.exists(path);
        match (replace, exists) {
            (false, true) => Err(Error::AlreadyExists(path.to_string())),
            (true, false) => Err(Error::NotFound(path.to_string())),
            _ => Ok(()),
        }
    }

    /// Open a seekable read handle over a file inside the lockbox.
    pub fn open_file(&self, path: &LockboxPath) -> Result<LockboxFileReader<'_, State>> {
        let path = path.as_file_path()?;
        let entry = self
            .toc_entries
            .get(path)
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .ok_or_else(|| Error::NotFound(path.to_string()))?;
        Ok(LockboxFileReader::new(self, entry.path.clone(), entry.len))
    }

    /// Add or replace a file from an in-memory byte slice.
    ///
    /// Missing parent directories are created with the default directory
    /// permissions when adding a new file.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if `path`
    /// already names an existing file or symlink. When `replace` is `true`,
    /// returns `Error::NotFound` if there is no existing entry to replace. Returns
    /// `Error::InvalidPath` for directory-only or unsafe lockbox paths and
    /// propagates storage or encoding errors from the write.
    pub fn add_file(&mut self, path: &LockboxPath, data: &[u8], replace: bool) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        self.add_file_with_permissions(path, data, DEFAULT_FILE_PERMISSIONS, replace)
    }

    /// Add or replace a file with explicit Unix-style permissions.
    ///
    /// Missing parent directories are created with the default directory
    /// permissions when adding a new file.
    ///
    /// `permissions` is a Unix mode value containing only the low permission
    /// bits, written in Rust as octal literals such as `0o600`, `0o640`, or
    /// `0o755`. File type bits, sticky/setuid/setgid bits, and platform ACLs
    /// are not supported.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if `path`
    /// already names an existing file or symlink. When `replace` is `true`,
    /// returns `Error::NotFound` if there is no existing entry to replace. Returns
    /// `Error::InvalidPath` for directory-only or unsafe lockbox paths,
    /// `Error::InvalidPath` for unsupported permission bits, and propagates
    /// storage or encoding errors from the write.
    pub fn add_file_with_permissions(
        &mut self,
        path: &LockboxPath,
        data: &[u8],
        permissions: u32,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        self.ensure_mirror_path_mutable(path)?;
        if data.len() <= SMALL_FILE_PACKING_LIMIT {
            return self.stage_small_file(path, data, permissions, replace);
        }
        if self.worker_jobs() > 1 {
            return self.add_file_from_reader_with_permissions(
                path,
                Cursor::new(data),
                permissions,
                replace,
            );
        }
        self.write_file_from_source_with_permissions(
            path,
            permissions,
            replace,
            |archive, path, permissions| {
                archive.write_file_data_from_slice(path, data, permissions)
            },
        )
    }

    /// Add or replace a file by streaming bytes from a reader.
    ///
    /// Missing parent directories are created with the default directory
    /// permissions when adding a new file.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if `path`
    /// already names an existing file or symlink. When `replace` is `true`,
    /// returns `Error::NotFound` if there is no existing entry to replace. Returns
    /// `Error::InvalidPath` for directory-only or unsafe lockbox paths and
    /// propagates reader, storage, or encoding errors from the write.
    pub fn add_file_from_reader(
        &mut self,
        path: &LockboxPath,
        reader: impl Read,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        self.add_file_from_reader_with_permissions(path, reader, DEFAULT_FILE_PERMISSIONS, replace)
    }

    /// Add or replace a file by reading from a host filesystem path.
    ///
    /// Missing parent directories are created with the default directory
    /// permissions when adding a new file.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if
    /// `destination` already names an existing file or symlink. When `replace`
    /// is `true`, returns `Error::NotFound` if there is no existing entry to replace.
    /// Returns `Error::InvalidPath` for directory-only or unsafe destination
    /// paths and `Error::Io` if the host file cannot be read.
    pub fn add_file_from_path(
        &mut self,
        source: &Path,
        destination: &LockboxPath,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        let file = open_host_file_nofollow(source)?;
        self.add_file_from_open_file(file, destination, replace)
    }

    /// Adds a host file through a caller-held regular-file handle. Directory
    /// traversals should open a child without following symlinks before calling.
    pub fn add_file_from_open_file(
        &mut self,
        mut file: std::fs::File,
        destination: &LockboxPath,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        let stat_start = Instant::now();
        let metadata = file.metadata().map_err(|err| Error::Io(err.to_string()))?;
        if !metadata.is_file() {
            return Err(Error::UnsupportedHostPath(
                "source handle is not a regular file".to_string(),
            ));
        }
        self.add_host_stat_nanos(stat_start.elapsed().as_nanos());
        if metadata.len() <= SMALL_FILE_PACKING_LIMIT as u64 {
            let read_start = Instant::now();
            let mut data = Vec::new();
            (&mut file)
                .take((SMALL_FILE_PACKING_LIMIT + 1) as u64)
                .read_to_end(&mut data)
                .map_err(|err| Error::Io(err.to_string()))?;
            if data.len() > SMALL_FILE_PACKING_LIMIT {
                return Err(Error::InvalidOperation(
                    "source file grew while it was imported".to_string(),
                ));
            }
            self.add_host_read_nanos(read_start.elapsed().as_nanos());
            return self.add_file(destination, &data, replace);
        }
        self.add_file_from_reader(destination, file, replace)
    }

    /// Add or replace a host file and require the exact bytes consumed by the
    /// import to match `expected_sha256`.
    ///
    /// This preserves bulk small-file packing while allowing callers that
    /// scanned a changing filesystem to prove that the imported bytes match
    /// their scan. A mismatch leaves the change uncommitted and returns an
    /// error.
    pub fn add_file_from_path_verified(
        &mut self,
        source: &Path,
        destination: &LockboxPath,
        replace: bool,
        expected_sha256: &[u8; 32],
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        struct HashingReader<R> {
            inner: R,
            hasher: Sha256,
        }
        impl<R: Read> Read for HashingReader<R> {
            fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
                let count = self.inner.read(buffer)?;
                self.hasher.update(&buffer[..count]);
                Ok(count)
            }
        }

        let mut file = open_host_file_nofollow(source)?;
        let metadata = file
            .metadata()
            .map_err(|err| Error::Io(format!("stat {}: {err}", source.display())))?;
        let actual: [u8; 32] = if metadata.len() <= SMALL_FILE_PACKING_LIMIT as u64 {
            let mut data = Vec::new();
            (&mut file)
                .take((SMALL_FILE_PACKING_LIMIT + 1) as u64)
                .read_to_end(&mut data)
                .map_err(|err| Error::Io(format!("read {}: {err}", source.display())))?;
            if data.len() > SMALL_FILE_PACKING_LIMIT {
                return Err(Error::InvalidOperation(
                    "source file grew while it was imported".to_string(),
                ));
            }
            let digest = Sha256::digest(&data).into();
            self.add_file(destination, &data, replace)?;
            digest
        } else {
            let mut reader = HashingReader {
                inner: file,
                hasher: Sha256::new(),
            };
            self.add_file_from_reader(destination, &mut reader, replace)?;
            reader.hasher.finalize().into()
        };
        if &actual != expected_sha256 {
            return Err(Error::InvalidOperation(format!(
                "source file changed while it was imported: {}",
                source.display()
            )));
        }
        Ok(())
    }

    /// Add or replace a streamed file with explicit Unix-style permissions.
    ///
    /// Missing parent directories are created with the default directory
    /// permissions when adding a new file.
    ///
    /// `permissions` is a Unix mode value containing only the low permission
    /// bits, written in Rust as octal literals such as `0o600`, `0o640`, or
    /// `0o755`. File type bits, sticky/setuid/setgid bits, and platform ACLs
    /// are not supported.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if `path`
    /// already names an existing file or symlink. When `replace` is `true`,
    /// returns `Error::NotFound` if there is no existing entry to replace. Returns
    /// `Error::InvalidPath` for directory-only or unsafe lockbox paths,
    /// `Error::InvalidPath` for unsupported permission bits, and propagates
    /// reader, storage, or encoding errors from the write.
    pub fn add_file_from_reader_with_permissions(
        &mut self,
        path: &LockboxPath,
        reader: impl Read,
        permissions: u32,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        self.ensure_mirror_path_mutable(path)?;
        self.write_file_from_reader_with_permissions(path, reader, permissions, replace)
    }

    fn write_file_from_reader_with_permissions(
        &mut self,
        path: &LockboxPath,
        reader: impl Read,
        permissions: u32,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        self.write_file_from_source_with_permissions(
            path,
            permissions,
            replace,
            |archive, path, permissions| {
                let jobs = archive.worker_jobs();
                if jobs > 1 {
                    archive.write_file_data_parallel(path, reader, permissions, jobs)
                } else {
                    archive.write_file_data_sequential(path, reader, permissions)
                }
            },
        )
    }

    fn write_file_from_source_with_permissions(
        &mut self,
        path: &LockboxPath,
        permissions: u32,
        replace: bool,
        write_data: impl FnOnce(&mut Self, &LockboxPath, u32) -> Result<(u64, Vec<FileChunk>)>,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        let path = path.file_path()?;
        let permissions = validate_permissions(permissions)?;
        self.validate_replace_intent(&path, replace)?;
        self.create_parent_dirs_for(&path)?;
        if self.should_discard_file_pages_after_flush()
            && self.pending_small_files.contains_key(path.as_str())
        {
            self.flush_bulk_small_file_packer()?;
        }
        self.remove_pending_small_file(&path);
        if let Some(old) = self.toc_entries.get(path.as_str()).cloned() {
            self.free_entry_slots(old)?;
        }

        let (file_offset, chunks) = write_data(self, &path, permissions)?;

        let entry = TocEntry {
            path: path.clone(),
            len: file_offset,
            record_offset: chunks
                .first()
                .and_then(|chunk| chunk.segments.first())
                .map(|segment| segment.page_offset)
                .unwrap_or(0),
            record_len: chunks
                .first()
                .and_then(|chunk| chunk.segments.first())
                .map(|segment| segment.page_len)
                .unwrap_or(0),
            record_object_id: chunks
                .first()
                .and_then(|chunk| chunk.segments.first())
                .map(|segment| segment.object_id)
                .unwrap_or(0),
            record_digest: [0; 32],
            deleted: false,
            node_kind: NodeKind::File,
            permissions,
            chunks,
        };
        self.add_entry_record_refs(&entry);
        self.toc_entries.insert(path.clone(), entry);
        self.mark_toc_dirty(&path);
        self.needs_packing = true;
        Ok(())
    }

    fn write_file_data_from_slice(
        &mut self,
        path: &LockboxPath,
        data: &[u8],
        permissions: u32,
    ) -> Result<(u64, Vec<FileChunk>)> {
        // Only large in-memory inputs reach this path. Borrow each frame from
        // the caller instead of copying it through the streaming read buffer.
        debug_assert!(data.len() > SMALL_FILE_PACKING_LIMIT);
        let mut writer = FilePageWriter::new(self);
        let pipeline = writer.import_pipeline(1);
        pipeline.with_encoder(
            pipeline.encoder_frame(&data[..data.len().min(FILE_COMPRESSION_FRAME_BYTES)]),
            |encode| {
                let mut chunks = Vec::new();
                let mut file_offset = 0u64;
                for frame in data.chunks(FILE_COMPRESSION_FRAME_BYTES) {
                    let prepared = pipeline.prepare_with_encoder(
                        &[CompressionFrameWrite {
                            path,
                            permissions,
                            total_len: 0,
                            file_offset,
                            data: frame,
                        }],
                        encode,
                    );
                    writer.write_prepared_compression_frame(prepared, &mut chunks)?;
                    file_offset += frame.len() as u64;
                }
                writer.finish(&mut chunks)?;
                Ok((file_offset, chunks))
            },
        )
    }

    fn write_file_data_sequential(
        &mut self,
        path: &LockboxPath,
        mut reader: impl Read,
        permissions: u32,
    ) -> Result<(u64, Vec<FileChunk>)> {
        let mut writer = FilePageWriter::new(self);
        let pipeline = writer.import_pipeline(1);
        let mut buffer =
            crate::page_buffer::ZeroizingBytes::new(vec![0; FILE_COMPRESSION_FRAME_BYTES]);
        let started = Instant::now();
        let mut read = read_next_chunk(&mut reader, &mut buffer)?;
        writer
            .lockbox
            .add_host_read_nanos(started.elapsed().as_nanos());
        // The encoder retains only input properties, so this buffer can be
        // refilled without copying or retaining a borrow of the first frame.
        let first = pipeline.encoder_frame(&buffer[..read]);
        pipeline.with_encoder(first, |encode| {
            let mut chunks = Vec::new();
            let mut file_offset = 0u64;
            loop {
                let prepared = pipeline.prepare_with_encoder(
                    &[CompressionFrameWrite {
                        path,
                        permissions,
                        total_len: 0,
                        file_offset,
                        data: &buffer[..read],
                    }],
                    encode,
                );
                writer.write_prepared_compression_frame(prepared, &mut chunks)?;
                file_offset += read as u64;
                if read == 0 {
                    break;
                }
                let started = Instant::now();
                read = read_next_chunk(&mut reader, &mut buffer)?;
                writer
                    .lockbox
                    .add_host_read_nanos(started.elapsed().as_nanos());
                if read == 0 {
                    break;
                }
            }
            writer.finish(&mut chunks)?;
            Ok((file_offset, chunks))
        })
    }

    fn write_file_data_parallel(
        &mut self,
        path: &LockboxPath,
        mut reader: impl Read,
        permissions: u32,
        jobs: usize,
    ) -> Result<(u64, Vec<FileChunk>)> {
        let jobs = jobs.max(1);
        let level = self.compression_frame_zstd_level();
        let pipeline = FileImportPipeline::new(level, jobs)
            .with_sensitive(!self.format_mode.plaintext())
            .with_compression(self.configured_compression())
            .with_native_blocks(cfg!(feature = "native-block-layout") && self.format_mode.0 != 0);
        let queue_bound = jobs.saturating_mul(2).max(1);
        let (job_tx, job_rx) = std::sync::mpsc::sync_channel::<ParallelCompressionJob>(queue_bound);
        let (result_tx, result_rx) = std::sync::mpsc::channel::<ParallelCompressionResult>();
        let job_rx = Arc::new(Mutex::new(job_rx));

        std::thread::scope(|scope| -> Result<(u64, Vec<FileChunk>)> {
            for _ in 0..jobs {
                let job_rx = Arc::clone(&job_rx);
                let result_tx = result_tx.clone();
                scope.spawn(move || {
                    let first_job = match job_rx.lock() {
                        Ok(rx) => rx.recv(),
                        Err(_) => return,
                    };
                    let Ok(mut job) = first_job else {
                        return;
                    };
                    // Keep one scoped encoder per worker. Its existing lease
                    // wipes backing buffers on normal exit and unwinding.
                    pipeline.with_encoder(pipeline.encoder_frame(&job.data), |encode| loop {
                        let result = pipeline.prepare_parallel_job_with_encoder(job, encode);
                        if result_tx.send(result).is_err() {
                            return;
                        }
                        let next_job = match job_rx.lock() {
                            Ok(rx) => rx.recv(),
                            Err(_) => return,
                        };
                        match next_job {
                            Ok(next) => job = next,
                            Err(_) => return,
                        }
                    });
                });
            }
            drop(result_tx);

            let mut writer = FilePageWriter::new(self);
            let mut chunks = Vec::new();
            let mut frame_order = ParallelFrameOrder::new();
            let mut file_offset = 0u64;
            let mut job_count = 0usize;
            let mut buffer = vec![0; FILE_COMPRESSION_FRAME_BYTES];
            loop {
                let read_start = Instant::now();
                let read = read_next_chunk(&mut reader, &mut buffer)?;
                writer
                    .lockbox
                    .add_host_read_nanos(read_start.elapsed().as_nanos());
                if read == 0 {
                    if file_offset == 0 {
                        job_tx
                            .send(ParallelCompressionJob {
                                index: job_count,
                                path: path.clone(),
                                permissions,
                                total_len: 0,
                                file_offset: 0,
                                data: Vec::new(),
                            })
                            .map_err(|_| {
                                Error::Io("compression worker stopped unexpectedly".to_string())
                            })?;
                        job_count += 1;
                        frame_order.drain_ready(&result_rx, &mut writer, &mut chunks)?;
                    }
                    break;
                }

                job_tx
                    .send(ParallelCompressionJob {
                        index: job_count,
                        path: path.clone(),
                        permissions,
                        total_len: 0,
                        file_offset,
                        data: buffer[..read].to_vec(),
                    })
                    .map_err(|_| {
                        Error::Io("compression worker stopped unexpectedly".to_string())
                    })?;
                file_offset += read as u64;
                job_count += 1;
                frame_order.drain_ready(&result_rx, &mut writer, &mut chunks)?;
            }
            drop(job_tx);

            while frame_order.received_count < job_count {
                let result = result_rx.recv().map_err(|_| {
                    Error::Io("compression worker stopped unexpectedly".to_string())
                })?;
                frame_order.accept(result, &mut writer, &mut chunks)?;
            }
            writer.finish(&mut chunks)?;
            Ok((file_offset, chunks))
        })
    }

    /// Return the complete contents of a file.
    ///
    /// Returns `Error::InvalidPath` for directory-only paths, `Error::NotFound`
    /// if `path` is absent or not a file, `Error::CorruptRecord` if stored file
    /// metadata is inconsistent, and `Error::Io` if an internal write into the
    /// output buffer fails. Returns `Error::SecurityLimitExceeded` if the
    /// multi-frame or sparse output reservation cannot be satisfied.
    pub fn get_file(&self, path: &LockboxPath) -> Result<Vec<u8>> {
        let path_key = path.as_file_path()?;
        let entry = self
            .toc_entries
            .get(path_key)
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .ok_or_else(|| Error::NotFound(path_key.to_string()))?;
        if let Some(pending) = self.pending_small_files.get(path_key) {
            return Ok(pending.data.to_vec());
        }
        // The decoder already owns the complete output for a single covering
        // chunk. Return it directly instead of cloning/sorting the chunk list
        // and copying the decoded bytes through another Vec writer.
        if let [chunk] = entry.chunks.as_slice() {
            if chunk.file_offset == 0 && chunk.len == entry.len {
                let mut decoded =
                    ZeroizingBytes::new(self.read_file_chunk_compression_frame(entry.len, chunk)?);
                if decoded.len() as u64 != entry.len {
                    return Err(Error::CorruptRecord);
                }
                return Ok(std::mem::take(&mut *decoded));
            }
        }
        let sensitive = !self.format_mode.plaintext();
        let mut out = SensitiveBytes::new(Vec::new(), sensitive);
        // Sensitive output must not grow after plaintext has been copied:
        // ordinary Vec growth would free an unwiped previous allocation.
        // Clear compressed output retains the existing allocation order.
        if sensitive
            || entry
                .chunks
                .iter()
                .all(|chunk| chunk.compression == COMPRESSION_NONE)
        {
            let capacity = usize::try_from(entry.len).map_err(|_| {
                Error::SecurityLimitExceeded("file contents exceed addressable memory".to_string())
            })?;
            out.try_reserve_exact(capacity).map_err(|_| {
                Error::SecurityLimitExceeded("cannot allocate complete file contents".to_string())
            })?;
        }
        self.extract_file_to_writer(path, &mut *out)?;
        Ok(out.into_vec())
    }

    /// Extract a file's contents to a writer.
    ///
    /// Returns `Error::InvalidPath` for directory-only paths, `Error::NotFound`
    /// if `path` is absent or not a file, `Error::CorruptRecord` if stored file
    /// metadata is inconsistent, and `Error::Io` if the writer fails.
    pub fn extract_file_to_writer(&self, path: &LockboxPath, mut writer: impl Write) -> Result<()> {
        let path = path.as_file_path()?;
        let entry = self
            .toc_entries
            .get(path)
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .ok_or_else(|| Error::NotFound(path.to_string()))?;

        if let Some(pending) = self.pending_small_files.get(path) {
            writer
                .write_all(&pending.data)
                .map_err(|err| Error::Io(err.to_string()))?;
            return Ok(());
        }

        if entry.chunks.is_empty() {
            write_zeroes(&mut writer, entry.len)?;
            return Ok(());
        }

        let mut chunks = entry.chunks.clone();
        chunks.sort_by_key(|chunk| chunk.file_offset);
        let mut written = 0u64;
        for chunk in chunks {
            if chunk.file_offset < written || chunk.file_offset > entry.len {
                return Err(Error::CorruptRecord);
            }
            if chunk.file_offset > written {
                write_zeroes(&mut writer, chunk.file_offset - written)?;
                written = chunk.file_offset;
            }
            if chunk.file_offset.saturating_add(chunk.len) > entry.len {
                return Err(Error::CorruptRecord);
            }
            #[cfg(any(test, feature = "native-block-layout"))]
            let decoded_chunk = if chunk.block_frame.is_some() {
                self.read_native_block_chunk_view(entry.len, &chunk, 0..chunk.len, true)?
            } else {
                NativeReadBytes::Owned(self.read_file_chunk_compression_frame(entry.len, &chunk)?)
            }
            .for_internal_write(!self.format_mode.plaintext());
            #[cfg(not(any(test, feature = "native-block-layout")))]
            let decoded_chunk = SensitiveBytes::new(
                self.read_file_chunk_compression_frame(entry.len, &chunk)?,
                !self.format_mode.plaintext(),
            );
            #[cfg(any(test, feature = "native-block-layout"))]
            decoded_chunk.ensure_current(&self.storage)?;
            writer
                .write_all(&decoded_chunk)
                .map_err(|err| Error::Io(err.to_string()))?;
            written = written.saturating_add(decoded_chunk.len() as u64);
            if written > entry.len {
                return Err(Error::CorruptRecord);
            }
        }
        if written < entry.len {
            write_zeroes(&mut writer, entry.len - written)?;
        } else if written != entry.len {
            return Err(Error::CorruptRecord);
        }
        Ok(())
    }

    /// Extract a file's contents to a host filesystem path.
    ///
    /// When `replace` is `false`, returns `Error::AlreadyExists` if the
    /// destination path already exists. When `replace` is `true`, returns
    /// `Error::NotFound` if the destination path does not already exist.
    /// Returns `Error::Io` if the destination file cannot be created. Returns
    /// the same errors as `extract_file_to_writer` for lockbox read failures.
    pub fn extract_file_to(
        &self,
        source: &LockboxPath,
        destination: &Path,
        replace: bool,
    ) -> Result<()> {
        self.extract_file_to_staged(source, destination, replace, replace, None)
    }

    /// Extract one file with limits and permission restoration applied before
    /// atomic publication. A failed read leaves any existing destination intact.
    pub fn extract_file_to_with_policy(
        &self,
        source: &LockboxPath,
        destination: &Path,
        policy: &crate::ExtractPolicy,
    ) -> Result<()> {
        let path = source.as_file_path()?;
        let entry = self
            .toc_entries
            .get(path)
            .filter(|entry| !entry.deleted && entry.node_kind == crate::node_kind::NodeKind::File)
            .ok_or_else(|| Error::NotFound(source.to_string()))?;
        if policy.max_files == 0
            || entry.len > policy.max_file_bytes
            || entry.len > policy.max_total_bytes
        {
            return Err(Error::SecurityLimitExceeded(
                "file exceeds extraction limits".into(),
            ));
        }
        self.extract_file_to_staged(
            source,
            destination,
            policy.overwrite,
            false,
            policy.restore_permissions.then_some(entry.permissions),
        )
    }

    fn extract_file_to_staged(
        &self,
        source: &LockboxPath,
        destination: &Path,
        overwrite: bool,
        require_existing: bool,
        permissions: Option<u32>,
    ) -> Result<()> {
        let map_error = |error: std::io::Error| match error.kind() {
            std::io::ErrorKind::AlreadyExists => {
                Error::AlreadyExists(destination.display().to_string())
            }
            std::io::ErrorKind::NotFound => Error::NotFound(destination.display().to_string()),
            _ => Error::Io(error.to_string()),
        };
        let mut staged = super::secure_output::StagedFile::at(destination, require_existing)
            .map_err(map_error)?;
        self.extract_file_to_writer(source, staged.writer())?;
        staged.publish(overwrite, permissions).map_err(map_error)
    }

    /// Return stored Unix-style permissions for a file or symlink.
    ///
    /// The returned value uses the low Unix permission bits only, for example
    /// `0o600`, `0o640`, or `0o755`.
    pub fn permissions(&self, path: &LockboxPath) -> Option<u32> {
        let path = path.as_file_path().ok()?;
        self.toc_entries
            .get(path)
            .filter(|entry| !entry.deleted)
            .map(|entry| entry.permissions)
    }

    /// Read a bounded byte range from a file.
    ///
    /// Returns `Error::InvalidPath` for directory-only paths, `Error::NotFound`
    /// if `path` is absent or not a file, and `Error::CorruptRecord` if stored
    /// file metadata is inconsistent. A range outside the file returns an empty
    /// vector rather than an error.
    pub fn read_file_range(&self, path: &LockboxPath, offset: u64, len: u64) -> Result<Vec<u8>> {
        let path = path.as_file_path()?;
        let entry = self
            .toc_entries
            .get(path)
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .ok_or_else(|| Error::NotFound(path.to_string()))?;
        if len == 0 || offset >= entry.len {
            return Ok(Vec::new());
        }
        let wanted_end = offset.saturating_add(len).min(entry.len);

        if let Some(pending) = self.pending_small_files.get(path) {
            let start = offset.min(pending.data.len() as u64) as usize;
            let end = wanted_end.min(pending.data.len() as u64) as usize;
            return Ok(pending.data[start..end].to_vec());
        }

        let capacity = usize::try_from(wanted_end - offset).map_err(|_| {
            Error::SecurityLimitExceeded("requested range exceeds addressable memory".to_string())
        })?;
        // Exact chunk reads transfer their decoded allocation below. Do not
        // allocate a second, unused output buffer before knowing it is needed.
        let mut out = Vec::new();
        let mut chunks = entry.chunks.clone();
        chunks.sort_by_key(|chunk| chunk.file_offset);
        let mut cursor = offset;
        for chunk in chunks {
            let chunk_start = chunk.file_offset;
            let chunk_end = chunk.file_offset.saturating_add(chunk.len);
            if chunk_start > chunk_end || chunk_end > entry.len {
                return Err(Error::CorruptRecord);
            }
            if chunk_end <= offset || chunk_start >= wanted_end {
                continue;
            }
            if chunk_start > cursor {
                let zeroes = chunk_start.min(wanted_end) - cursor;
                if out.capacity() == 0 {
                    out.reserve(capacity);
                }
                out.resize(out.len() + zeroes as usize, 0);
                cursor = chunk_start.min(wanted_end);
            }

            let copy_start = cursor.max(chunk_start) - chunk_start;
            let copy_end = wanted_end.min(chunk_end) - chunk_start;
            let mut decoded_chunk = ZeroizingBytes::new(self.read_file_chunk_range(
                entry.len,
                &chunk,
                copy_start..copy_end,
            )?);
            // An aligned frame read already owns exactly the requested bytes.
            // Transfer it to the caller instead of making another full copy.
            if out.is_empty() && chunk_start == offset && chunk_end == wanted_end {
                return Ok(std::mem::take(&mut *decoded_chunk));
            }
            if out.capacity() == 0 {
                out.reserve(capacity);
            }
            out.extend_from_slice(&decoded_chunk);
            cursor = chunk_start + copy_end;
            if cursor >= wanted_end {
                break;
            }
        }
        if cursor < wanted_end {
            if out.capacity() == 0 {
                out.reserve(capacity);
            }
            out.resize(out.len() + (wanted_end - cursor) as usize, 0);
        }
        Ok(out)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    pub(super) fn read_native_file_window(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
    ) -> Result<NativeReadBytes> {
        // Preserve the format policy checked by read_file_chunk_range.
        if self.format_mode.0 != 0
            && self.format_mode.options().compression == crate::Compression::None
            && chunk.compression != COMPRESSION_NONE
        {
            return Err(Error::CorruptRecord);
        }
        self.read_native_block_chunk_view(expected_total_len, chunk, 0..chunk.len, true)
    }

    pub(crate) fn read_file_chunk_compression_frame(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
    ) -> Result<Vec<u8>> {
        self.read_file_chunk_range(expected_total_len, chunk, 0..chunk.len)
    }

    /// Authenticate precisely the retained objects that relocation will copy.
    /// Other frame segments are streamed; the retained page is never reread.
    pub(super) fn verify_frame_for_relocation(
        &self,
        total_len: u64,
        chunk: &FileChunk,
        retained_offset: u64,
        retained: &crate::page::DecodedPage,
    ) -> Result<()> {
        #[cfg(any(test, feature = "native-block-layout"))]
        if chunk.block_frame.is_some() {
            return Err(Error::CorruptRecord);
        }
        validate_compression_frame_lengths(chunk.compression_frame_len, chunk.compressed_len)?;
        if chunk.compressed_len > DEFAULT_MAX_PAGE_LOGICAL_BYTES as u64 {
            return Err(Error::SecurityLimitExceeded(
                "compressed frame exceeds relocation limit".into(),
            ));
        }
        let mut hash = crate::crypto::strong_checksum_hasher(chunk.compressed_len);
        let mut position = 0u64;
        for segment in &chunk.segments {
            if segment.segment_offset != position {
                return Err(Error::CorruptRecord);
            }
            let mut verify = |object: &PageObject| -> Result<()> {
                if object.kind != PageObjectKind::FileData {
                    return Err(Error::CorruptRecord);
                }
                object.with_payload(|payload| {
                    let decoded = decode_compression_frame_segment_payload_view(payload)?;
                    validate_frame_segment(&decoded, chunk, segment, total_len)?;
                    hash.update(decoded.data);
                    Ok(())
                })?
            };
            if segment.page_offset == retained_offset {
                let mut objects = retained
                    .objects
                    .iter()
                    .filter(|object| object.id == segment.object_id);
                let object = objects.next().ok_or(Error::CorruptRecord)?;
                if objects.next().is_some() {
                    return Err(Error::CorruptRecord);
                }
                verify(object)?;
            } else {
                self.with_page_object(segment.page_offset, segment.object_id, verify)?;
            }
            position = position
                .checked_add(segment.segment_len)
                .ok_or(Error::CorruptRecord)?;
        }
        let digest: [u8; 32] = hash.finalize().into();
        if position != chunk.compressed_len || digest != chunk.compression_frame_digest {
            return Err(Error::CorruptRecord);
        }
        Ok(())
    }

    pub(super) fn verified_raw_file_range(
        &self,
        path: &LockboxPath,
        offset: u64,
        len: u64,
    ) -> Result<Option<VerifiedFileRange>> {
        let path = path.as_file_path()?;
        if self.pending_small_files.contains_key(path) {
            return Ok(None);
        }
        let entry = self.toc_entries.get(path).ok_or(Error::CorruptRecord)?;
        let wanted_end = offset.checked_add(len).ok_or(Error::CorruptRecord)?;
        let Some(chunk) = entry.chunks.iter().find(|chunk| {
            chunk.file_offset <= offset
                && chunk
                    .file_offset
                    .checked_add(chunk.len)
                    .is_some_and(|end| end >= wanted_end)
        }) else {
            return Ok(None);
        };
        #[cfg(any(test, feature = "native-block-layout"))]
        if chunk.block_frame.is_some() {
            // This shortcut authenticates a whole-frame hash, not a block index.
            return Ok(None);
        }
        if chunk.compression != COMPRESSION_NONE || chunk.segments.len() != 1 {
            return Ok(None);
        }
        let segment = &chunk.segments[0];
        if segment.segment_offset != 0 || segment.segment_len != chunk.compressed_len {
            return Ok(None);
        }
        validate_compression_frame_lengths(chunk.compression_frame_len, chunk.compressed_len)?;
        if chunk.compressed_len != chunk.compression_frame_len
            || chunk
                .file_offset
                .checked_add(chunk.len)
                .is_none_or(|end| end > entry.len)
        {
            return Err(Error::CorruptRecord);
        }
        let page = self.read_shared_page(segment.page_offset)?;
        let object_index = page
            .objects
            .iter()
            .position(|object| object.id == segment.object_id)
            .ok_or(Error::CorruptRecord)?;
        let range = page.objects[object_index].with_payload(|payload| {
            let decoded = decode_compression_frame_segment_payload_view(payload)?;
            validate_frame_segment(&decoded, chunk, segment, entry.len)?;
            if strong_checksum(decoded.data) != chunk.compression_frame_digest {
                return Err(Error::CorruptRecord);
            }
            let chunk_end = chunk
                .compression_frame_offset
                .checked_add(chunk.len)
                .ok_or(Error::CorruptRecord)?;
            if chunk_end > decoded.data.len() as u64 {
                return Err(Error::CorruptRecord);
            }
            // Segment data is the final slice of its object payload.
            let data_start = payload.len() - decoded.data.len();
            let start = data_start
                + usize::try_from(chunk.compression_frame_offset + (offset - chunk.file_offset))
                    .map_err(|_| Error::CorruptRecord)?;
            let end = start
                .checked_add(usize::try_from(len).map_err(|_| Error::CorruptRecord)?)
                .ok_or(Error::CorruptRecord)?;
            if end > payload.len() {
                return Err(Error::CorruptRecord);
            }
            Ok(start..end)
        })??;
        Ok(Some(VerifiedFileRange {
            page,
            object_index,
            range,
        }))
    }

    fn read_file_chunk_range(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: std::ops::Range<u64>,
    ) -> Result<Vec<u8>> {
        if range.start > range.end || range.end > chunk.len {
            return Err(Error::CorruptRecord);
        }
        if self.format_mode.0 != 0
            && self.format_mode.options().compression == crate::Compression::None
            && chunk.compression != COMPRESSION_NONE
        {
            return Err(Error::CorruptRecord);
        }
        #[cfg(any(test, feature = "native-block-layout"))]
        if chunk.block_frame.is_some() {
            return self.read_native_block_chunk(expected_total_len, chunk, range);
        }
        if let Some(cached) =
            self.read_cached_compression_frame_slice(expected_total_len, chunk, &range)?
        {
            return Ok(cached);
        }
        validate_compression_frame_lengths(chunk.compression_frame_len, chunk.compressed_len)?;
        if chunk.compressed_len > DEFAULT_MAX_PAGE_LOGICAL_BYTES as u64 {
            return Err(Error::SecurityLimitExceeded(
                "compressed compression-frame exceeds safety limit".to_string(),
            ));
        }
        let compressed_len =
            usize::try_from(chunk.compressed_len).map_err(|_| Error::CorruptRecord)?;
        // Most frames occupy a single page object. Borrow its already checked
        // payload instead of assembling and later wiping another frame-sized buffer.
        if let [segment] = chunk.segments.as_slice() {
            if segment.segment_offset == 0 && segment.segment_len == chunk.compressed_len {
                return self.with_page_object(segment.page_offset, segment.object_id, |object| {
                    object.with_payload(|payload| {
                        let decoded = decode_compression_frame_segment_payload_view(payload)?;
                        validate_frame_segment(&decoded, chunk, segment, expected_total_len)?;
                        self.read_checked_frame_slice(
                            chunk,
                            &range,
                            decoded.data,
                            decoded
                                .manifest
                                .map(|manifest| manifest.slices)
                                .unwrap_or_default(),
                        )
                    })?
                });
            }
        }
        let mut stored = ZeroizingBytes::new(vec![0u8; compressed_len]);
        let mut cache_slices = None;
        for segment in &chunk.segments {
            self.with_page_object(segment.page_offset, segment.object_id, |object| {
                object.with_payload(|payload| {
                    let decoded = decode_compression_frame_segment_payload_view(payload)?;
                    if let Some(manifest) = decoded.manifest.as_ref() {
                        if cache_slices.is_none() {
                            cache_slices = Some(manifest.slices.clone());
                        }
                    }
                    validate_frame_segment(&decoded, chunk, segment, expected_total_len)?;
                    let start = usize::try_from(segment.segment_offset)
                        .map_err(|_| Error::CorruptRecord)?;
                    let end = start
                        .checked_add(decoded.data.len())
                        .ok_or(Error::CorruptRecord)?;
                    if end > stored.len() {
                        return Err(Error::CorruptRecord);
                    }
                    stored[start..end].copy_from_slice(decoded.data);
                    Ok(())
                })?
            })?;
        }
        self.read_checked_frame_slice(chunk, &range, &stored, cache_slices.unwrap_or_default())
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn read_native_block_chunk(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: std::ops::Range<u64>,
    ) -> Result<Vec<u8>> {
        self.read_native_block_chunk_with_cache(expected_total_len, chunk, range, true)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn read_native_block_chunk_with_cache(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: std::ops::Range<u64>,
        cache_single_frames: bool,
    ) -> Result<Vec<u8>> {
        self.read_native_block_chunk_view(expected_total_len, chunk, range, cache_single_frames)?
            .into_vec(&self.storage)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn read_native_block_chunk_view(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: std::ops::Range<u64>,
        cache_single_frames: bool,
    ) -> Result<NativeReadBytes> {
        // A decoded frame was admitted only after verifying its complete body.
        // Reuse that proof only for the exact committed reference and allocation.
        crate::file_format::indexed_frame::block_page::validate_chunk_reference(
            self.lockbox_id,
            self.format_mode,
            expected_total_len,
            chunk,
        )?;
        let [segment] = chunk.segments.as_slice() else {
            return Err(Error::CorruptRecord);
        };
        let required_end = segment
            .page_offset
            .checked_add(segment.page_len)
            .ok_or(Error::CorruptRecord)?;
        let revision = self.storage.write_revision();
        if let Some(cached) = self.native_cached_frame(chunk)? {
            // Consumers validate before exposing cached bytes: into_vec after
            // copying, extraction before the writer, and native file handles
            // through their retained extent/revision before every window copy.
            let reference = chunk.block_frame.as_ref().ok_or(Error::CorruptRecord)?;
            if cached
                .native_reference
                .as_ref()
                .is_none_or(|(verified, allocation)| {
                    verified != reference.as_ref() || allocation != segment
                })
            {
                return Err(Error::CorruptRecord);
            }
            let bounds = Self::cached_frame_bounds(&cached, expected_total_len, chunk, &range)?;
            return Ok(NativeReadBytes::Shared {
                frame: cached,
                range: bounds,
                source_guard: Some((required_end, revision)),
            });
        }
        // Whole small frames can be captured in one bounded source read. Keep
        // the same metadata/index/body validators and revalidate the live source
        // before returning bytes; partial ranges never take this eager path.
        const SMALL_FRAME_SNAPSHOT_BYTES: u64 = 16 * 1024;
        if !matches!(&self.storage, crate::storage::StorageBackend::Memory(_))
            && range.start == 0
            && range.end == chunk.len
            && chunk.compression_frame_offset == 0
            && chunk.len == chunk.compression_frame_len
            && chunk.compression_frame_len <= SMALL_FRAME_SNAPSHOT_BYTES
            && segment.page_len <= SMALL_FRAME_SNAPSHOT_BYTES
        {
            use crate::file_format::indexed_frame::block_page::{validate_chunk_reference, Reader};
            use crate::storage::{Storage, StorageBackend};
            // The bounded exact read detects truncation. Validate live source
            // identity/extent and revision after decoding, before exposing bytes.
            let mut page = ZeroizingBytes::new(vec![0; segment.page_len as usize]);
            self.storage.read_at_into(segment.page_offset, &mut page)?;
            let identity = validate_chunk_reference(
                self.lockbox_id,
                self.format_mode,
                expected_total_len,
                chunk,
            )?;
            let reference = chunk.block_frame.as_ref().ok_or(Error::CorruptRecord)?;
            let (mut decoded, slices) = StorageBackend::with_read_snapshot(page, |snapshot| {
                let read = |key: &[u8]| {
                    let reader = Reader::open(
                        snapshot,
                        0,
                        identity,
                        &reference.descriptor,
                        segment.page_len as usize,
                        key,
                    )?;
                    reader.validate_slice(chunk, expected_total_len)?;
                    Ok((
                        ZeroizingBytes::new(reader.read(0..chunk.len)?),
                        reader.slices().to_vec(),
                    ))
                };
                if self.format_mode.plaintext() {
                    read(&[0; 32])
                } else {
                    self.key.with_bytes(read)?
                }
            })?;
            if required_end > self.storage.current_len()? {
                return Err(Error::Truncated);
            }
            if revision == u64::MAX || revision != self.storage.write_revision() {
                return Err(Error::CorruptRecord);
            }
            if cache_single_frames && self.should_cache_native_decoded_frame(decoded.len()) {
                let len = decoded.len();
                let frame = self
                    .cache_decoded_compression_frame_at_revision(
                        chunk,
                        slices,
                        std::mem::take(&mut *decoded),
                        revision,
                    )
                    .ok_or(Error::CorruptRecord)?;
                return Ok(NativeReadBytes::Shared {
                    frame,
                    range: 0..len,
                    source_guard: None,
                });
            }
            return Ok(NativeReadBytes::Owned(std::mem::take(&mut *decoded)));
        }
        let reader = self.open_native_block_chunk(expected_total_len, chunk)?;
        let start = chunk
            .compression_frame_offset
            .checked_add(range.start)
            .ok_or(Error::CorruptRecord)?;
        let end = chunk
            .compression_frame_offset
            .checked_add(range.end)
            .ok_or(Error::CorruptRecord)?;
        let frame_len =
            usize::try_from(chunk.compression_frame_len).map_err(|_| Error::CorruptRecord)?;
        // Cache complete file slices (including packed neighbors), but do not
        // expand a partial raw range just to populate the cache. Compressed
        // reads already decode the complete frame.
        if self.should_cache_native_decoded_frame(frame_len)
            && (cache_single_frames || reader.slices().len() > 1)
            && (chunk.compression != COMPRESSION_NONE
                || (range.start == 0 && range.end == chunk.len))
        {
            let mut decoded = ZeroizingBytes::new(reader.read(0..chunk.compression_frame_len)?);
            let start = usize::try_from(start).map_err(|_| Error::CorruptRecord)?;
            let end = usize::try_from(end).map_err(|_| Error::CorruptRecord)?;
            decoded.get(start..end).ok_or(Error::CorruptRecord)?;
            let frame = self
                .cache_decoded_compression_frame_at_revision(
                    chunk,
                    reader.slices().to_vec(),
                    std::mem::take(&mut *decoded),
                    reader.write_revision(),
                )
                .ok_or(Error::CorruptRecord)?;
            return Ok(NativeReadBytes::Shared {
                frame,
                range: start..end,
                source_guard: None,
            });
        }
        reader
            .read_with_cache(start..end, &self.page_manager)
            .map(NativeReadBytes::Owned)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    pub(super) fn open_native_block_chunk(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
    ) -> Result<crate::file_format::indexed_frame::block_page::Reader<'_>> {
        use crate::file_format::indexed_frame::block_page::{validate_chunk_reference, Reader};
        let identity =
            validate_chunk_reference(self.lockbox_id, self.format_mode, expected_total_len, chunk)?;
        let reference = chunk.block_frame.as_ref().ok_or(Error::CorruptRecord)?;
        let descriptor = &reference.descriptor;
        let [segment] = chunk.segments.as_slice() else {
            return Err(Error::CorruptRecord);
        };
        let page_len = usize::try_from(segment.page_len).map_err(|_| Error::CorruptRecord)?;
        let cached = self
            .page_manager
            .borrow_mut()
            .native_index(segment.page_offset, self.storage.write_revision());
        let open = |key: &[u8]| {
            if let Some(cached) = &cached {
                return cached.bind(&self.storage, chunk, expected_total_len, key);
            }
            let reader = Reader::open(
                &self.storage,
                segment.page_offset,
                identity,
                descriptor,
                page_len,
                key,
            )?;
            reader.validate_slice(chunk, expected_total_len)?;
            self.page_manager.borrow_mut().insert_native_index(
                segment.page_offset,
                segment.page_len,
                reader.cache_entry(chunk)?,
                reader.write_revision(),
            );
            Ok(reader)
        };
        if self.format_mode.plaintext() {
            // Plaintext metadata and block indexes are checked against their
            // committed hashes, not a content key. Owner authorization still
            // belongs to signed archive opening. Avoid exposing protected key
            // memory for an operation that cannot use it.
            open(&[0; 32])
        } else {
            self.key.with_bytes(open)?
        }
    }

    fn read_checked_frame_slice(
        &self,
        chunk: &FileChunk,
        range: &std::ops::Range<u64>,
        stored: &[u8],
        cache_slices: Vec<CompressionFrameSlice>,
    ) -> Result<Vec<u8>> {
        if strong_checksum(stored) != chunk.compression_frame_digest {
            return Err(Error::CorruptRecord);
        }
        let start =
            usize::try_from(chunk.compression_frame_offset).map_err(|_| Error::CorruptRecord)?;
        let len = usize::try_from(chunk.len).map_err(|_| Error::CorruptRecord)?;
        let end = start.checked_add(len).ok_or(Error::CorruptRecord)?;
        if end > usize::try_from(chunk.compression_frame_len).map_err(|_| Error::CorruptRecord)? {
            return Err(Error::CorruptRecord);
        }
        let end = start + usize::try_from(range.end).map_err(|_| Error::CorruptRecord)?;
        let start = start + usize::try_from(range.start).map_err(|_| Error::CorruptRecord)?;
        if chunk.compression == COMPRESSION_NONE {
            if stored.len() as u64 != chunk.compression_frame_len || end > stored.len() {
                return Err(Error::CorruptRecord);
            }
            let out = stored[start..end].to_vec();
            if self.should_cache_decoded_compression_frame(stored.len()) {
                self.cache_decoded_compression_frame_owned(chunk, cache_slices, stored.to_vec());
            }
            return Ok(out);
        }

        let mut decoded = ZeroizingBytes::new(decode_compression_frame(
            chunk.compression,
            stored,
            chunk.compression_frame_len,
        )?);
        if start == 0
            && end == decoded.len()
            && !self.should_cache_decoded_compression_frame(decoded.len())
        {
            return Ok(std::mem::take(&mut *decoded));
        }
        let out = decoded[start..end].to_vec();
        self.cache_decoded_compression_frame_owned(
            chunk,
            cache_slices,
            std::mem::take(&mut *decoded),
        );
        Ok(out)
    }

    fn stage_small_file(
        &mut self,
        path: &LockboxPath,
        data: &[u8],
        permissions: u32,
        replace: bool,
    ) -> Result<()>
    where
        State: crate::WritableLockboxState,
    {
        let path = path.file_path()?;
        let permissions = validate_permissions(permissions)?;
        self.validate_replace_intent(&path, replace)?;
        self.create_parent_dirs_for(&path)?;
        if let Some(old) = self.toc_entries.get(path.as_str()).cloned() {
            self.free_entry_slots(old)?;
        }

        self.insert_pending_small_file(
            path.clone(),
            PendingFileChunk {
                path: path.clone(),
                permissions,
                total_len: data.len() as u64,
                data: Arc::from(data),
            },
        );
        self.toc_entries.insert(
            path.clone(),
            TocEntry {
                path: path.clone(),
                len: data.len() as u64,
                record_offset: 0,
                record_len: 0,
                record_object_id: 0,
                record_digest: [0; 32],
                deleted: false,
                node_kind: NodeKind::File,
                permissions,
                chunks: Vec::new(),
            },
        );
        self.mark_toc_dirty(&path);
        if self.should_discard_file_pages_after_flush()
            && self.pending_small_file_bytes >= MAX_SEGMENT_BYTES
        {
            self.flush_pending_small_files()?;
        }
        Ok(())
    }

    pub(crate) fn remove_pending_small_file(
        &mut self,
        path: &LockboxPath,
    ) -> Option<PendingFileChunk> {
        let removed = self.pending_small_files.remove(path);
        if let Some(pending) = removed.as_ref() {
            self.pending_small_file_bytes = self
                .pending_small_file_bytes
                .saturating_sub(pending.data.len());
        }
        removed
    }

    pub(crate) fn insert_pending_small_file(
        &mut self,
        path: LockboxPath,
        pending: PendingFileChunk,
    ) {
        let pending_len = pending.data.len();
        if let Some(old) = self.pending_small_files.insert(path, pending) {
            self.pending_small_file_bytes =
                self.pending_small_file_bytes.saturating_sub(old.data.len());
        }
        self.pending_small_file_bytes = self.pending_small_file_bytes.saturating_add(pending_len);
    }

    pub(crate) fn flush_pending_small_files(&mut self) -> Result<()> {
        if self.pending_small_files.is_empty() {
            return Ok(());
        }

        let pending = std::mem::take(&mut self.pending_small_files);
        self.pending_small_file_bytes = 0;
        let compression_frame_target = self.small_file_compression_frame_target();
        let mut writer = FilePageWriter::new(self);
        let mut all_chunks = Vec::new();
        let mut updates = Vec::new();
        let mut dirty_paths = Vec::new();
        let pending = pending.into_values().collect::<Vec<_>>();
        let mut batches = Vec::new();
        let mut batch = Vec::new();
        let mut batch_bytes = 0usize;
        for chunk in &pending {
            if !batch.is_empty()
                && batch_bytes.saturating_add(chunk.data.len()) > compression_frame_target
            {
                batches.push(batch);
                batch = Vec::new();
                batch_bytes = 0;
            }
            batch_bytes = batch_bytes.saturating_add(chunk.data.len());
            batch.push(CompressionFrameWrite {
                path: &chunk.path,
                permissions: chunk.permissions,
                total_len: chunk.total_len,
                file_offset: 0,
                data: &chunk.data,
            });
        }
        if !batch.is_empty() {
            batches.push(batch);
        }
        let batch_indices = writer.write_compression_frame_batches(&batches, &mut all_chunks)?;
        for (batch, indices) in batches.iter().zip(batch_indices) {
            for (frame, chunk_index) in batch.iter().zip(indices) {
                updates.push((
                    (*frame.path).clone(),
                    frame.permissions,
                    frame.total_len,
                    chunk_index,
                ));
            }
        }
        writer.finish(&mut all_chunks)?;
        for (path, permissions, total_len, chunk_index) in updates {
            let chunks = vec![all_chunks[chunk_index].clone()];
            if let Some(entry) = writer.lockbox.toc_entries.get_mut(path.as_str()) {
                entry.record_offset = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.page_offset)
                    .unwrap_or(0);
                entry.record_len = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.page_len)
                    .unwrap_or(0);
                entry.record_object_id = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.object_id)
                    .unwrap_or(0);
                entry.len = total_len;
                entry.permissions = permissions;
                entry.chunks = chunks;
                dirty_paths.push(entry.path.clone());
                let entry = entry.clone();
                writer.lockbox.add_entry_record_refs(&entry);
            }
        }
        writer.lockbox.mark_toc_dirty_paths(dirty_paths.iter());
        Ok(())
    }

    pub(crate) fn flush_bulk_small_file_packer(&mut self) -> Result<()> {
        self.flush_pending_small_files()
    }

    pub(crate) fn pack_small_file_pages(&mut self) -> Result<()> {
        let mut candidates = Vec::new();
        for entry in self.toc_entries.values() {
            if entry.deleted
                || entry.node_kind != NodeKind::File
                || entry.len > 1024 * 1024
                || entry_has_sparse_ranges(entry)
            {
                continue;
            }
            let data = self.get_file(&entry.path)?;
            candidates.push((entry.path.clone(), entry.permissions, data, entry.clone()));
        }

        if candidates.len() < 10 {
            return Ok(());
        }

        for (_, _, _, old) in &candidates {
            self.free_entry_slots(old.clone())?;
        }

        let compression_frame_target = self.small_file_compression_frame_target();
        let mut writer = FilePageWriter::new(self);
        let mut all_chunks = Vec::new();
        let mut updates = Vec::new();
        let mut dirty_paths = Vec::new();
        let mut batches = Vec::new();
        let mut batch = Vec::new();
        let mut batch_bytes = 0usize;
        for (path, permissions, data, _) in &candidates {
            if !batch.is_empty()
                && batch_bytes.saturating_add(data.len()) > compression_frame_target
            {
                batches.push(batch);
                batch = Vec::new();
                batch_bytes = 0;
            }
            let len = data.len() as u64;
            batch_bytes = batch_bytes.saturating_add(data.len());
            batch.push(CompressionFrameWrite {
                path,
                permissions: *permissions,
                total_len: len,
                file_offset: 0,
                data,
            });
        }
        if !batch.is_empty() {
            batches.push(batch);
        }
        let batch_indices = writer.write_compression_frame_batches(&batches, &mut all_chunks)?;
        for (batch, indices) in batches.iter().zip(batch_indices) {
            for (frame, chunk_index) in batch.iter().zip(indices) {
                updates.push((
                    (*frame.path).clone(),
                    frame.permissions,
                    frame.total_len,
                    chunk_index,
                ));
            }
        }
        writer.finish(&mut all_chunks)?;
        for (path, permissions, len, chunk_index) in updates {
            let chunks = vec![all_chunks[chunk_index].clone()];
            if let Some(entry) = writer.lockbox.toc_entries.get_mut(path.as_str()) {
                entry.record_offset = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.page_offset)
                    .unwrap_or(0);
                entry.record_len = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.page_len)
                    .unwrap_or(0);
                entry.record_object_id = chunks
                    .first()
                    .and_then(|chunk| chunk.segments.first())
                    .map(|segment| segment.object_id)
                    .unwrap_or(0);
                entry.len = len;
                entry.permissions = permissions;
                entry.chunks = chunks;
                dirty_paths.push(entry.path.clone());
                let entry = entry.clone();
                writer.lockbox.add_entry_record_refs(&entry);
            }
        }
        writer.lockbox.mark_toc_dirty_paths(dirty_paths.iter());
        Ok(())
    }

    fn small_file_compression_frame_target(&self) -> usize {
        match self.workload_profile {
            WorkloadProfile::BulkImport => BULK_IMPORT_SMALL_FILE_COMPRESSION_FRAME_BYTES,
            _ => SMALL_FILE_COMPRESSION_FRAME_BYTES,
        }
    }

    fn compression_frame_zstd_level(&self) -> i32 {
        match self.workload_profile {
            WorkloadProfile::BulkImport => ZSTD_BULK_IMPORT_LEVEL,
            _ => ZSTD_DEFAULT_LEVEL,
        }
    }

    fn configured_compression(&self) -> Option<crate::Compression> {
        (self.format_mode.0 != 0).then(|| self.format_mode.options().compression)
    }

    fn decoded_compression_frame_cache_limit(&self) -> usize {
        match self.workload_profile {
            WorkloadProfile::ExtractMany
                if !cfg!(target_arch = "wasm32")
                    && matches!(
                        self.page_manager.borrow().configured_limit(),
                        crate::CacheLimit::Auto
                    ) =>
            {
                // Four ordinary 2 MiB frames retain adjacent packed-file reuse.
                // Native frames share the page cache and its separate 32 MiB target.
                8 * 1024 * 1024
            }
            WorkloadProfile::ReadMostly | WorkloadProfile::ExtractMany => {
                DECODED_COMPRESSION_FRAME_CACHE_BYTES
            }
            _ => 0,
        }
    }

    pub(super) fn trim_decoded_compression_frame_cache(&self) {
        let limit = self.decoded_compression_frame_cache_limit();
        let mut cache = self.compression_frame_cache.borrow_mut();
        while cache.used_bytes > limit {
            let Some(key) = cache.entries.keys().next().copied() else {
                break;
            };
            if let Some(old) = cache.entries.remove(&key) {
                cache.used_bytes = cache.used_bytes.saturating_sub(old.data.len());
                // CachedCompressionFrame::drop wipes the decoded plaintext.
            }
        }
    }

    fn read_cached_compression_frame_slice(
        &self,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: &std::ops::Range<u64>,
    ) -> Result<Option<Vec<u8>>> {
        #[cfg(any(test, feature = "native-block-layout"))]
        if chunk.block_frame.is_some() {
            return self
                .native_cached_frame(chunk)?
                .map(|entry| Self::cached_frame_slice(&entry, expected_total_len, chunk, range))
                .transpose();
        }
        let cache = self.compression_frame_cache.borrow();
        let Some(entry) = cache.entries.get(&chunk.compression_frame_id) else {
            return Ok(None);
        };
        Self::cached_frame_slice(entry, expected_total_len, chunk, range).map(Some)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn native_cached_frame(
        &self,
        chunk: &FileChunk,
    ) -> Result<Option<Arc<super::CachedCompressionFrame>>> {
        let [segment] = chunk.segments.as_slice() else {
            return Err(Error::CorruptRecord);
        };
        Ok(self
            .page_manager
            .borrow_mut()
            .native_decoded_page(segment.page_offset, self.storage.write_revision()))
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn should_cache_native_decoded_frame(&self, len: usize) -> bool {
        let limit = self.page_manager.borrow().stats().limit_bytes;
        limit > 0 && len as u64 <= limit
    }

    fn cached_frame_slice(
        entry: &super::CachedCompressionFrame,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: &std::ops::Range<u64>,
    ) -> Result<Vec<u8>> {
        let bounds = Self::cached_frame_bounds(entry, expected_total_len, chunk, range)?;
        Ok(entry.data[bounds].to_vec())
    }

    fn cached_frame_bounds(
        entry: &super::CachedCompressionFrame,
        expected_total_len: u64,
        chunk: &FileChunk,
        range: &std::ops::Range<u64>,
    ) -> Result<std::ops::Range<usize>> {
        if range.start > range.end || range.end > chunk.len {
            return Err(Error::CorruptRecord);
        }
        if entry.compression != chunk.compression
            || entry.compression_frame_len != chunk.compression_frame_len
            || entry.compressed_len != chunk.compressed_len
            || entry.compression_frame_digest != chunk.compression_frame_digest
        {
            return Err(Error::CorruptRecord);
        }
        let has_slice = entry.slices.iter().any(|slice| {
            slice.compression_frame_offset == chunk.compression_frame_offset
                && slice.len == chunk.len
                && slice.file_offset == chunk.file_offset
                && (slice.total_len == 0 || slice.total_len == expected_total_len)
                && slice.path == chunk.stored_path
        });
        if !has_slice {
            return Err(Error::CorruptRecord);
        }
        let start =
            usize::try_from(chunk.compression_frame_offset).map_err(|_| Error::CorruptRecord)?;
        let len = usize::try_from(chunk.len).map_err(|_| Error::CorruptRecord)?;
        let end = start.checked_add(len).ok_or(Error::CorruptRecord)?;
        if end > entry.data.len() {
            return Err(Error::CorruptRecord);
        }
        let end = start + usize::try_from(range.end).map_err(|_| Error::CorruptRecord)?;
        let start = start + usize::try_from(range.start).map_err(|_| Error::CorruptRecord)?;
        Ok(start..end)
    }

    fn cache_decoded_compression_frame_owned(
        &self,
        chunk: &FileChunk,
        slices: Vec<CompressionFrameSlice>,
        decoded: Vec<u8>,
    ) {
        drop(self.cache_decoded_compression_frame_at_revision(chunk, slices, decoded, 0));
    }

    // Some supplies native-frame ownership, not a promise of cache admission.
    // The caller may retain it through a write even if the cache evicts it.
    fn cache_decoded_compression_frame_at_revision(
        &self,
        chunk: &FileChunk,
        slices: Vec<CompressionFrameSlice>,
        mut decoded: Vec<u8>,
        _revision: u64,
    ) -> Option<Arc<super::CachedCompressionFrame>> {
        #[cfg(any(test, feature = "native-block-layout"))]
        if chunk.block_frame.is_some() {
            let [segment] = chunk.segments.as_slice() else {
                crate::page_buffer::zeroize_bytes(&mut decoded);
                return None;
            };
            return Some(
                self.page_manager.borrow_mut().insert_native_decoded_page(
                    segment.page_offset,
                    segment.page_len,
                    super::CachedCompressionFrame {
                        native_reference: chunk
                            .block_frame
                            .as_ref()
                            .map(|reference| ((**reference).clone(), segment.clone())),
                        compression: chunk.compression,
                        compression_frame_len: chunk.compression_frame_len,
                        compressed_len: chunk.compressed_len,
                        compression_frame_digest: chunk.compression_frame_digest,
                        slices,
                        data: decoded,
                    },
                    _revision,
                ),
            );
        }
        if !self.should_cache_decoded_compression_frame(decoded.len()) {
            crate::page_buffer::zeroize_bytes(&mut decoded);
            return None;
        }
        self.insert_decoded_compression_frame(chunk, slices, decoded);
        None
    }

    fn should_cache_decoded_compression_frame(&self, decoded_len: usize) -> bool {
        let limit = self.decoded_compression_frame_cache_limit();
        limit > 0 && decoded_len <= limit
    }

    fn insert_decoded_compression_frame(
        &self,
        chunk: &FileChunk,
        slices: Vec<CompressionFrameSlice>,
        decoded: Vec<u8>,
    ) {
        let decoded_len = decoded.len();
        let limit = self.decoded_compression_frame_cache_limit();
        let mut cache = self.compression_frame_cache.borrow_mut();
        if let Some(old) = cache.entries.remove(&chunk.compression_frame_id) {
            cache.used_bytes = cache.used_bytes.saturating_sub(old.data.len());
        }
        while cache.used_bytes.saturating_add(decoded_len) > limit {
            let Some(key) = cache.entries.keys().next().copied() else {
                break;
            };
            if let Some(old) = cache.entries.remove(&key) {
                cache.used_bytes = cache.used_bytes.saturating_sub(old.data.len());
            }
        }
        cache.entries.insert(
            chunk.compression_frame_id,
            super::CachedCompressionFrame {
                #[cfg(any(test, feature = "native-block-layout"))]
                native_reference: None,
                compression: chunk.compression,
                compression_frame_len: chunk.compression_frame_len,
                compressed_len: chunk.compressed_len,
                compression_frame_digest: chunk.compression_frame_digest,
                slices,
                data: decoded,
            },
        );
        cache.used_bytes = cache.used_bytes.saturating_add(decoded_len);
    }

    #[cfg(test)]
    pub(crate) fn decoded_compression_frame_cache_entries_for_tests(&self) -> usize {
        self.compression_frame_cache.borrow().entries.len()
            + self.page_manager.borrow().native_decoded_entries()
    }

    /// Stream file content ranges without extracting files to the host filesystem.
    pub fn stream_content<F>(&self, options: ContentStreamOptions, visitor: F) -> Result<()>
    where
        F: FnMut(ContentChunk, &mut dyn Read) -> Result<()>,
    {
        // Workspace setup and final wiping must amortize across enough data.
        // Count file slices, not shared frame lengths, so many tiny files in
        // one cached frame do not spuriously select the larger allocation.
        let mut compressed_bytes = 0u64;
        let reuse = self
            .toc_entries
            .values()
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .flat_map(|entry| &entry.chunks)
            .any(|chunk| {
                if chunk.compression != COMPRESSION_NONE && chunk.compression_frame_len >= 64 * 1024
                {
                    compressed_bytes = compressed_bytes.saturating_add(chunk.len);
                }
                compressed_bytes >= 8 * 1024 * 1024
            });
        if reuse {
            crate::compression::with_decode_workspace(|| {
                self.stream_content_inner(options, visitor)
            })
        } else {
            self.stream_content_inner(options, visitor)
        }
    }

    fn stream_content_inner<F>(&self, options: ContentStreamOptions, mut visitor: F) -> Result<()>
    where
        F: FnMut(ContentChunk, &mut dyn Read) -> Result<()>,
    {
        // A sequential pass larger than the cache evicts single-file frames
        // before a later pass can reuse them. Packed frames still benefit
        // neighboring slices within this pass.
        #[cfg(any(test, feature = "native-block-layout"))]
        let stream_len = self
            .toc_entries
            .values()
            .filter(|entry| !entry.deleted && entry.node_kind == NodeKind::File)
            .fold(0u64, |total, entry| total.saturating_add(entry.len));
        #[cfg(any(test, feature = "native-block-layout"))]
        let cache_single_frames = stream_len <= self.decoded_compression_frame_cache_limit() as u64;
        #[cfg(not(any(test, feature = "native-block-layout")))]
        let cache_single_frames = false;
        let mut stream_state = ContentStreamState::default();
        match options.order {
            ContentStreamOrder::Logical => {
                for entry in self.toc_entries.values() {
                    if entry.deleted || entry.node_kind != NodeKind::File {
                        continue;
                    }
                    self.stream_file_content(
                        entry,
                        &mut visitor,
                        cache_single_frames,
                        &mut stream_state,
                    )?;
                }
            }
            ContentStreamOrder::Physical => {
                let mut items = Vec::new();
                for entry in self.toc_entries.values() {
                    if entry.deleted || entry.node_kind != NodeKind::File {
                        continue;
                    }
                    if self.pending_small_files.contains_key(&entry.path) {
                        if entry.len > 0 {
                            items.push(ContentStreamItem {
                                path: entry.path.clone(),
                                file_offset: 0,
                                len: entry.len,
                                total_len: entry.len,
                                physical_offset: None,
                                sparse: false,
                                chunk: None,
                            });
                        }
                        continue;
                    }
                    collect_content_stream_items(entry, &mut items)?;
                }
                items.sort_by(|left, right| {
                    left.physical_offset
                        .unwrap_or(u64::MAX)
                        .cmp(&right.physical_offset.unwrap_or(u64::MAX))
                        .then_with(|| left.path.cmp(&right.path))
                        .then_with(|| left.file_offset.cmp(&right.file_offset))
                });
                for item in items {
                    self.visit_content_stream_item(
                        item,
                        &mut visitor,
                        cache_single_frames,
                        &mut stream_state,
                    )?;
                }
            }
        }
        Ok(())
    }

    pub(super) fn stream_file_content<'a, F>(
        &'a self,
        entry: &TocEntry,
        visitor: &mut F,
        cache_single_frames: bool,
        stream_state: &mut ContentStreamState<'a>,
    ) -> Result<()>
    where
        F: FnMut(ContentChunk, &mut dyn Read) -> Result<()>,
    {
        if self.pending_small_files.contains_key(&entry.path) {
            if entry.len > 0 {
                self.visit_content_stream_item(
                    ContentStreamItem {
                        path: entry.path.clone(),
                        file_offset: 0,
                        len: entry.len,
                        total_len: entry.len,
                        physical_offset: None,
                        sparse: false,
                        chunk: None,
                    },
                    visitor,
                    cache_single_frames,
                    stream_state,
                )?;
            }
            return Ok(());
        }
        let mut items = Vec::new();
        collect_content_stream_items(entry, &mut items)?;
        for item in items {
            self.visit_content_stream_item(item, visitor, cache_single_frames, stream_state)?;
        }
        Ok(())
    }

    fn visit_content_stream_item<'a, F>(
        &'a self,
        item: ContentStreamItem,
        visitor: &mut F,
        _cache_single_frames: bool,
        _state: &mut ContentStreamState<'a>,
    ) -> Result<()>
    where
        F: FnMut(ContentChunk, &mut dyn Read) -> Result<()>,
    {
        let chunk = ContentChunk {
            path: item.path.clone(),
            file_offset: item.file_offset,
            len: item.len,
            physical_offset: item.physical_offset,
            sparse: item.sparse,
        };
        #[cfg(any(test, feature = "native-block-layout"))]
        if let Some(reference) = item.chunk.as_ref().filter(|reference| {
            !item.sparse
                && reference.block_frame.is_some()
                && reference.len < reference.compression_frame_len
        }) {
            use crate::file_format::indexed_frame::block_page::validate_chunk_reference;
            validate_chunk_reference(self.lockbox_id, self.format_mode, item.total_len, reference)?;
            if !_state.native.as_ref().is_some_and(|retained| {
                retained.reference.block_frame == reference.block_frame
                    && retained.reference.segments == reference.segments
            }) {
                // Drop and wipe the previous frame before allocating another.
                _state.native = None;
                let reader = self.open_native_block_chunk(item.total_len, reference)?;
                let cached = {
                    if let Some(entry) = self.native_cached_frame(reference)? {
                        if entry.compression != reference.compression
                            || entry.compression_frame_len != reference.compression_frame_len
                            || entry.compressed_len != reference.compressed_len
                            || entry.compression_frame_digest != reference.compression_frame_digest
                            || entry.slices != reader.slices()
                        {
                            return Err(Error::CorruptRecord);
                        }
                        Some(ZeroizingBytes::new(entry.data.clone()))
                    } else {
                        None
                    }
                };
                let was_cached = cached.is_some();
                let data = match cached {
                    Some(data) => data,
                    None => ZeroizingBytes::new(reader.read(0..reference.compression_frame_len)?),
                };
                if !was_cached
                    && self.should_cache_decoded_compression_frame(data.len())
                    && self.should_cache_native_decoded_frame(data.len())
                {
                    let _ = self.cache_decoded_compression_frame_at_revision(
                        reference,
                        reader.slices().to_vec(),
                        data.to_vec(),
                        reader.write_revision(),
                    );
                }
                _state.native = Some(NativeStreamFrame {
                    reference: reference.clone(),
                    reader,
                    data,
                });
            }
            let retained = _state.native.as_ref().ok_or(Error::CorruptRecord)?;
            retained.reader.validate_slice(reference, item.total_len)?;
            retained.reader.ensure_current()?;
            let start = usize::try_from(reference.compression_frame_offset)
                .map_err(|_| Error::CorruptRecord)?;
            let end = start
                .checked_add(usize::try_from(reference.len).map_err(|_| Error::CorruptRecord)?)
                .ok_or(Error::CorruptRecord)?;
            let bytes = retained.data.get(start..end).ok_or(Error::CorruptRecord)?;
            return visitor(chunk, &mut Cursor::new(bytes));
        }
        #[cfg(any(test, feature = "native-block-layout"))]
        {
            _state.native = None;
        }
        if item.sparse {
            let mut reader = ZeroReader {
                remaining: item.len,
            };
            visitor(chunk, &mut reader)?;
        } else {
            let data = match item.chunk.as_ref() {
                #[cfg(any(test, feature = "native-block-layout"))]
                Some(chunk) if chunk.block_frame.is_some() => self
                    .read_native_block_chunk_with_cache(
                        item.total_len,
                        chunk,
                        0..chunk.len,
                        _cache_single_frames,
                    )?,
                Some(chunk) => self.read_file_chunk_compression_frame(item.total_len, chunk)?,
                None => self.read_file_range(&item.path, item.file_offset, item.len)?,
            };
            let mut reader = Cursor::new(data);
            visitor(chunk, &mut reader)?;
        }
        Ok(())
    }
}

#[derive(Default)]
pub(super) struct ContentStreamState<'a> {
    #[cfg(any(test, feature = "native-block-layout"))]
    native: Option<NativeStreamFrame<'a>>,
    #[cfg(not(any(test, feature = "native-block-layout")))]
    _lifetime: std::marker::PhantomData<&'a ()>,
}

#[cfg(any(test, feature = "native-block-layout"))]
// One verified packed frame retained within a stream call. The reader checks
// the source before each slice; dropping this state wipes data, including on
// visitor error or unwind. It never retains a second frame during replacement.
struct NativeStreamFrame<'a> {
    reference: FileChunk,
    reader: crate::file_format::indexed_frame::block_page::Reader<'a>,
    data: ZeroizingBytes,
}

#[derive(Debug)]
struct ContentStreamItem {
    path: LockboxPath,
    file_offset: u64,
    len: u64,
    total_len: u64,
    physical_offset: Option<u64>,
    sparse: bool,
    chunk: Option<FileChunk>,
}

struct ZeroReader {
    remaining: u64,
}

impl Read for ZeroReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.remaining == 0 || buf.is_empty() {
            return Ok(0);
        }
        let len = buf.len().min(self.remaining as usize);
        buf[..len].fill(0);
        self.remaining -= len as u64;
        Ok(len)
    }
}

fn collect_content_stream_items(
    entry: &TocEntry,
    items: &mut Vec<ContentStreamItem>,
) -> Result<()> {
    if entry.len == 0 {
        return Ok(());
    }
    let mut chunks = entry.chunks.clone();
    chunks.sort_by_key(|chunk| chunk.file_offset);
    let mut cursor = 0u64;
    for chunk in chunks {
        let chunk_end = chunk.file_offset.saturating_add(chunk.len);
        if chunk.file_offset < cursor || chunk_end > entry.len {
            return Err(Error::CorruptRecord);
        }
        if chunk.file_offset > cursor {
            items.push(ContentStreamItem {
                path: entry.path.clone(),
                file_offset: cursor,
                len: chunk.file_offset - cursor,
                total_len: entry.len,
                physical_offset: None,
                sparse: true,
                chunk: None,
            });
        }
        if chunk.len > 0 {
            items.push(ContentStreamItem {
                path: entry.path.clone(),
                file_offset: chunk.file_offset,
                len: chunk.len,
                total_len: entry.len,
                physical_offset: first_physical_offset(&chunk),
                sparse: false,
                chunk: Some(chunk.clone()),
            });
        }
        cursor = chunk_end;
    }
    if cursor < entry.len {
        items.push(ContentStreamItem {
            path: entry.path.clone(),
            file_offset: cursor,
            len: entry.len - cursor,
            total_len: entry.len,
            physical_offset: None,
            sparse: true,
            chunk: None,
        });
    }
    Ok(())
}

fn first_physical_offset(chunk: &FileChunk) -> Option<u64> {
    chunk
        .segments
        .iter()
        .map(|segment| segment.page_offset)
        .min()
}

fn entry_has_sparse_ranges(entry: &TocEntry) -> bool {
    if entry.len == 0 {
        return false;
    }
    let mut chunks = entry.chunks.clone();
    chunks.sort_by_key(|chunk| chunk.file_offset);
    let mut cursor = 0u64;
    for chunk in chunks {
        if chunk.file_offset != cursor {
            return true;
        }
        cursor = cursor.saturating_add(chunk.len);
    }
    cursor != entry.len
}

pub(super) fn ranges_overlap(
    left_start: u64,
    left_end: u64,
    right_start: u64,
    right_end: u64,
) -> bool {
    left_start < right_end && right_start < left_end
}

pub(super) fn trim_zeroes(bytes: &[u8]) -> Option<(usize, usize)> {
    let start = bytes.iter().position(|byte| *byte != 0)?;
    let end = bytes
        .iter()
        .rposition(|byte| *byte != 0)
        .map(|index| index + 1)?;
    Some((start, end))
}

fn write_zeroes(writer: &mut impl Write, mut len: u64) -> Result<()> {
    const ZERO_BUF: [u8; 8192] = [0; 8192];
    while len > 0 {
        let write_len = ZERO_BUF.len().min(len as usize);
        writer
            .write_all(&ZERO_BUF[..write_len])
            .map_err(|err| Error::Io(err.to_string()))?;
        len -= write_len as u64;
    }
    Ok(())
}

pub(super) fn seek_position(current: u64, len: u64, pos: SeekFrom) -> io::Result<u64> {
    let absolute = match pos {
        SeekFrom::Start(offset) => offset as i128,
        SeekFrom::End(offset) => len as i128 + offset as i128,
        SeekFrom::Current(offset) => current as i128 + offset as i128,
    };
    if absolute < 0 || absolute > u64::MAX as i128 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid seek before start of file",
        ));
    }
    Ok(absolute as u64)
}

pub(super) fn to_io_error(err: Error) -> io::Error {
    io::Error::other(err)
}

fn read_next_chunk(reader: &mut impl Read, buffer: &mut [u8]) -> Result<usize> {
    let mut read_total = 0usize;
    while read_total < buffer.len() {
        let read = reader
            .read(&mut buffer[read_total..])
            .map_err(|err| Error::Io(err.to_string()))?;
        if read == 0 {
            break;
        }
        read_total += read;
    }
    Ok(read_total)
}

struct ParallelFrameOrder {
    pending: BTreeMap<usize, PreparedCompressionFrame>,
    next_index: usize,
    received_count: usize,
}

impl ParallelFrameOrder {
    fn new() -> Self {
        Self {
            pending: BTreeMap::new(),
            next_index: 0,
            received_count: 0,
        }
    }

    fn drain_ready<State>(
        &mut self,
        result_rx: &std::sync::mpsc::Receiver<ParallelCompressionResult>,
        writer: &mut FilePageWriter<'_, State>,
        chunks: &mut Vec<FileChunk>,
    ) -> Result<()> {
        loop {
            match result_rx.try_recv() {
                Ok(result) => self.accept(result, writer, chunks)?,
                Err(std::sync::mpsc::TryRecvError::Empty) => return Ok(()),
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    return Err(Error::Io(
                        "compression worker stopped unexpectedly".to_string(),
                    ));
                }
            }
        }
    }

    fn accept<State>(
        &mut self,
        result: ParallelCompressionResult,
        writer: &mut FilePageWriter<'_, State>,
        chunks: &mut Vec<FileChunk>,
    ) -> Result<()> {
        self.received_count += 1;
        self.pending.insert(result.index, result.frame);
        while let Some(frame) = self.pending.remove(&self.next_index) {
            writer.write_prepared_compression_frame(frame, chunks)?;
            self.next_index += 1;
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
struct PendingSegment {
    chunk_indices: Vec<usize>,
    segment_offset: u64,
    segment_len: u64,
}

pub(super) struct FilePageWriter<'a, State> {
    lockbox: &'a mut Lockbox<State>,
    packer: PageObjectPacker<PendingSegment>,
    #[cfg(any(test, feature = "native-block-layout"))]
    native_blocks: bool,
}

struct SharedCompressionFrameSurvivor {
    path: LockboxPath,
    permissions: u32,
    total_len: u64,
    file_offset: u64,
    data: Vec<u8>,
}

impl Drop for SharedCompressionFrameSurvivor {
    fn drop(&mut self) {
        self.data.zeroize();
    }
}

impl<'a, State> FilePageWriter<'a, State> {
    pub(super) fn new(lockbox: &'a mut Lockbox<State>) -> Self {
        #[cfg(any(test, feature = "native-block-layout"))]
        let native_blocks = cfg!(feature = "native-block-layout") && lockbox.format_mode.0 != 0;
        Self {
            lockbox,
            packer: PageObjectPacker::new(DEFAULT_PAGE_BYTES),
            #[cfg(any(test, feature = "native-block-layout"))]
            native_blocks,
        }
    }

    #[cfg(test)]
    pub(super) fn native(lockbox: &'a mut Lockbox<State>) -> Self {
        Self {
            native_blocks: true,
            ..Self::new(lockbox)
        }
    }

    pub(super) fn write_compression_frame(
        &mut self,
        frame: CompressionFrameWrite<'_>,
        chunks: &mut Vec<FileChunk>,
    ) -> Result<()> {
        self.write_compression_frame_bundle(&[frame], chunks)
            .map(|_| ())
    }

    pub(super) fn write_compression_frame_bundle(
        &mut self,
        frames: &[CompressionFrameWrite<'_>],
        chunks: &mut Vec<FileChunk>,
    ) -> Result<Vec<usize>> {
        let prepared = self.import_pipeline(1).prepare(frames);
        self.write_prepared_compression_frame(prepared, chunks)
    }

    fn write_compression_frame_batches(
        &mut self,
        batches: &[Vec<CompressionFrameWrite<'_>>],
        chunks: &mut Vec<FileChunk>,
    ) -> Result<Vec<Vec<usize>>> {
        let prepared = self
            .import_pipeline(self.lockbox.worker_jobs())
            .prepare_batches(batches);
        let mut indices = Vec::with_capacity(prepared.len());
        for frame in prepared {
            indices.push(self.write_prepared_compression_frame(frame, chunks)?);
        }
        Ok(indices)
    }

    fn import_pipeline(&self, jobs: usize) -> FileImportPipeline {
        let pipeline = FileImportPipeline::new(self.lockbox.compression_frame_zstd_level(), jobs)
            .with_sensitive(!self.lockbox.format_mode.plaintext())
            .with_compression(self.lockbox.configured_compression());
        #[cfg(any(test, feature = "native-block-layout"))]
        let pipeline = pipeline.with_native_blocks(self.native_blocks);
        pipeline
    }

    fn write_prepared_compression_frame(
        &mut self,
        prepared: PreparedCompressionFrame,
        chunks: &mut Vec<FileChunk>,
    ) -> Result<Vec<usize>> {
        #[cfg(any(test, feature = "native-block-layout"))]
        if self.native_blocks {
            return self.write_prepared_native_frame(prepared, chunks);
        }
        let compression_frame_digest = prepared.integrity.legacy_checksum()?;
        self.lockbox.add_frame_prepare_nanos(prepared.prepare_nanos);
        self.lockbox.sequence += 1;
        let compression_frame_id = self.lockbox.sequence;
        let mut chunk_indices = Vec::with_capacity(prepared.slices.len());
        let manifest = CompressionFrameManifest {
            compression_frame_id,
            compression: prepared.compression,
            compression_frame_len: prepared.compression_frame_len,
            compressed_len: prepared.compressed_len,
            compression_frame_digest,
            slices: prepared.slices,
        };
        for slice in &manifest.slices {
            let chunk_index = chunks.len();
            chunks.push(FileChunk {
                #[cfg(any(test, feature = "native-block-layout"))]
                block_frame: None,
                stored_path: slice.path.clone(),
                file_offset: slice.file_offset,
                len: slice.len,
                compression_frame_offset: slice.compression_frame_offset,
                compression_frame_len: manifest.compression_frame_len,
                compressed_len: manifest.compressed_len,
                compression: manifest.compression,
                compression_frame_id,
                compression_frame_digest: manifest.compression_frame_digest,
                segments: Vec::new(),
            });
            chunk_indices.push(chunk_index);
        }

        if prepared.stored.is_empty() {
            self.add_segment(&manifest, 0, &chunk_indices, &[], chunks)?;
            return Ok(chunk_indices);
        }

        let mut offset = 0usize;
        while offset < prepared.stored.len() {
            let end = (offset + MAX_SEGMENT_BYTES).min(prepared.stored.len());
            self.add_segment(
                &manifest,
                offset as u64,
                &chunk_indices,
                &prepared.stored[offset..end],
                chunks,
            )?;
            offset = end;
        }
        Ok(chunk_indices)
    }

    #[cfg(any(test, feature = "native-block-layout"))]
    fn write_prepared_native_frame(
        &mut self,
        prepared: PreparedCompressionFrame,
        chunks: &mut Vec<FileChunk>,
    ) -> Result<Vec<usize>> {
        use crate::file_chunk::BlockFrameReference;
        use crate::file_format::indexed_frame::block_page::PageIdentity;
        use crate::page_cache::PageWritePolicy;
        self.flush(chunks)?;
        self.lockbox.add_frame_prepare_nanos(prepared.prepare_nanos);
        let started = Instant::now();
        let frame_id = self
            .lockbox
            .sequence
            .checked_add(1)
            .ok_or(Error::CorruptRecord)?;
        let page_id = frame_id.checked_add(1).ok_or(Error::CorruptRecord)?;
        let identity = PageIdentity {
            archive: self.lockbox.lockbox_id,
            mode: self.lockbox.format_mode,
            page_id,
            sequence: page_id,
        };
        let page = std::sync::Arc::new(
            self.lockbox
                .key
                .with_bytes(|key| prepared.encode_native_page(identity, frame_id, key))??,
        );
        self.lockbox.sequence = page_id;
        let page_len = page.bytes().len() as u64;
        let offset = self.lockbox.allocate_page_offset(page_len)?;
        self.lockbox.page_manager.borrow_mut().stage_native_page(
            offset,
            self.lockbox.lockbox_id,
            page.clone(),
            PageWritePolicy::DiscardAfterFlush,
        )?;
        // The normal preparation protocol owns both reused and appended extents.
        // Publish no chunk reference until those bytes have actually been written.
        self.lockbox.flush_discardable_pages()?;
        let reference = std::sync::Arc::new(BlockFrameReference {
            descriptor: page.descriptor().clone(),
            sequence: identity.sequence,
        });
        let mut indices = Vec::with_capacity(prepared.slices.len());
        for slice in prepared.slices {
            indices.push(chunks.len());
            chunks.push(FileChunk {
                block_frame: Some(reference.clone()),
                stored_path: slice.path,
                file_offset: slice.file_offset,
                len: slice.len,
                compression_frame_offset: slice.compression_frame_offset,
                compression_frame_len: reference.descriptor.logical_len,
                compressed_len: reference.descriptor.stored_len,
                compression: reference.descriptor.compression,
                compression_frame_id: frame_id,
                compression_frame_digest: reference.descriptor.index_commitment,
                segments: vec![CompressionFrameSegment {
                    page_offset: offset,
                    page_len,
                    object_id: page_id,
                    segment_offset: 0,
                    segment_len: reference.descriptor.stored_len,
                }],
            });
        }
        self.lockbox
            .add_page_write_nanos(started.elapsed().as_nanos());
        Ok(indices)
    }

    fn add_segment(
        &mut self,
        manifest: &CompressionFrameManifest,
        segment_offset: u64,
        chunk_indices: &[usize],
        segment: &[u8],
        chunks: &mut [FileChunk],
    ) -> Result<()> {
        self.lockbox.sequence += 1;
        let object_id = self.lockbox.sequence;
        let payload = crate::payload::encode_compression_frame_segment_payload_with_compression(
            manifest,
            segment_offset,
            segment,
            self.lockbox.configured_compression(),
            !self.lockbox.format_mode.plaintext(),
        )?;
        let object = PageObject::new(PageObjectKind::FileData, object_id, payload);
        let context = PendingSegment {
            chunk_indices: chunk_indices.to_vec(),
            segment_offset,
            segment_len: segment.len() as u64,
        };

        let encoded_len = self.packer.encoded_object_len(&object)?;
        if !self.packer.is_empty() && !self.fits_with(encoded_len)? {
            self.flush(chunks)?;
        }
        if !self.fits_with(encoded_len)? {
            return Err(Error::SecurityLimitExceeded(
                "file segment does not fit in a page".to_string(),
            ));
        }
        self.packer.push_encoded(object, context, encoded_len)?;
        Ok(())
    }

    pub(super) fn finish(&mut self, chunks: &mut [FileChunk]) -> Result<()> {
        self.flush(chunks)
    }

    fn fits_with(&self, encoded_len: usize) -> Result<bool> {
        self.packer.fits_encoded_len(encoded_len)
    }

    fn flush(&mut self, chunks: &mut [FileChunk]) -> Result<()> {
        if self.packer.is_empty() {
            return Ok(());
        }
        let write_start = Instant::now();
        // This operation-local writer is discarded on errors. Transfer payloads
        // into the page, retaining only the small reference-publication context.
        let pending = self.packer.take_pending();
        let mut objects = Vec::with_capacity(pending.len());
        let mut contexts = Vec::with_capacity(pending.len());
        for pending in pending {
            contexts.push((pending.object.id, pending.context));
            objects.push(pending.object);
        }
        let page_size = crate::page::page_size_for_encoded_objects_with_format(
            &objects,
            self.lockbox.format_mode,
        )?;
        let page_offset = self.lockbox.allocate_page_offset(page_size as u64)?;
        if self.lockbox.should_discard_file_pages_after_flush() {
            self.lockbox
                .write_insert_only_page_at(page_offset, self.lockbox.sequence, objects)?;
            self.lockbox.flush_discardable_pages()?;
        } else {
            self.lockbox
                .write_decoded_page_at(page_offset, self.lockbox.sequence, objects)?;
            self.lockbox
                .page_manager
                .borrow_mut()
                .mark_new_file_page(page_offset);
            self.lockbox.flush_file_pages_under_pressure()?;
        }
        for (object_id, context) in contexts {
            for chunk_index in context.chunk_indices {
                if let Some(chunk) = chunks.get_mut(chunk_index) {
                    chunk.segments.push(CompressionFrameSegment {
                        page_offset,
                        page_len: page_size as u64,
                        object_id,
                        segment_offset: context.segment_offset,
                        segment_len: context.segment_len,
                    });
                }
            }
        }
        self.lockbox
            .add_page_write_nanos(write_start.elapsed().as_nanos());
        Ok(())
    }
}