rustfs-ecstore 1.0.1

Erasure coding storage backend for RustFS, providing efficient data storage and retrieval with redundancy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;

use crate::io_support::rio::Index;
use std::mem::MaybeUninit;

#[cfg(feature = "rio-v2")]
const DARE_PAYLOAD_SIZE: i64 = 64 * 1024;
#[cfg(feature = "rio-v2")]
const DARE_PACKAGE_SIZE: i64 = DARE_PAYLOAD_SIZE + 32;

fn part_plaintext_size(part: &ObjectPartInfo) -> i64 {
    if part.actual_size > 0 {
        part.actual_size
    } else {
        part.size as i64
    }
}

fn http_range_spec_from_object_info(oi: &ObjectInfo, part_number: usize) -> Option<HTTPRangeSpec> {
    HTTPRangeSpec::from_part_sizes(oi.size, part_number, oi.parts.iter().map(part_plaintext_size))
}

/// A restore read forces `ReadPlan::build` down the `Plain` branch, so it
/// yields the STORED representation even for compressed or encrypted objects.
pub(crate) fn restore_request_active(opts: &ObjectOptions) -> bool {
    let restore = &opts.transition.restore_request;
    restore.type_.is_some() || restore.days.is_some() || restore.output_location.is_some() || restore.select_parameters.is_some()
}

fn decode_compression_index(index: Option<&Bytes>) -> Option<Index> {
    crate::io_support::rio::decode_compression_index_bytes(index?)
}

fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
    let mut skip_length = 0_i64;
    let mut cumulative_actual_size = 0_i64;
    let mut first_part_idx = 0_usize;
    let mut compressed_offset = 0_i64;

    for (i, part) in oi.parts.iter().enumerate() {
        cumulative_actual_size += part_plaintext_size(part);
        if cumulative_actual_size <= offset {
            compressed_offset += part.size as i64;
        } else {
            first_part_idx = i;
            skip_length = cumulative_actual_size - part_plaintext_size(part);
            break;
        }
    }

    let mut part_skip = offset - skip_length;
    #[cfg(feature = "rio-v2")]
    let (mut decrypt_skip, mut seq_num) = (0_i64, 0_u64);
    #[cfg(not(feature = "rio-v2"))]
    let (decrypt_skip, seq_num) = (0_i64, 0_u64);

    if part_skip > 0
        && let Some(part) = oi.parts.get(first_part_idx)
        && let Some(index) = decode_compression_index(part.index.as_ref())
        && let Ok((comp_off, uncomp_off)) = index.find(part_skip)
        && comp_off > 0
    {
        #[cfg(feature = "rio-v2")]
        if oi.is_encrypted() {
            seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
            decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
            compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
        } else {
            compressed_offset += comp_off;
        }

        #[cfg(not(feature = "rio-v2"))]
        {
            compressed_offset += comp_off;
        }

        part_skip -= uncomp_off;
    }

    (compressed_offset, part_skip, first_part_idx, decrypt_skip, seq_num)
}

#[cfg(feature = "rio-v2")]
fn get_encrypted_offsets(oi: &ObjectInfo, offset: i64) -> Result<(i64, usize, usize, u32, i64)> {
    if oi.parts.is_empty() {
        let plaintext_size = oi.decrypted_size()?;
        let start_package_number = offset / DARE_PAYLOAD_SIZE;
        let plaintext_skip = usize::try_from(offset % DARE_PAYLOAD_SIZE)
            .map_err(|_| Error::other(format!("invalid DARE skip offset {offset}")))?;
        let encrypted_offset = start_package_number * DARE_PACKAGE_SIZE;
        let aligned_plaintext_offset = start_package_number * DARE_PAYLOAD_SIZE;
        let remaining_plaintext_size = plaintext_size - aligned_plaintext_offset;
        let sequence_number = u32::try_from(start_package_number)
            .map_err(|_| Error::other(format!("invalid DARE sequence number {start_package_number}")))?;
        return Ok((encrypted_offset, plaintext_skip, 0, sequence_number, remaining_plaintext_size));
    }

    let mut cumulative_plaintext_size = 0_i64;
    let mut cumulative_encrypted_size = 0_i64;

    for (part_index, part) in oi.parts.iter().enumerate() {
        let current_part_plaintext_size = part_plaintext_size(part);
        if offset < cumulative_plaintext_size + current_part_plaintext_size {
            let relative_offset = offset - cumulative_plaintext_size;
            let start_package_number = relative_offset / DARE_PAYLOAD_SIZE;
            let plaintext_skip = usize::try_from(relative_offset % DARE_PAYLOAD_SIZE)
                .map_err(|_| Error::other(format!("invalid DARE skip offset {relative_offset}")))?;
            let encrypted_offset = cumulative_encrypted_size + start_package_number * DARE_PACKAGE_SIZE;
            let aligned_plaintext_offset = cumulative_plaintext_size + start_package_number * DARE_PAYLOAD_SIZE;
            let remaining_plaintext_size = oi.decrypted_size()? - aligned_plaintext_offset;
            let sequence_number = u32::try_from(start_package_number)
                .map_err(|_| Error::other(format!("invalid DARE sequence number {start_package_number}")))?;

            return Ok((encrypted_offset, plaintext_skip, part_index, sequence_number, remaining_plaintext_size));
        }

        cumulative_plaintext_size += current_part_plaintext_size;
        cumulative_encrypted_size += part.size as i64;
    }

    Err(Error::other(format!(
        "invalid encrypted offset {offset} for object with decrypted size {}",
        oi.decrypted_size()?
    )))
}

/// Metric path label for a Legacy encrypted Range GET that kept the conservative full-object read.
const ENCRYPTED_RANGE_READ_PATH_FULL: &str = "full";
/// Metric path label for a Legacy encrypted Range GET served by the part-boundary seek.
const ENCRYPTED_RANGE_READ_PATH_PART_SEEK: &str = "part_seek";
/// Metric path label for a single-part v2 fixed-frame seek.
const ENCRYPTED_RANGE_READ_PATH_FRAME_SEEK: &str = "frame_seek";

/// Plaintext bytes per non-final v2 frame (the rio v2 writer's fixed block).
const V2_FRAME_PLAINTEXT_LEN: i64 = 8 * 1024;
/// Ciphertext cost of one full v2 frame: 8-byte header, 2-byte uvarint(8192),
/// the plaintext block, and the 16-byte GCM tag.
const V2_FRAME_CIPHERTEXT_LEN: i64 = 8 + 2 + V2_FRAME_PLAINTEXT_LEN + 16;

/// True when a single-part v2 fixed-frame object may seek to a frame boundary.
///
/// The marker's value is the object's `data_dir` token (see
/// [`ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX`]), so metadata re-homed onto other
/// ciphertext or another object identity disqualifies itself. Correctness never
/// rests on the marker: the v2 decrypt path authenticates every frame against
/// its absolute index, so a lying marker surfaces as a read error, never as
/// plaintext from the wrong offset.
fn v2_frame_seek_eligible(
    oi: &ObjectInfo,
    is_multipart: bool,
    is_compressed: bool,
    requested_length: i64,
    recorded_plaintext_size: Option<i64>,
) -> bool {
    if is_multipart || is_compressed || requested_length <= 0 || recorded_plaintext_size.is_none() {
        return false;
    }
    let Some(data_dir) = oi.data_dir.filter(|data_dir| !data_dir.is_nil()) else {
        return false;
    };
    let mut layout_token_buf = [0_u8; 36];
    let layout_token = data_dir.hyphenated().encode_lower(&mut layout_token_buf);
    has_encrypted_part_layout_marker(&oi.user_defined, ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX, layout_token)
}

/// Closed-form frame-boundary offsets for a single-part v2 object.
///
/// Returns `(storage_offset, storage_length, plaintext_skip_in_frame,
/// starting_frame_index, remaining_plaintext)`. `None` on any bound the stored
/// layout cannot satisfy — the caller then keeps the conservative full read.
fn get_v2_frame_offsets(oi: &ObjectInfo, offset: i64, length: i64, plaintext_size: i64) -> Option<(i64, i64, usize, u32, i64)> {
    if offset < 0 || length <= 0 || plaintext_size < 0 {
        return None;
    }
    let end = offset.checked_add(length)?.checked_sub(1)?;
    if end >= plaintext_size {
        return None;
    }
    let frame_index = offset / V2_FRAME_PLAINTEXT_LEN;
    let storage_offset = frame_index.checked_mul(V2_FRAME_CIPHERTEXT_LEN)?;
    if storage_offset >= oi.size {
        return None;
    }
    let end_frame = end / V2_FRAME_PLAINTEXT_LEN;
    let total_full_frames = plaintext_size / V2_FRAME_PLAINTEXT_LEN;
    // Frames below `total_full_frames` are full-size by construction. A range
    // reaching into the last plaintext-bearing frame extends the window to the
    // ciphertext end: a range that touches the plaintext end drains the
    // decrypt stream, and the stream only ends cleanly at its authenticated
    // final frame (which on a block-aligned object is the empty frame after
    // the last full one). Interior ranges stop before their window ends and
    // never observe the cut.
    let storage_end = if end_frame.checked_add(1)? < total_full_frames {
        end_frame.checked_add(1)?.checked_mul(V2_FRAME_CIPHERTEXT_LEN)?.min(oi.size)
    } else {
        oi.size
    };
    if storage_end <= storage_offset {
        return None;
    }
    let plaintext_skip = usize::try_from(offset % V2_FRAME_PLAINTEXT_LEN).ok()?;
    let remaining_plaintext = plaintext_size.checked_sub(frame_index.checked_mul(V2_FRAME_PLAINTEXT_LEN)?)?;
    let starting_frame = u32::try_from(frame_index).ok()?;
    Some((
        storage_offset,
        storage_end - storage_offset,
        plaintext_skip,
        starting_frame,
        remaining_plaintext,
    ))
}

/// True when a Legacy (rio v1) encrypted Range GET may seek to the covering part
/// boundary instead of streaming the whole ciphertext.
///
/// Every condition is required for correctness, not merely for benefit:
/// - `is_multipart`: single-part rio v1 streams have variable-length encrypted blocks
///   with no closed-form plaintext-to-physical mapping, so only part boundaries
///   (recorded in metadata) are safe seek targets.
/// - `!is_compressed`: under compression the requested offset addresses the
///   decompressed stream, not per-part plaintext, so stay on the full read.
/// - non-empty parts with `actual_size > 0` for every part: a part with
///   `actual_size <= 0` would make `part_plaintext_size` fall back to the physical
///   size and poison the plaintext cumulative sums.
/// - physical part sizes must add up to `oi.size`: guards against inconsistent
///   metadata scheduling reads past the object end in the erasure layer.
/// - plaintext part sizes must add up to the recorded decrypted object size.
/// - `requested_length > 0`: degenerate empty ranges keep their existing full-read
///   behavior (and its error surface) unchanged.
fn legacy_encrypted_seek_eligible(
    oi: &ObjectInfo,
    is_multipart: bool,
    is_compressed: bool,
    requested_length: i64,
    recorded_plaintext_size: Option<i64>,
) -> bool {
    if !legacy_encrypted_range_seek_enabled() || !is_multipart || is_compressed || requested_length <= 0 || oi.parts.is_empty() {
        return false;
    }
    let Some(recorded_plaintext_size) = recorded_plaintext_size else {
        return false;
    };
    let Some(data_dir) = oi.data_dir.filter(|data_dir| !data_dir.is_nil()) else {
        return false;
    };
    let mut layout_token_buf = [0_u8; 36];
    let layout_token = data_dir.hyphenated().encode_lower(&mut layout_token_buf);
    if !has_encrypted_part_layout_marker(&oi.user_defined, ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX, layout_token) {
        return false;
    }

    let Some((physical_size, plaintext_size)) = legacy_part_layout_totals(&oi.parts) else {
        return false;
    };
    physical_size == oi.size && recorded_plaintext_size == plaintext_size
}

fn legacy_part_layout_totals(parts: &[ObjectPartInfo]) -> Option<(i64, i64)> {
    if parts.is_empty() {
        return None;
    }
    // Complete votes on these four boundary fields in
    // `resolve_read_part_from_responses`; final object reads additionally require
    // the full `FileInfo` identity (including parts) to reach metadata quorum.
    parts
        .iter()
        .try_fold((0_i64, 0_i64), |(physical_size, plaintext_size), part| {
            let part_physical_size = i64::try_from(part.size).ok()?;
            let part_plaintext_size = (part.actual_size > 0).then_some(part.actual_size)?;
            Some((
                physical_size.checked_add(part_physical_size)?,
                plaintext_size.checked_add(part_plaintext_size)?,
            ))
        })
}

/// Part-boundary seek offsets for a Legacy (rio v1) encrypted multipart object.
///
/// Uses only the two per-part metadata facts — `size` (physical encrypted bytes on
/// disk) and `actual_size` (plaintext bytes) — and makes zero assumptions about the
/// encrypted block layout inside a part. Returns `(physical_offset, physical_length,
/// plaintext_skip_in_part, part_start_index, remaining_plaintext)` where
/// `physical_offset` is the ciphertext offset of the first part covering `offset`,
/// `physical_length` extends to the physical end of the last part covering
/// `offset + length - 1`, `plaintext_skip_in_part` is the decrypted plaintext to
/// discard before the range starts, and `remaining_plaintext` is the total plaintext
/// from the covering part through the end of the object (the same contract
/// `get_encrypted_offsets` hands to `into_reader`).
///
/// Returns `None` when the range does not fall inside the parts table; the caller
/// must then keep the conservative full-object read. With the
/// `legacy_encrypted_seek_eligible` gate satisfied this cannot happen, because the
/// range spec already clamps `offset + length` to the summed part plaintext.
fn get_legacy_encrypted_offsets(oi: &ObjectInfo, offset: i64, length: i64) -> Option<(i64, i64, usize, usize, i64)> {
    if offset < 0 || length <= 0 {
        return None;
    }
    let end_plaintext = offset.checked_add(length)?.checked_sub(1)?;
    let mut cumulative_plaintext_size = 0_i64;
    let mut cumulative_encrypted_size = 0_i64;

    for (part_index, part) in oi.parts.iter().enumerate() {
        let current_part_plaintext_size = part.actual_size;
        let part_plaintext_end = cumulative_plaintext_size.checked_add(current_part_plaintext_size)?;
        if offset < part_plaintext_end {
            let mut covered_plaintext_end = cumulative_plaintext_size;
            let mut physical_end = cumulative_encrypted_size;
            let mut remaining_plaintext = 0_i64;
            let mut covered = false;
            for tail_part in &oi.parts[part_index..] {
                remaining_plaintext = remaining_plaintext.checked_add(tail_part.actual_size)?;
                if !covered {
                    physical_end = physical_end.checked_add(i64::try_from(tail_part.size).ok()?)?;
                    covered_plaintext_end = covered_plaintext_end.checked_add(tail_part.actual_size)?;
                    if end_plaintext < covered_plaintext_end {
                        covered = true;
                    }
                }
            }
            if !covered {
                return None;
            }
            let plaintext_skip_in_part = usize::try_from(offset - cumulative_plaintext_size).ok()?;
            return Some((
                cumulative_encrypted_size,
                physical_end.checked_sub(cumulative_encrypted_size)?,
                plaintext_skip_in_part,
                part_index,
                remaining_plaintext,
            ));
        }

        cumulative_plaintext_size = part_plaintext_end;
        cumulative_encrypted_size = cumulative_encrypted_size.checked_add(i64::try_from(part.size).ok()?)?;
    }

    None
}

/// Encrypted-range plan tuple shared by both Legacy (rio v1) build arms:
/// `(storage_offset, storage_length, decrypt_skip, plaintext_offset,
/// plaintext_length, total_plaintext_size, sequence_number, part_numbers)`.
type EncryptedRangePlan = (usize, i64, usize, usize, i64, usize, u32, Vec<usize>);

/// Range plan for a Legacy (rio v1) encrypted object
/// (https://github.com/rustfs/backlog/issues/1316 Phase A).
///
/// Eligible multipart objects seek to the covering part boundary: per-part physical
/// sizes are exact metadata facts, and the rio v1 multipart decrypt reader already
/// decrypts a stream that starts at any part boundary once it is handed the part
/// numbers from that part onward. Everything else — single-part objects, compressed
/// payloads, defective parts tables, the kill switch — keeps the conservative
/// full-object read: rio v1 encrypted blocks are variable-length, so existing
/// objects have no safe sub-part seek.
fn legacy_encrypted_range_plan(
    oi: &ObjectInfo,
    is_multipart: bool,
    is_compressed: bool,
    requested_offset: usize,
    requested_length: i64,
    full_plaintext_size: usize,
    recorded_plaintext_size: Option<i64>,
) -> Result<EncryptedRangePlan> {
    if v2_frame_seek_eligible(oi, is_multipart, is_compressed, requested_length, recorded_plaintext_size)
        && let Some(recorded_plaintext) = recorded_plaintext_size
        && let Ok(requested_offset_i64) = i64::try_from(requested_offset)
        && let Some((physical_offset, physical_length, plaintext_skip_in_frame, starting_frame, remaining_plaintext)) =
            get_v2_frame_offsets(oi, requested_offset_i64, requested_length, recorded_plaintext)
    {
        let storage_offset = usize::try_from(physical_offset)
            .map_err(|_| Error::other(format!("invalid v2 encrypted offset {physical_offset}")))?;
        let total_plaintext_size = usize::try_from(remaining_plaintext)
            .map_err(|_| Error::other(format!("invalid v2 remaining decrypted size {remaining_plaintext}")))?;
        record_encrypted_range_read_amplification(ENCRYPTED_RANGE_READ_PATH_FRAME_SEEK, physical_length, requested_length);
        return Ok((
            storage_offset,
            physical_length,
            0,
            plaintext_skip_in_frame,
            requested_length,
            total_plaintext_size,
            starting_frame,
            Vec::new(),
        ));
    }

    if legacy_encrypted_seek_eligible(oi, is_multipart, is_compressed, requested_length, recorded_plaintext_size)
        && let Ok(requested_offset) = i64::try_from(requested_offset)
        && let Some((physical_offset, physical_length, plaintext_skip_in_part, part_start_index, remaining_plaintext)) =
            get_legacy_encrypted_offsets(oi, requested_offset, requested_length)
    {
        let storage_offset = usize::try_from(physical_offset)
            .map_err(|_| Error::other(format!("invalid legacy encrypted offset {physical_offset}")))?;
        let total_plaintext_size = usize::try_from(remaining_plaintext)
            .map_err(|_| Error::other(format!("invalid legacy remaining decrypted size {remaining_plaintext}")))?;
        record_encrypted_range_read_amplification(ENCRYPTED_RANGE_READ_PATH_PART_SEEK, physical_length, requested_length);
        return Ok((
            storage_offset,
            physical_length,
            0,
            plaintext_skip_in_part,
            requested_length,
            total_plaintext_size,
            0,
            multipart_part_numbers(&oi.parts[part_start_index..]),
        ));
    }

    // Skip the metric for compressed payloads: their requested length addresses
    // the decompressed stream, so the physical/plaintext ratio would mix
    // coordinate systems and pollute the histogram.
    if !is_compressed {
        record_encrypted_range_read_amplification(ENCRYPTED_RANGE_READ_PATH_FULL, oi.size, requested_length);
    }
    Ok((
        0,
        oi.size,
        0,
        requested_offset,
        requested_length,
        full_plaintext_size,
        0,
        multipart_part_numbers(&oi.parts),
    ))
}

/// Record path and physical/plaintext read amplification for one Legacy encrypted
/// Range GET at the ReadPlan decision point.
fn record_encrypted_range_read_amplification(path: &'static str, physical_length: i64, requested_length: i64) {
    if requested_length <= 0 || physical_length < 0 {
        return;
    }
    rustfs_io_metrics::record_get_encrypted_range_read_amplification(path, physical_length as f64 / requested_length as f64);
}

pub struct PutObjReader {
    pub stream: HashReader,
}

impl Debug for PutObjReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PutObjReader").finish()
    }
}

impl PutObjReader {
    pub fn new(stream: HashReader) -> Self {
        PutObjReader { stream }
    }

    pub fn as_hash_reader(&self) -> &HashReader {
        &self.stream
    }

    pub fn from_vec(data: Vec<u8>) -> Self {
        use sha2::{Digest, Sha256};
        let content_length = data.len() as i64;
        let sha256hex = if content_length > 0 {
            Some(hex_simd::encode_to_string(Sha256::digest(&data), hex_simd::AsciiCase::Lower))
        } else {
            None
        };
        PutObjReader {
            stream: HashReader::from_stream(Cursor::new(data), content_length, content_length, None, sha256hex, false).unwrap(),
        }
    }

    pub fn from_prehashed_bytes(data: Bytes, sha256hex: Option<String>) -> std::io::Result<Self> {
        let content_length =
            i64::try_from(data.len()).map_err(|_| std::io::Error::other("prehashed object payload exceeds i64 length"))?;
        Ok(PutObjReader {
            stream: HashReader::from_stream(Cursor::new(data), content_length, content_length, None, sha256hex, false)?,
        })
    }

    pub fn size(&self) -> i64 {
        self.stream.size()
    }

    pub fn actual_size(&self) -> i64 {
        self.stream.actual_size()
    }
}

/// Provenance of a [`GetObjectReader`] with respect to the app-layer object
/// data cache hook, so the app layer can avoid repeating the cache lookup the
/// ecstore GET probe already ran after fresh metadata resolution (backlog#1121
/// / ODC-16). One hook-served GET must record exactly one lookup, not two.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GetObjectBodySource {
    /// The cache hook did not probe this read: the hook is unregistered, or the
    /// read is ineligible under the fail-closed allow-list. The app layer runs
    /// its own cache lookup, as before.
    #[default]
    Unprobed,
    /// The hook probed after fresh metadata resolution and did not serve a body
    /// (a genuine miss, or a length-defensive rejection). Its miss is
    /// authoritative, so the app layer must skip the lookup and only build a
    /// plan to fill.
    HookMissed,
    /// `buffered_body` is exactly the body the hook served from the cache. The
    /// app layer serves it directly as the object-data-cache source, with no
    /// second lookup and no re-fill.
    HookServed,
}

pub struct GetObjectReader {
    pub stream: Box<dyn AsyncRead + Unpin + Send + Sync>,
    pub object_info: ObjectInfo,
    pub buffered_body: Option<Bytes>,
    /// Cache-hook provenance; defaults to [`GetObjectBodySource::Unprobed`] for
    /// every reader that never passed through the app-layer cache probe.
    pub body_source: GetObjectBodySource,
}

impl GetObjectReader {
    /// Builds a fully materialized reader from a cache-coordinated body.
    pub fn from_cache_body(mut object_info: ObjectInfo, body: Bytes) -> Result<Self> {
        object_info.size = i64::try_from(body.len()).map_err(|_| Error::other("cached GET body length exceeds i64::MAX"))?;
        Ok(Self {
            stream: Box::new(std::io::Cursor::new(body.clone())),
            object_info,
            buffered_body: Some(body),
            body_source: GetObjectBodySource::HookServed,
        })
    }

    /// True when `buffered_body` is the body the cache hook served. The app
    /// layer serves it as the object-data-cache source without a second lookup.
    pub fn is_cache_hook_served(&self) -> bool {
        matches!(self.body_source, GetObjectBodySource::HookServed)
    }

    /// True when the cache hook probed this read (whether it served a body or
    /// missed). The app layer must not repeat the lookup in either case.
    pub fn cache_hook_probed(&self) -> bool {
        !matches!(self.body_source, GetObjectBodySource::Unprobed)
    }
}

enum ReadTransform {
    // Written but never read by production code: the enclosing struct already
    // carries the same pair as `storage_offset`/`storage_length`. They survive
    // as the read plan's test-visible record — four tests assert them by
    // literal pattern (`Plain { visible_offset: 6, visible_length: 4 }`), which
    // rustc does not count as a read.
    #[allow(
        dead_code,
        reason = "asserted by literal pattern in this file's read-plan tests (backlog#1823)"
    )]
    Plain { visible_offset: usize, visible_length: i64 },
    Compressed {
        algorithm: CompressionAlgorithm,
        backend: crate::io_support::rio::ReadCompressionBackend,
        decompressed_offset: usize,
        decompressed_length: i64,
        total_plaintext_size: usize,
    },
    Encrypted {
        material: ReadEncryptionMaterial,
        is_multipart: bool,
        part_numbers: Vec<usize>,
        sequence_number: u32,
        decrypt_skip: usize,
        plaintext_offset: usize,
        plaintext_length: i64,
        total_plaintext_size: usize,
        compression: Option<(CompressionAlgorithm, crate::io_support::rio::ReadCompressionBackend)>,
    },
}

/// How an object's stored bytes must be fetched and transformed to serve a
/// request.
///
/// Public so callers that fetch the stored bytes from somewhere other than the
/// local erasure set — the remote-tier read path — can position their own fetch
/// with [`ReadPlan::storage_offset`] / [`ReadPlan::storage_length`] and then
/// hand the resulting stream to [`ReadPlan::into_object_reader`], instead of
/// reimplementing the transform decisions (rustfs/rustfs#6025).
pub struct ReadPlan {
    storage_offset: usize,
    storage_length: i64,
    object_size: i64,
    transform: ReadTransform,
}

impl ReadPlan {
    /// Byte offset into the object's **stored** bytes where the fetch must
    /// start. Encrypted and compressed objects address their storage in a
    /// different coordinate system than the plaintext range the caller asked
    /// for, which is exactly the distinction this plan resolves.
    pub fn storage_offset(&self) -> usize {
        self.storage_offset
    }

    /// Number of **stored** bytes the fetch must deliver, in the same
    /// coordinate system as [`Self::storage_offset`].
    pub fn storage_length(&self) -> i64 {
        self.storage_length
    }

    /// Build the plan for a request without consuming a stream, so a caller
    /// that has to issue its own positioned fetch can read the offsets first.
    pub async fn build_for_request(
        rs: Option<HTTPRangeSpec>,
        oi: &ObjectInfo,
        opts: &ObjectOptions,
        h: &HeaderMap<HeaderValue>,
        resolver: Option<&dyn ObjectEncryptionResolver>,
    ) -> Result<Self> {
        Self::build_with_resolver(rs, oi, opts, h, resolver).await
    }

    /// Wrap `reader` — the stored bytes this plan asked for, already positioned
    /// at [`Self::storage_offset`] — in the transforms that turn them into the
    /// bytes the caller requested.
    pub fn into_object_reader(
        self,
        reader: Box<dyn AsyncRead + Unpin + Send + Sync>,
        oi: &ObjectInfo,
    ) -> Result<GetObjectReader> {
        self.into_reader(reader, oi).map(|(reader, _, _)| reader)
    }

    #[cfg(test)]
    async fn build(rs: Option<HTTPRangeSpec>, oi: &ObjectInfo, opts: &ObjectOptions, h: &HeaderMap<HeaderValue>) -> Result<Self> {
        Self::build_with_resolver(rs, oi, opts, h, Some(&tests::TEST_RESOLVER)).await
    }

    async fn build_with_resolver(
        rs: Option<HTTPRangeSpec>,
        oi: &ObjectInfo,
        opts: &ObjectOptions,
        h: &HeaderMap<HeaderValue>,
        resolver: Option<&dyn ObjectEncryptionResolver>,
    ) -> Result<Self> {
        let mut rs = rs;
        // A part number addresses the object's PLAINTEXT bytes. A restore read
        // serves the stored representation instead (see
        // [`restore_request_active`]), where that synthesized range would be
        // reinterpreted as a storage range and truncate an encrypted or
        // compressed payload by exactly its encoding overhead — the copy-back
        // then fails its length check partway through
        // (rustfs/rustfs#6025). An explicit caller range is already in storage
        // coordinates on that path and is still honored.
        if let Some(part_number) = opts.part_number
            && rs.is_none()
            && !restore_request_active(opts)
        {
            rs = http_range_spec_from_object_info(oi, part_number);
        }

        if opts.raw_data_movement_read {
            let (visible_offset, visible_length) = if let Some(rs) = rs {
                rs.get_offset_length(oi.size)?
            } else {
                (0, oi.size)
            };

            return Ok(Self {
                storage_offset: visible_offset,
                storage_length: visible_length,
                object_size: oi.size,
                transform: ReadTransform::Plain {
                    visible_offset,
                    visible_length,
                },
            });
        }

        let mut is_encrypted = oi.is_encrypted();
        let (algo, compression_backend, mut is_compressed) = oi.compression_read_plan()?;

        if restore_request_active(opts) {
            is_encrypted = false;
            is_compressed = false;
        }

        if is_compressed && !is_encrypted {
            let actual_size = oi.get_actual_size()?;
            let (storage_offset, storage_length, decompressed_offset, decompressed_length) = if let Some(rs) = rs {
                let (req_off, req_length) = rs.get_offset_length(actual_size)?;
                let (physical_off, decompressed_skip, _, _, _) = get_compressed_offsets(oi, req_off as i64);
                let storage_offset = usize::try_from(physical_off)
                    .map_err(|_| Error::other(format!("invalid compressed offset {physical_off}")))?;
                (storage_offset, oi.size - physical_off, decompressed_skip as usize, req_length)
            } else {
                (0, oi.size, 0, actual_size)
            };

            let total_plaintext_size =
                usize::try_from(actual_size).map_err(|_| Error::other(format!("invalid decompressed size {actual_size}")))?;

            return Ok(Self {
                storage_offset,
                storage_length,
                object_size: decompressed_length,
                transform: ReadTransform::Compressed {
                    algorithm: algo,
                    backend: compression_backend,
                    decompressed_offset,
                    decompressed_length,
                    total_plaintext_size,
                },
            });
        }

        if is_encrypted {
            let resolver = resolver.ok_or_else(|| Error::other("object encryption resolver is unavailable"))?;
            let resolved = resolver
                .resolve_read_material(ReadEncryptionRequest {
                    bucket: &oi.bucket,
                    object: &oi.name,
                    metadata: &oi.user_defined,
                    headers: h,
                })
                .await
                .map_err(Error::other)?
                .ok_or_else(|| {
                    // The resolver saw no encryption it recognizes, yet the
                    // object's markers say it is encrypted. Keep failing closed,
                    // but as a typed, non-retryable error: the condition is a
                    // permanent property of the stored metadata, not a fault a
                    // retry can fix.
                    Error::other(EncryptionResolutionError::new(
                        EncryptionResolutionErrorKind::InvalidMetadata,
                        "object is marked encrypted, but no decryption material could be resolved from its metadata; \
                         the encryption metadata is incomplete or in a format this server cannot read",
                    ))
                })?;
            let material = resolved;
            #[cfg(feature = "rio-v2")]
            let uses_legacy_encryption = matches!(material.mode, ReadEncryptionMode::Direct { .. });
            let is_multipart = is_multipart_encrypted_object(&oi.parts, oi.etag.as_deref());
            let recorded_plaintext_size = oi.encryption_original_size()?;
            let plaintext_size = encrypted_plaintext_size(oi, is_multipart, is_compressed, recorded_plaintext_size)?;
            let full_plaintext_size =
                usize::try_from(plaintext_size).map_err(|_| Error::other(format!("invalid decrypted size {plaintext_size}")))?;
            let (
                storage_offset,
                storage_length,
                decrypt_skip,
                plaintext_offset,
                plaintext_length,
                total_plaintext_size,
                sequence_number,
                part_numbers,
            ) = if let Some(rs) = rs {
                let (requested_offset, requested_length) = rs.get_offset_length(plaintext_size)?;
                #[cfg(feature = "rio-v2")]
                {
                    if uses_legacy_encryption {
                        legacy_encrypted_range_plan(
                            oi,
                            is_multipart,
                            is_compressed,
                            requested_offset,
                            requested_length,
                            full_plaintext_size,
                            recorded_plaintext_size,
                        )?
                    } else if is_compressed {
                        let (physical_off, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
                            get_compressed_offsets(oi, requested_offset as i64);
                        (
                            usize::try_from(physical_off)
                                .map_err(|_| Error::other(format!("invalid encrypted compressed offset {physical_off}")))?,
                            oi.size - physical_off,
                            usize::try_from(decrypt_skip)
                                .map_err(|_| Error::other(format!("invalid decrypt skip {decrypt_skip}")))?,
                            usize::try_from(decompressed_skip)
                                .map_err(|_| Error::other(format!("invalid decompressed skip {decompressed_skip}")))?,
                            requested_length,
                            full_plaintext_size,
                            u32::try_from(seq_num)
                                .map_err(|_| Error::other(format!("invalid DARE sequence number {seq_num}")))?,
                            multipart_part_numbers(&oi.parts[first_part_idx..]),
                        )
                    } else {
                        let (encrypted_offset, plaintext_skip, part_start_index, sequence_number, remaining_plaintext_size) =
                            get_encrypted_offsets(oi, requested_offset as i64)?;
                        let total_plaintext_size = usize::try_from(remaining_plaintext_size)
                            .map_err(|_| Error::other(format!("invalid remaining decrypted size {remaining_plaintext_size}")))?;
                        (
                            usize::try_from(encrypted_offset)
                                .map_err(|_| Error::other(format!("invalid encrypted offset {encrypted_offset}")))?,
                            oi.size - encrypted_offset,
                            0,
                            plaintext_skip,
                            requested_length,
                            total_plaintext_size,
                            sequence_number,
                            multipart_part_numbers(&oi.parts[part_start_index..]),
                        )
                    }
                }
                #[cfg(not(feature = "rio-v2"))]
                {
                    legacy_encrypted_range_plan(
                        oi,
                        is_multipart,
                        is_compressed,
                        requested_offset,
                        requested_length,
                        full_plaintext_size,
                        recorded_plaintext_size,
                    )?
                }
            } else {
                (
                    0,
                    oi.size,
                    0,
                    0,
                    plaintext_size,
                    full_plaintext_size,
                    0,
                    multipart_part_numbers(&oi.parts),
                )
            };

            return Ok(Self {
                storage_offset,
                storage_length,
                object_size: plaintext_length,
                transform: ReadTransform::Encrypted {
                    material,
                    is_multipart,
                    part_numbers,
                    sequence_number,
                    decrypt_skip,
                    plaintext_offset,
                    plaintext_length,
                    total_plaintext_size,
                    compression: is_compressed.then_some((algo, compression_backend)),
                },
            });
        }

        let (visible_offset, visible_length) = if let Some(rs) = rs {
            rs.get_offset_length(oi.size)?
        } else {
            (0, oi.size)
        };

        Ok(Self {
            storage_offset: visible_offset,
            storage_length: visible_length,
            object_size: oi.size,
            transform: ReadTransform::Plain {
                visible_offset,
                visible_length,
            },
        })
    }

    fn into_reader(
        self,
        reader: Box<dyn AsyncRead + Unpin + Send + Sync>,
        oi: &ObjectInfo,
    ) -> Result<(GetObjectReader, usize, i64)> {
        match self.transform {
            ReadTransform::Plain { .. } => Ok((
                GetObjectReader {
                    stream: reader,
                    object_info: oi.clone(),
                    buffered_body: None,
                    body_source: GetObjectBodySource::Unprobed,
                },
                self.storage_offset,
                self.storage_length,
            )),
            ReadTransform::Compressed {
                algorithm,
                backend,
                decompressed_offset,
                decompressed_length,
                total_plaintext_size,
            } => {
                let dec_reader = crate::io_support::rio::decompression_reader(reader, algorithm, backend);
                #[cfg(feature = "rio-v2")]
                let dec_reader = StreamConsumer::new(dec_reader);
                let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decompressed_offset > 0
                    || decompressed_length != total_plaintext_size as i64
                {
                    #[cfg(feature = "rio-v2")]
                    let ranged_result = RangedDecompressReader::new_draining(
                        dec_reader,
                        decompressed_offset,
                        decompressed_length,
                        total_plaintext_size,
                    );
                    #[cfg(not(feature = "rio-v2"))]
                    let ranged_result =
                        RangedDecompressReader::new(dec_reader, decompressed_offset, decompressed_length, total_plaintext_size);

                    match ranged_result {
                        Ok(ranged_reader) => {
                            tracing::debug!(
                                "Successfully created RangedDecompressReader for offset={}, length={}",
                                decompressed_offset,
                                decompressed_length
                            );
                            Box::new(ranged_reader)
                        }
                        Err(e) => {
                            tracing::error!("RangedDecompressReader failed with invalid range parameters: {}", e);
                            return Err(e);
                        }
                    }
                } else {
                    Box::new(HardLimitReader::new(dec_reader, decompressed_length))
                };

                let mut object_info = oi.clone();
                object_info.size = self.object_size;

                Ok((
                    GetObjectReader {
                        stream: final_reader,
                        object_info,
                        buffered_body: None,
                        body_source: GetObjectBodySource::Unprobed,
                    },
                    self.storage_offset,
                    self.storage_length,
                ))
            }
            ReadTransform::Encrypted {
                material,
                is_multipart,
                part_numbers,
                sequence_number,
                decrypt_skip,
                plaintext_offset,
                plaintext_length,
                total_plaintext_size,
                compression,
            } => {
                #[cfg(not(feature = "rio-v2"))]
                let _ = sequence_number;
                let decrypted_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if is_multipart {
                    match material.mode {
                        ReadEncryptionMode::Object => crate::io_support::rio::decrypt_multipart_reader_with_object_key(
                            reader,
                            material.key_bytes,
                            part_numbers,
                            sequence_number,
                        ),
                        ReadEncryptionMode::Direct { base_nonce } => crate::io_support::rio::decrypt_multipart_reader(
                            reader,
                            material.key_bytes,
                            base_nonce,
                            part_numbers,
                            crate::io_support::rio::ReadEncryptionBackend::Legacy,
                            sequence_number,
                        ),
                    }
                } else {
                    match material.mode {
                        ReadEncryptionMode::Object => {
                            crate::io_support::rio::decrypt_reader_with_object_key(reader, material.key_bytes, sequence_number)
                        }
                        ReadEncryptionMode::Direct { base_nonce } => crate::io_support::rio::decrypt_reader(
                            reader,
                            material.key_bytes,
                            base_nonce,
                            crate::io_support::rio::ReadEncryptionBackend::Legacy,
                            sequence_number,
                        ),
                    }
                };
                let decrypted_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decrypt_skip > 0 {
                    Box::new(SkipReader::new(decrypted_reader, decrypt_skip))
                } else {
                    decrypted_reader
                };
                let total_plaintext_size_i64 = i64::try_from(total_plaintext_size)
                    .map_err(|_| Error::other(format!("invalid plaintext size {total_plaintext_size}")))?;

                let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> =
                    if let Some((algo, compression_backend)) = compression {
                        let decompressed_reader =
                            crate::io_support::rio::decompression_reader(decrypted_reader, algo, compression_backend);
                        #[cfg(feature = "rio-v2")]
                        let decompressed_reader = StreamConsumer::new(decompressed_reader);
                        if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
                            #[cfg(feature = "rio-v2")]
                            let ranged_reader = RangedDecompressReader::new_draining(
                                decompressed_reader,
                                plaintext_offset,
                                plaintext_length,
                                total_plaintext_size,
                            )?;
                            #[cfg(not(feature = "rio-v2"))]
                            let ranged_reader = RangedDecompressReader::new(
                                decompressed_reader,
                                plaintext_offset,
                                plaintext_length,
                                total_plaintext_size,
                            )?;
                            Box::new(ranged_reader)
                        } else {
                            Box::new(HardLimitReader::new(decompressed_reader, total_plaintext_size_i64))
                        }
                    } else if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
                        Box::new(RangedDecompressReader::new(
                            decrypted_reader,
                            plaintext_offset,
                            plaintext_length,
                            total_plaintext_size,
                        )?)
                    } else {
                        Box::new(HardLimitReader::new(decrypted_reader, total_plaintext_size_i64))
                    };

                let mut object_info = oi.clone();
                object_info.size = self.object_size;

                Ok((
                    GetObjectReader {
                        stream: final_reader,
                        object_info,
                        buffered_body: None,
                        body_source: GetObjectBodySource::Unprobed,
                    },
                    self.storage_offset,
                    self.storage_length,
                ))
            }
        }
    }
}

impl GetObjectReader {
    #[cfg(test)]
    pub(crate) async fn new(
        reader: Box<dyn AsyncRead + Unpin + Send + Sync>,
        rs: Option<HTTPRangeSpec>,
        oi: &ObjectInfo,
        opts: &ObjectOptions,
        h: &HeaderMap<HeaderValue>,
    ) -> Result<(Self, usize, i64)> {
        Self::new_with_resolver(reader, rs, oi, opts, h, Some(&tests::TEST_RESOLVER)).await
    }

    pub async fn new_with_resolver(
        reader: Box<dyn AsyncRead + Unpin + Send + Sync>,
        rs: Option<HTTPRangeSpec>,
        oi: &ObjectInfo,
        opts: &ObjectOptions,
        h: &HeaderMap<HeaderValue>,
        resolver: Option<&dyn ObjectEncryptionResolver>,
    ) -> Result<(Self, usize, i64)> {
        ReadPlan::build_with_resolver(rs, oi, opts, h, resolver)
            .await?
            .into_reader(reader, oi)
    }
    #[hotpath::measure(impl_type = "GetObjectReader")]
    pub async fn read_all(&mut self) -> Result<Vec<u8>> {
        let mut data = Vec::new();
        self.stream.read_to_end(&mut data).await?;

        // while let Some(x) = self.stream.next().await {
        //     let buf = match x {
        //         Ok(res) => res,
        //         Err(e) => return Err(Error::other(e.to_string())),
        //     };
        //     data.extend_from_slice(buf.as_ref());
        // }

        Ok(data)
    }
}

impl AsyncRead for GetObjectReader {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.stream).poll_read(cx, buf)
    }
}

#[derive(Debug)]
struct SkipReader<R> {
    inner: R,
    bytes_to_skip: usize,
    bytes_skipped: usize,
    scratch: Box<[MaybeUninit<u8>]>,
}

impl<R: AsyncRead + Unpin + Send + Sync> SkipReader<R> {
    fn new(inner: R, bytes_to_skip: usize) -> Self {
        Self {
            inner,
            bytes_to_skip,
            bytes_skipped: 0,
            scratch: Box::<[u8]>::new_uninit_slice(8192),
        }
    }
}

impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SkipReader<R> {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        let this = self.as_mut().get_mut();

        while this.bytes_skipped < this.bytes_to_skip {
            let remaining = this.bytes_to_skip - this.bytes_skipped;
            let scratch_len = remaining.min(this.scratch.len());
            let mut scratch_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
            match Pin::new(&mut this.inner).poll_read(cx, &mut scratch_buf) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
                Poll::Ready(Ok(())) => {
                    let n = scratch_buf.filled().len();
                    if n == 0 {
                        return Poll::Ready(Err(std::io::Error::new(
                            std::io::ErrorKind::UnexpectedEof,
                            format!("unexpected EOF while skipping {} bytes from decrypted stream", this.bytes_to_skip),
                        )));
                    }
                    this.bytes_skipped += n;
                }
            }
        }

        Pin::new(&mut this.inner).poll_read(cx, buf)
    }
}

/// A streaming decompression reader that supports range requests by skipping data in the decompressed stream.
/// This implementation acknowledges that compressed streams (like LZ4) must be decompressed sequentially
/// from the beginning, so it streams and discards data until reaching the target offset.
#[derive(Debug)]
pub struct RangedDecompressReader<R: AsyncRead + Unpin + Send + Sync + 'static> {
    inner: Option<R>,
    target_offset: usize,
    target_length: usize,
    current_offset: usize,
    bytes_returned: usize,
    scratch: Box<[MaybeUninit<u8>]>,
    drain_on_done: bool,
    drain_task: Option<tokio::task::JoinHandle<()>>,
}

impl<R: AsyncRead + Unpin + Send + Sync + 'static> RangedDecompressReader<R> {
    pub fn new(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
        Self::new_with_drain(inner, offset, length, total_size, false)
    }

    pub fn new_draining(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
        Self::new_with_drain(inner, offset, length, total_size, true)
    }

    fn new_with_drain(inner: R, offset: usize, length: i64, total_size: usize, drain_on_done: bool) -> Result<Self> {
        // Validate the range request
        if offset >= total_size {
            tracing::debug!("Range offset {} exceeds total size {}", offset, total_size);
            return Err(Error::InvalidRangeSpec("Range offset exceeds file size".to_string()));
        }

        // Adjust length if it extends beyond file end
        let actual_length = std::cmp::min(length as usize, total_size - offset);

        tracing::debug!(
            "Creating RangedDecompressReader: offset={}, length={}, total_size={}, actual_length={}",
            offset,
            length,
            total_size,
            actual_length
        );

        Ok(Self {
            inner: Some(inner),
            target_offset: offset,
            target_length: actual_length,
            current_offset: 0,
            bytes_returned: 0,
            scratch: Box::<[u8]>::new_uninit_slice(8192),
            drain_on_done,
            drain_task: None,
        })
    }

    fn start_drain(&mut self) {
        if !self.drain_on_done || self.drain_task.is_some() {
            return;
        }

        let Some(mut inner) = self.inner.take() else {
            return;
        };

        self.drain_task = Some(tokio::spawn(async move {
            let mut buf = [0u8; 8192];
            loop {
                match inner.read(&mut buf).await {
                    Ok(0) => break,
                    Ok(_) => continue,
                    Err(_) => break,
                }
            }
        }));
    }
}

impl<R: AsyncRead + Unpin + Send + Sync + 'static> AsyncRead for RangedDecompressReader<R> {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        use std::pin::Pin;
        use std::task::Poll;
        use tokio::io::ReadBuf;

        let this = self.as_mut().get_mut();

        loop {
            // If we've returned all the bytes we need, return EOF
            if this.bytes_returned >= this.target_length {
                this.start_drain();
                return Poll::Ready(Ok(()));
            }

            // Read from the inner stream
            let buf_capacity = buf.remaining();
            if buf_capacity == 0 {
                return Poll::Ready(Ok(()));
            }

            let scratch_len = std::cmp::min(this.scratch.len(), std::cmp::max(buf_capacity, 1));
            let mut temp_read_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);

            let Some(inner) = this.inner.as_mut() else {
                return Poll::Ready(Ok(()));
            };

            match Pin::new(inner).poll_read(cx, &mut temp_read_buf) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                Poll::Ready(Ok(())) => {
                    let n = temp_read_buf.filled().len();
                    if n == 0 {
                        // EOF from inner stream
                        if this.current_offset < this.target_offset {
                            // We haven't reached the target offset yet - this is an error
                            return Poll::Ready(Err(std::io::Error::new(
                                std::io::ErrorKind::UnexpectedEof,
                                format!(
                                    "Unexpected EOF: only read {} bytes, target offset is {}",
                                    this.current_offset, this.target_offset
                                ),
                            )));
                        }
                        // Normal EOF after reaching target
                        return Poll::Ready(Ok(()));
                    }

                    // Update current position
                    let old_offset = this.current_offset;
                    this.current_offset += n;

                    // Check if we're still in the skip phase
                    if old_offset < this.target_offset {
                        // We're still skipping data
                        let skip_end = std::cmp::min(this.current_offset, this.target_offset);
                        let bytes_to_skip_in_this_read = skip_end - old_offset;

                        if this.current_offset <= this.target_offset {
                            // All data in this read should be skipped
                            tracing::trace!("Skipping {} bytes at offset {}", n, old_offset);
                            // Continue reading in the loop instead of recursive call
                            continue;
                        } else {
                            // Partial skip: some data should be returned
                            let data_start_in_buffer = bytes_to_skip_in_this_read;
                            let available_data = n - data_start_in_buffer;
                            let bytes_to_return = std::cmp::min(
                                available_data,
                                std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned),
                            );

                            if bytes_to_return > 0 {
                                let data_slice =
                                    &temp_read_buf.filled()[data_start_in_buffer..data_start_in_buffer + bytes_to_return];
                                buf.put_slice(data_slice);
                                this.bytes_returned += bytes_to_return;

                                tracing::trace!(
                                    "Skipped {} bytes, returned {} bytes at offset {}",
                                    bytes_to_skip_in_this_read,
                                    bytes_to_return,
                                    old_offset
                                );
                            }
                            return Poll::Ready(Ok(()));
                        }
                    } else {
                        // We're in the data return phase
                        let bytes_to_return =
                            std::cmp::min(n, std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned));

                        if bytes_to_return > 0 {
                            buf.put_slice(&temp_read_buf.filled()[..bytes_to_return]);
                            this.bytes_returned += bytes_to_return;

                            tracing::trace!("Returned {} bytes at offset {}", bytes_to_return, old_offset);
                        }
                        return Poll::Ready(Ok(()));
                    }
                }
            }
        }
    }
}

impl<R: AsyncRead + Unpin + Send + Sync + 'static> Drop for RangedDecompressReader<R> {
    fn drop(&mut self) {
        if self.bytes_returned >= self.target_length {
            self.start_drain();
        }
    }
}

/// A wrapper that ensures the inner stream is fully consumed even if the outer reader stops early.
/// This prevents broken pipe errors in erasure coding scenarios where the writer expects
/// the full stream to be consumed.
pub struct StreamConsumer<R: AsyncRead + Unpin + Send + 'static> {
    inner: Option<R>,
    consumer_task: Option<tokio::task::JoinHandle<()>>,
}

impl<R: AsyncRead + Unpin + Send + 'static> StreamConsumer<R> {
    pub fn new(inner: R) -> Self {
        Self {
            inner: Some(inner),
            consumer_task: None,
        }
    }

    fn ensure_consumer_started(&mut self) {
        if self.consumer_task.is_none() && self.inner.is_some() {
            let mut inner = self.inner.take().unwrap();
            let task = tokio::spawn(async move {
                let mut buf = [0u8; 8192];
                loop {
                    match inner.read(&mut buf).await {
                        Ok(0) => break,    // EOF
                        Ok(_) => continue, // Keep consuming
                        Err(_) => break,   // Error, stop consuming
                    }
                }
            });
            self.consumer_task = Some(task);
        }
    }
}

impl<R: AsyncRead + Unpin + Send + 'static> AsyncRead for StreamConsumer<R> {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        use std::pin::Pin;
        use std::task::Poll;

        if let Some(ref mut inner) = self.inner {
            Pin::new(inner).poll_read(cx, buf)
        } else {
            Poll::Ready(Ok(())) // EOF
        }
    }
}

impl<R: AsyncRead + Unpin + Send + 'static> Drop for StreamConsumer<R> {
    fn drop(&mut self) {
        self.ensure_consumer_started();
    }
}

fn encrypted_plaintext_size(
    oi: &ObjectInfo,
    is_multipart: bool,
    is_compressed: bool,
    recorded_plaintext_size: Option<i64>,
) -> Result<i64> {
    if is_compressed {
        return oi.get_actual_size().map_err(Into::into);
    }

    if is_multipart && recorded_plaintext_size.is_none() {
        return Ok(legacy_part_layout_totals(&oi.parts)
            .map(|(_, plaintext_size)| plaintext_size)
            .unwrap_or(oi.size));
    }

    Ok(recorded_plaintext_size.unwrap_or(oi.size))
}

fn is_multipart_encrypted_object(parts: &[ObjectPartInfo], etag: Option<&str>) -> bool {
    if parts.len() > 1 {
        return true;
    }

    etag.map(|etag| etag.trim_matches('"').len() != 32).unwrap_or(false)
}

fn multipart_part_numbers(parts: &[ObjectPartInfo]) -> Vec<usize> {
    parts.iter().map(|part| part.number).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64_simd::STANDARD as BASE64_STANDARD;
    use md5::{Digest, Md5};
    use rustfs_utils::http::{SSEC_ALGORITHM_HEADER, SSEC_KEY_MD5_HEADER};
    use std::collections::HashMap;
    use std::io::Cursor;
    use temp_env::async_with_vars;
    use tokio::io::AsyncReadExt;

    #[derive(Debug)]
    struct PendingPartialReader {
        data: &'static [u8],
        position: usize,
        pending: bool,
    }

    impl PendingPartialReader {
        fn new(data: &'static [u8]) -> Self {
            Self {
                data,
                position: 0,
                pending: true,
            }
        }
    }

    impl AsyncRead for PendingPartialReader {
        fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
            if self.pending {
                self.pending = false;
                cx.waker().wake_by_ref();
                return Poll::Pending;
            }
            if self.position == self.data.len() {
                return Poll::Ready(Ok(()));
            }

            let length = buf.remaining().min(3).min(self.data.len() - self.position);
            let end = self.position + length;
            buf.put_slice(&self.data[self.position..end]);
            self.position = end;
            self.pending = true;
            Poll::Ready(Ok(()))
        }
    }

    const TEST_DIRECT_KEY_HEADER: &str = "x-rustfs-test-direct-key";
    const TEST_OBJECT_KEY_HEADER: &str = "x-rustfs-test-object-key";
    const TEST_NONCE_HEADER: &str = "x-rustfs-test-nonce";

    pub(super) static TEST_RESOLVER: TestObjectEncryptionResolver = TestObjectEncryptionResolver;

    pub(super) struct TestObjectEncryptionResolver;

    #[async_trait::async_trait]
    impl ObjectEncryptionResolver for TestObjectEncryptionResolver {
        async fn resolve_read_material(
            &self,
            request: ReadEncryptionRequest<'_>,
        ) -> std::result::Result<Option<ReadEncryptionMaterial>, EncryptionResolutionError> {
            if let Some(encoded) = request.metadata.get(TEST_OBJECT_KEY_HEADER) {
                let decoded = BASE64_STANDARD.decode_to_vec(encoded).map_err(|_| {
                    EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidMetadata, "invalid test object key")
                })?;
                let key_bytes = decoded.try_into().map_err(|_| {
                    EncryptionResolutionError::new(
                        EncryptionResolutionErrorKind::InvalidMetadata,
                        "invalid test object key length",
                    )
                })?;
                return Ok(Some(ReadEncryptionMaterial {
                    key_bytes,
                    mode: ReadEncryptionMode::Object,
                }));
            }

            let encoded = request
                .headers
                .get(TEST_DIRECT_KEY_HEADER)
                .ok_or_else(|| {
                    EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidRequest, "missing test direct key")
                })?
                .to_str()
                .map_err(|_| {
                    EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidRequest, "invalid test encryption key")
                })?;
            let decoded = BASE64_STANDARD.decode_to_vec(encoded).map_err(|_| {
                EncryptionResolutionError::new(EncryptionResolutionErrorKind::InvalidRequest, "invalid test encryption key")
            })?;
            let key_bytes = decoded.try_into().map_err(|_| {
                EncryptionResolutionError::new(
                    EncryptionResolutionErrorKind::InvalidRequest,
                    "invalid test encryption key length",
                )
            })?;
            let base_nonce = request
                .metadata
                .get(TEST_NONCE_HEADER)
                .and_then(|encoded| BASE64_STANDARD.decode_to_vec(encoded).ok())
                .and_then(|bytes| bytes.try_into().ok())
                .unwrap_or_else(|| fixture_nonce(request.bucket, request.object));
            Ok(Some(ReadEncryptionMaterial {
                key_bytes,
                mode: ReadEncryptionMode::Direct { base_nonce },
            }))
        }
    }

    fn md5_bytes(data: impl AsRef<[u8]>) -> [u8; 16] {
        let digest = Md5::digest(data.as_ref());
        let mut bytes = [0u8; 16];
        bytes.copy_from_slice(&digest);
        bytes
    }

    fn fixture_nonce(bucket: &str, object: &str) -> [u8; 12] {
        let digest = md5_bytes(format!("{bucket}-{object}"));
        let mut nonce = [0; 12];
        nonce.copy_from_slice(&digest[..12]);
        nonce
    }

    fn ssec_headers_from_key(key_bytes: [u8; 32]) -> HeaderMap<HeaderValue> {
        let mut headers = HeaderMap::new();
        headers.insert(
            TEST_DIRECT_KEY_HEADER,
            HeaderValue::from_str(&BASE64_STANDARD.encode_to_string(key_bytes)).expect("test key header is valid"),
        );
        headers
    }

    #[tokio::test]
    async fn cache_body_uses_plaintext_length_for_compressed_metadata() {
        let mut metadata = HashMap::new();
        rustfs_utils::http::insert_str(
            &mut metadata,
            rustfs_utils::http::SUFFIX_COMPRESSION,
            "klauspost/compress/s2".to_string(),
        );
        let object_info = ObjectInfo {
            size: 3,
            actual_size: 11,
            user_defined: Arc::new(metadata),
            ..Default::default()
        };
        assert!(object_info.is_compressed());

        let body = Bytes::from_static(b"hello world");
        let mut reader =
            GetObjectReader::from_cache_body(object_info, body.clone()).expect("cache body length must fit in object metadata");

        assert_eq!(reader.body_source, GetObjectBodySource::HookServed);
        assert_eq!(reader.buffered_body.as_ref(), Some(&body));
        assert_eq!(reader.object_info.size, 11);
        assert_eq!(reader.object_info.actual_size, 11);
        assert!(reader.object_info.is_compressed());
        let mut restored = Vec::new();
        reader
            .stream
            .read_to_end(&mut restored)
            .await
            .expect("cache body should stream");
        assert_eq!(restored, body);
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader() {
        // Create test data
        let original_data = b"Hello, World! This is a test for range requests on compressed data.";

        // For this test, we'll simulate using the original data directly as "decompressed"
        let cursor = Cursor::new(original_data.to_vec());

        // Test reading a range from the middle
        let mut ranged_reader = RangedDecompressReader::new(cursor, 7, 5, original_data.len()).unwrap();

        let mut result = Vec::new();
        ranged_reader.read_to_end(&mut result).await.unwrap();

        // Should read "World" (5 bytes starting from position 7)
        assert_eq!(result, b"World");
    }

    #[tokio::test]
    async fn uninitialized_scratch_preserves_partial_pending_and_eof_reads() {
        let mut skipped = SkipReader::new(PendingPartialReader::new(b"0123456789abcdef"), 5);
        let mut skipped_output = Vec::new();
        skipped
            .read_to_end(&mut skipped_output)
            .await
            .expect("skip reader should survive partial pending reads through EOF");
        assert_eq!(skipped_output, b"56789abcdef");

        let mut ranged = RangedDecompressReader::new(PendingPartialReader::new(b"0123456789abcdef"), 5, 7, 16)
            .expect("valid range should construct");
        let mut ranged_output = Vec::new();
        ranged
            .read_to_end(&mut ranged_output)
            .await
            .expect("range reader should survive partial pending reads through EOF");
        assert_eq!(ranged_output, b"56789ab");
    }

    #[tokio::test]
    async fn uninitialized_skip_scratch_reports_early_eof() {
        let mut reader = SkipReader::new(PendingPartialReader::new(b"short"), 6);
        let error = reader
            .read_to_end(&mut Vec::new())
            .await
            .expect_err("EOF before the skip boundary must remain visible");
        assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_from_start() {
        let original_data = b"Hello, World! This is a test.";
        let cursor = Cursor::new(original_data.to_vec());

        let mut ranged_reader = RangedDecompressReader::new(cursor, 0, 5, original_data.len()).unwrap();

        let mut result = Vec::new();
        ranged_reader.read_to_end(&mut result).await.unwrap();

        // Should read "Hello" (5 bytes from the start)
        assert_eq!(result, b"Hello");
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_to_end() {
        let original_data = b"Hello, World!";
        let cursor = Cursor::new(original_data.to_vec());

        let mut ranged_reader = RangedDecompressReader::new(cursor, 7, 6, original_data.len()).unwrap();

        let mut result = Vec::new();
        ranged_reader.read_to_end(&mut result).await.unwrap();

        // Should read "World!" (6 bytes starting from position 7)
        assert_eq!(result, b"World!");
    }

    #[tokio::test]
    async fn test_http_range_spec_with_compressed_data() {
        // Test that HTTPRangeSpec::get_offset_length works correctly
        let range_spec = HTTPRangeSpec {
            is_suffix_length: false,
            start: 5,
            end: 14, // inclusive
        };

        let total_size = 100i64;
        let (offset, length) = range_spec.get_offset_length(total_size).unwrap();

        assert_eq!(offset, 5);
        assert_eq!(length, 10); // end - start + 1 = 14 - 5 + 1 = 10
    }

    #[test]
    fn test_http_range_spec_suffix_positive_start() {
        let range_spec = HTTPRangeSpec {
            is_suffix_length: true,
            start: 5,
            end: -1,
        };

        let (offset, length) = range_spec.get_offset_length(20).unwrap();
        assert_eq!(offset, 15);
        assert_eq!(length, 5);
    }

    #[test]
    fn test_http_range_spec_suffix_negative_start() {
        let range_spec = HTTPRangeSpec {
            is_suffix_length: true,
            start: -5,
            end: -1,
        };

        let (offset, length) = range_spec.get_offset_length(20).unwrap();
        assert_eq!(offset, 15);
        assert_eq!(length, 5);
    }

    #[test]
    fn test_http_range_spec_suffix_exceeds_object() {
        let range_spec = HTTPRangeSpec {
            is_suffix_length: true,
            start: 50,
            end: -1,
        };

        let (offset, length) = range_spec.get_offset_length(20).unwrap();
        assert_eq!(offset, 0);
        assert_eq!(length, 20);
    }

    #[test]
    fn test_http_range_spec_from_object_info_valid_and_invalid_parts() {
        let object_info = ObjectInfo {
            size: 300,
            parts: Arc::new(vec![
                ObjectPartInfo {
                    etag: String::new(),
                    number: 1,
                    size: 100,
                    actual_size: 100,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 2,
                    size: 100,
                    actual_size: 100,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 3,
                    size: 100,
                    actual_size: 100,
                    ..Default::default()
                },
            ]),
            ..Default::default()
        };

        let spec = http_range_spec_from_object_info(&object_info, 2).unwrap();
        assert_eq!(spec.start, 100);
        assert_eq!(spec.end, 199);

        assert!(http_range_spec_from_object_info(&object_info, 0).is_none());
        assert!(http_range_spec_from_object_info(&object_info, 4).is_none());
    }

    #[test]
    fn test_http_range_spec_from_object_info_uses_actual_size() {
        let object_info = ObjectInfo {
            size: 90,
            parts: Arc::new(vec![
                ObjectPartInfo {
                    etag: String::new(),
                    number: 1,
                    size: 20,
                    actual_size: 30,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 2,
                    size: 30,
                    actual_size: 40,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 3,
                    size: 40,
                    actual_size: 50,
                    ..Default::default()
                },
            ]),
            ..Default::default()
        };

        let spec = http_range_spec_from_object_info(&object_info, 2).unwrap();
        assert_eq!(spec.start, 30);
        assert_eq!(spec.end, 69);
    }

    #[test]
    fn test_http_range_spec_from_object_info_falls_back_to_part_size_when_actual_size_missing() {
        let object_info = ObjectInfo {
            size: 90,
            parts: Arc::new(vec![
                ObjectPartInfo {
                    etag: String::new(),
                    number: 1,
                    size: 20,
                    actual_size: 0,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 2,
                    size: 30,
                    actual_size: 40,
                    ..Default::default()
                },
                ObjectPartInfo {
                    etag: String::new(),
                    number: 3,
                    size: 40,
                    actual_size: 0,
                    ..Default::default()
                },
            ]),
            ..Default::default()
        };

        let spec = http_range_spec_from_object_info(&object_info, 3).unwrap();
        assert_eq!(spec.start, 60);
        assert_eq!(spec.end, 99);
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_zero_length() {
        let original_data = b"Hello, World!";
        let cursor = Cursor::new(original_data.to_vec());
        let mut ranged_reader = RangedDecompressReader::new(cursor, 5, 0, original_data.len()).unwrap();
        let mut result = Vec::new();
        ranged_reader.read_to_end(&mut result).await.unwrap();
        // Should read nothing
        assert_eq!(result, b"");
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_skip_entire_data() {
        let original_data = b"Hello, World!";
        let cursor = Cursor::new(original_data.to_vec());
        // Skip to end of data with length 0 - this should read nothing
        let mut ranged_reader = RangedDecompressReader::new(cursor, original_data.len() - 1, 0, original_data.len()).unwrap();
        let mut result = Vec::new();
        ranged_reader.read_to_end(&mut result).await.unwrap();
        assert_eq!(result, b"");
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_out_of_bounds_offset() {
        let original_data = b"Hello, World!";
        let cursor = Cursor::new(original_data.to_vec());
        // Offset beyond EOF should return error in constructor
        let result = RangedDecompressReader::new(cursor, original_data.len() + 10, 5, original_data.len());
        assert!(result.is_err());
        // Use pattern matching to avoid requiring Debug on the error type
        if let Err(e) = result {
            assert!(e.to_string().contains("Range offset exceeds file size"));
        }
    }

    #[tokio::test]
    async fn test_ranged_decompress_reader_partial_read() {
        let original_data = b"abcdef";
        let cursor = Cursor::new(original_data.to_vec());
        let mut ranged_reader = RangedDecompressReader::new(cursor, 2, 3, original_data.len()).unwrap();
        let mut buf = [0u8; 2];
        let n = ranged_reader.read(&mut buf).await.unwrap();
        assert_eq!(n, 2);
        assert_eq!(&buf, b"cd");
        let mut buf2 = [0u8; 2];
        let n2 = ranged_reader.read(&mut buf2).await.unwrap();
        assert_eq!(n2, 1);
        assert_eq!(&buf2[..1], b"e");
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_ranged_decompress_reader_with_rio_v2_s2_stream() {
        let plaintext = b"abcdefghijklmnopqrstuvwxyz".to_vec();
        let mut compressed = Vec::new();
        crate::io_support::rio::CompressReader::new(Cursor::new(plaintext.clone()), CompressionAlgorithm::default())
            .read_to_end(&mut compressed)
            .await
            .expect("compress plaintext into rio_v2 stream");

        let decompress_reader =
            crate::io_support::rio::DecompressReader::new(Cursor::new(compressed), CompressionAlgorithm::default());
        let mut ranged_reader =
            RangedDecompressReader::new(decompress_reader, 5, 7, plaintext.len()).expect("create ranged reader");

        let mut actual = Vec::new();
        ranged_reader
            .read_to_end(&mut actual)
            .await
            .expect("read ranged decompressed plaintext");

        assert_eq!(actual, b"fghijkl");
    }

    /// Compresses one multipart part exactly like the write path does
    /// (`WritePlan::with_compression` wraps each part in its own
    /// `compression_reader`), returning the on-disk bytes and the storage-format
    /// compression index.
    async fn compressed_part_fixture(data: &[u8]) -> (Vec<u8>, Option<Bytes>) {
        use crate::io_support::rio::TryGetIndex as _;
        let mut compressor =
            crate::io_support::rio::compression_reader(Cursor::new(data.to_vec()), CompressionAlgorithm::default(), false);
        let mut compressed = Vec::new();
        compressor.read_to_end(&mut compressed).await.expect("compress part stream");
        let index = compressor
            .try_get_index()
            .map(crate::io_support::rio::compression_index_storage_bytes);
        (compressed, index)
    }

    struct CompressedMultipartFixture {
        object_info: ObjectInfo,
        stored: Vec<u8>,
        plaintext: Vec<u8>,
    }

    /// Builds the on-disk representation of a compressed multipart object: each
    /// part is an independent compressed stream and the storage layer serves
    /// their concatenation.
    async fn compressed_multipart_fixture(part_sizes: &[usize]) -> CompressedMultipartFixture {
        let pattern = b"compressed multipart read path fixture data ";
        let mut plaintext = Vec::new();
        let mut stored = Vec::new();
        let mut parts = Vec::with_capacity(part_sizes.len());

        for (i, part_size) in part_sizes.iter().enumerate() {
            let mut part_plaintext = Vec::with_capacity(*part_size);
            while part_plaintext.len() < *part_size {
                part_plaintext.extend_from_slice(pattern);
                part_plaintext.push(i as u8);
            }
            part_plaintext.truncate(*part_size);

            let (compressed, index) = compressed_part_fixture(&part_plaintext).await;
            parts.push(ObjectPartInfo {
                number: i + 1,
                size: compressed.len(),
                actual_size: *part_size as i64,
                index,
                ..Default::default()
            });
            stored.extend_from_slice(&compressed);
            plaintext.extend_from_slice(&part_plaintext);
        }

        let mut user_defined = HashMap::new();
        rustfs_utils::http::insert_str(
            &mut user_defined,
            rustfs_utils::http::SUFFIX_COMPRESSION,
            crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
        );
        rustfs_utils::http::insert_str(&mut user_defined, rustfs_utils::http::SUFFIX_ACTUAL_SIZE, plaintext.len().to_string());

        let object_info = ObjectInfo {
            bucket: "test-bucket".to_string(),
            name: "compressed-multipart".to_string(),
            size: stored.len() as i64,
            etag: Some(format!("6bcf86bed8807b8e78f0fc6e0a53079d-{}", part_sizes.len())),
            parts: Arc::new(parts),
            user_defined: Arc::new(user_defined),
            ..Default::default()
        };

        CompressedMultipartFixture {
            object_info,
            stored,
            plaintext,
        }
    }

    /// Plans the read once to learn the storage window, then serves exactly that
    /// window — mirroring how `set_disk` feeds the erasure read into the
    /// returned reader.
    async fn read_compressed_multipart(
        fixture: &CompressedMultipartFixture,
        rs: Option<HTTPRangeSpec>,
        opts: &ObjectOptions,
    ) -> Vec<u8> {
        let headers = HeaderMap::new();
        let (_, offset, length) =
            GetObjectReader::new(Box::new(Cursor::new(Vec::new())), rs.clone(), &fixture.object_info, opts, &headers)
                .await
                .expect("plan compressed multipart read");

        let end = offset + usize::try_from(length).expect("storage window length must be non-negative");
        assert!(
            end <= fixture.stored.len(),
            "planned storage window {offset}..{end} exceeds stored stream of {} bytes",
            fixture.stored.len()
        );
        let window = fixture.stored[offset..end].to_vec();

        let (mut reader, replay_offset, replay_length) =
            GetObjectReader::new(Box::new(Cursor::new(window)), rs, &fixture.object_info, opts, &headers)
                .await
                .expect("build compressed multipart reader");
        assert_eq!((replay_offset, replay_length), (offset, length), "read plan must be deterministic");

        reader.read_all().await.expect("read compressed multipart stream")
    }

    /// Byte pattern with a 2 KiB period: it compresses extremely well while
    /// looking nothing like ASCII fixtures. Mirrors the e2e generator that
    /// exposed a truncated full GET on high-ratio multipart payloads.
    fn high_ratio_binary_payload(size: usize, seed: u8) -> Vec<u8> {
        (0..size)
            .map(|i| ((i as u64).wrapping_mul(2_654_435_761).wrapping_add(seed as u64) >> 3) as u8)
            .collect()
    }

    #[tokio::test]
    async fn compressed_multipart_full_get_handles_high_ratio_binary_payload() {
        let part_sizes = [5 * 1024 * 1024_usize, 1024 * 1024];
        let mut plaintext = Vec::new();
        let mut stored = Vec::new();
        let mut parts = Vec::with_capacity(part_sizes.len());

        for (i, part_size) in part_sizes.iter().enumerate() {
            let part_plaintext = high_ratio_binary_payload(*part_size, if i == 0 { 7 } else { 61 });
            let (compressed, index) = compressed_part_fixture(&part_plaintext).await;
            parts.push(ObjectPartInfo {
                number: i + 1,
                size: compressed.len(),
                actual_size: *part_size as i64,
                index,
                ..Default::default()
            });
            stored.extend_from_slice(&compressed);
            plaintext.extend_from_slice(&part_plaintext);
        }

        let mut user_defined = HashMap::new();
        rustfs_utils::http::insert_str(
            &mut user_defined,
            rustfs_utils::http::SUFFIX_COMPRESSION,
            crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
        );
        rustfs_utils::http::insert_str(&mut user_defined, rustfs_utils::http::SUFFIX_ACTUAL_SIZE, plaintext.len().to_string());
        let fixture = CompressedMultipartFixture {
            object_info: ObjectInfo {
                bucket: "test-bucket".to_string(),
                name: "high-ratio-multipart".to_string(),
                size: stored.len() as i64,
                etag: Some("6bcf86bed8807b8e78f0fc6e0a53079d-2".to_string()),
                parts: Arc::new(parts),
                user_defined: Arc::new(user_defined),
                ..Default::default()
            },
            stored,
            plaintext,
        };

        let read = read_compressed_multipart(&fixture, None, &ObjectOptions::default()).await;

        assert_eq!(read.len(), fixture.plaintext.len(), "full GET must return the logical size");
        assert_eq!(read, fixture.plaintext, "high-ratio multipart payload must survive the roundtrip");
    }

    /// Full GET over a compressed multipart object must decode across part
    /// boundaries: every part is an independent compressed stream (this is also
    /// the on-disk shape written by builds before rustfs/rustfs#5169 disabled
    /// multipart compression, so this pins legacy-object readability).
    #[tokio::test]
    async fn compressed_multipart_full_get_decodes_across_part_boundaries() {
        let fixture = compressed_multipart_fixture(&[3 * 1024 * 1024, 2 * 1024 * 1024, 512 * 1024]).await;

        let read = read_compressed_multipart(&fixture, None, &ObjectOptions::default()).await;

        assert_eq!(read.len(), fixture.plaintext.len(), "full GET must return the logical size");
        assert_eq!(read, fixture.plaintext, "full GET must reassemble all parts");
    }

    #[tokio::test]
    async fn compressed_multipart_range_get_crosses_part_boundary() {
        let fixture = compressed_multipart_fixture(&[3 * 1024 * 1024, 2 * 1024 * 1024]).await;
        let boundary = 3 * 1024 * 1024_i64;
        let rs = HTTPRangeSpec {
            is_suffix_length: false,
            start: boundary - 100_000,
            end: boundary + 100_000 - 1,
        };

        let read = read_compressed_multipart(&fixture, Some(rs), &ObjectOptions::default()).await;

        let expected = &fixture.plaintext[(boundary - 100_000) as usize..(boundary + 100_000) as usize];
        assert_eq!(read, expected, "boundary-crossing range must splice both parts");
    }

    #[tokio::test]
    async fn compressed_multipart_range_get_seeks_into_later_part() {
        let fixture = compressed_multipart_fixture(&[3 * 1024 * 1024, 4 * 1024 * 1024]).await;
        // Deep inside part 2 so the plan skips part 1 entirely and (when the
        // part carries an index) seeks within part 2.
        let start = 3 * 1024 * 1024_i64 + 2 * 1024 * 1024_i64 + 137;
        let rs = HTTPRangeSpec {
            is_suffix_length: false,
            start,
            end: start + 64 * 1024 - 1,
        };

        let read = read_compressed_multipart(&fixture, Some(rs), &ObjectOptions::default()).await;

        let expected = &fixture.plaintext[start as usize..(start + 64 * 1024) as usize];
        assert_eq!(read, expected, "range inside a later part must decode from that part");
    }

    /// Parts written without a compression index (small parts skip the index in
    /// the rio-v2 backend) must still be rangeable: the plan starts at the part
    /// boundary and skips decompressed bytes.
    #[tokio::test]
    async fn compressed_multipart_range_get_works_without_part_indexes() {
        let mut fixture = compressed_multipart_fixture(&[1024 * 1024, 1024 * 1024]).await;
        let parts = fixture
            .object_info
            .parts
            .iter()
            .map(|part| ObjectPartInfo {
                index: None,
                ..part.clone()
            })
            .collect::<Vec<_>>();
        fixture.object_info.parts = Arc::new(parts);

        let start = 1024 * 1024_i64 + 4096;
        let rs = HTTPRangeSpec {
            is_suffix_length: false,
            start,
            end: start + 32 * 1024 - 1,
        };

        let read = read_compressed_multipart(&fixture, Some(rs), &ObjectOptions::default()).await;

        let expected = &fixture.plaintext[start as usize..(start + 32 * 1024) as usize];
        assert_eq!(read, expected, "index-less parts must fall back to part-boundary skip");
    }

    #[tokio::test]
    async fn compressed_multipart_part_number_get_returns_single_part() {
        let part_sizes = [3 * 1024 * 1024, 2 * 1024 * 1024, 512 * 1024];
        let fixture = compressed_multipart_fixture(&part_sizes).await;

        let mut logical_offset = 0_usize;
        for (i, part_size) in part_sizes.iter().enumerate() {
            let opts = ObjectOptions {
                part_number: Some(i + 1),
                ..Default::default()
            };

            let read = read_compressed_multipart(&fixture, None, &opts).await;

            let expected = &fixture.plaintext[logical_offset..logical_offset + part_size];
            assert_eq!(read.len(), *part_size, "partNumber={} GET must return the part's logical size", i + 1);
            assert_eq!(read, expected, "partNumber={} GET must return the original part bytes", i + 1);
            logical_offset += part_size;
        }
    }

    #[tokio::test]
    async fn compressed_multipart_suffix_range_reads_tail() {
        let fixture = compressed_multipart_fixture(&[3 * 1024 * 1024, 1024 * 1024]).await;
        let suffix_len = 128 * 1024_i64;
        let rs = HTTPRangeSpec {
            is_suffix_length: true,
            start: suffix_len,
            end: -1,
        };

        let read = read_compressed_multipart(&fixture, Some(rs), &ObjectOptions::default()).await;

        let expected = &fixture.plaintext[fixture.plaintext.len() - suffix_len as usize..];
        assert_eq!(read, expected, "suffix range must return the tail of the last part");
    }

    /// Builds an SSE-C + disk-compression multipart object exactly like the
    /// write path: each part is compressed into its own stream and then
    /// encrypted with the per-part key schedule. The fixture is
    /// legacy-encryption-specific (`rustfs_rio::EncryptReader`), matching the
    /// pre-existing `build_legacy_ssec_multipart_fixture` shape, while the
    /// compression layer follows the active backend feature.
    async fn compressed_encrypted_multipart_fixture(key_bytes: [u8; 32], part_sizes: &[usize]) -> CompressedMultipartFixture {
        let pattern = b"compressed encrypted multipart fixture data ";
        let mut plaintext = Vec::new();
        let mut stored = Vec::new();
        let mut parts = Vec::with_capacity(part_sizes.len());

        for (i, part_size) in part_sizes.iter().enumerate() {
            let part_number = i + 1;
            let mut part_plaintext = Vec::with_capacity(*part_size);
            while part_plaintext.len() < *part_size {
                part_plaintext.extend_from_slice(pattern);
                part_plaintext.push(part_number as u8);
            }
            part_plaintext.truncate(*part_size);

            let (compressed, index) = compressed_part_fixture(&part_plaintext).await;
            let mut part_cipher = Vec::new();
            rustfs_rio::EncryptReader::new_multipart(Cursor::new(compressed), key_bytes, LEGACY_FIXTURE_BASE_NONCE, part_number)
                .read_to_end(&mut part_cipher)
                .await
                .expect("encrypt compressed fixture part");

            parts.push(ObjectPartInfo {
                number: part_number,
                size: part_cipher.len(),
                actual_size: *part_size as i64,
                index,
                ..Default::default()
            });
            stored.extend_from_slice(&part_cipher);
            plaintext.extend_from_slice(&part_plaintext);
        }

        let mut user_defined = legacy_ssec_multipart_metadata(key_bytes, plaintext.len());
        rustfs_utils::http::insert_str(
            &mut user_defined,
            rustfs_utils::http::SUFFIX_COMPRESSION,
            crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
        );
        rustfs_utils::http::insert_str(&mut user_defined, rustfs_utils::http::SUFFIX_ACTUAL_SIZE, plaintext.len().to_string());

        let object_info = ObjectInfo {
            bucket: "test-bucket".to_string(),
            name: "compressed-encrypted-multipart".to_string(),
            size: stored.len() as i64,
            etag: Some(format!("6bcf86bed8807b8e78f0fc6e0a53079d-{}", part_sizes.len())),
            parts: Arc::new(parts),
            user_defined: Arc::new(user_defined),
            ..Default::default()
        };

        CompressedMultipartFixture {
            object_info,
            stored,
            plaintext,
        }
    }

    async fn read_compressed_encrypted_multipart(
        fixture: &CompressedMultipartFixture,
        key_bytes: [u8; 32],
        rs: Option<HTTPRangeSpec>,
        opts: &ObjectOptions,
    ) -> Vec<u8> {
        let headers = ssec_headers_from_key(key_bytes);
        let (_, offset, length) =
            GetObjectReader::new(Box::new(Cursor::new(Vec::new())), rs.clone(), &fixture.object_info, opts, &headers)
                .await
                .expect("plan compressed encrypted multipart read");

        let end = offset + usize::try_from(length).expect("storage window length must be non-negative");
        assert!(
            end <= fixture.stored.len(),
            "planned storage window {offset}..{end} exceeds stored stream of {} bytes",
            fixture.stored.len()
        );
        let window = fixture.stored[offset..end].to_vec();

        let (mut reader, replay_offset, replay_length) =
            GetObjectReader::new(Box::new(Cursor::new(window)), rs, &fixture.object_info, opts, &headers)
                .await
                .expect("build compressed encrypted multipart reader");
        assert_eq!((replay_offset, replay_length), (offset, length), "read plan must be deterministic");

        reader.read_all().await.expect("read compressed encrypted multipart stream")
    }

    #[tokio::test]
    async fn compressed_encrypted_multipart_full_get_roundtrip() {
        let key_bytes = [0x6Eu8; 32];
        let fixture = compressed_encrypted_multipart_fixture(key_bytes, &[3 * 1024 * 1024, 1024 * 1024]).await;

        let read = read_compressed_encrypted_multipart(&fixture, key_bytes, None, &ObjectOptions::default()).await;

        assert_eq!(read.len(), fixture.plaintext.len(), "full GET must return the logical size");
        assert_eq!(read, fixture.plaintext, "SSE-C + compression full GET must reassemble all parts");
    }

    #[tokio::test]
    async fn multipart_empty_tail_full_reads_preserve_plaintext() {
        let key = [0x6Eu8; 32];
        let part_sizes = [5 * 1024 * 1024, 0];
        let encrypted = build_legacy_ssec_multipart_fixture(key, &part_sizes).await;
        for (kind, mut fixture, headers) in [
            (
                "encrypted",
                CompressedMultipartFixture {
                    object_info: encrypted.object_info,
                    stored: encrypted.ciphertext,
                    plaintext: encrypted.plaintext,
                },
                ssec_headers_from_key(key),
            ),
            ("compressed", compressed_multipart_fixture(&part_sizes).await, HeaderMap::new()),
            (
                "compressed and encrypted",
                compressed_encrypted_multipart_fixture(key, &part_sizes).await,
                ssec_headers_from_key(key),
            ),
        ] {
            fixture.object_info.etag = Some(faster_hex::hex_string(Md5::digest(&fixture.plaintext).as_ref()));
            assert_eq!(fixture.object_info.etag.as_ref().expect("source ETag").len(), 32);
            assert_eq!(fixture.object_info.parts.len(), 2);
            let tail = &fixture.object_info.parts[1];
            assert_eq!(tail.actual_size, 0, "{kind}: final part has no plaintext");
            if kind == "compressed" {
                assert_eq!(tail.size, 0, "unpadded compression emits no bytes for an empty part");
            } else {
                assert!(tail.size > 0, "{kind}: the empty part still has a stored frame");
            }
            let stored_size = i64::try_from(fixture.stored.len()).expect("fixture size fits i64");
            let (mut reader, offset, length) = GetObjectReader::new(
                Box::new(Cursor::new(fixture.stored)),
                None,
                &fixture.object_info,
                &ObjectOptions::default(),
                &headers,
            )
            .await
            .expect("full transformed read must include the empty tail");
            assert_eq!((offset, length), (0, stored_size), "{kind}: full read includes all stored parts");
            let mut body = Vec::new();
            reader
                .stream
                .read_to_end(&mut body)
                .await
                .expect("read through the complete decoder EOF");
            assert_eq!(body, fixture.plaintext, "{kind}: no plaintext is added or lost by the empty tail");
        }
    }

    #[tokio::test]
    async fn multipart_empty_tail_full_read_authenticates_v2_final_frame() {
        let key = [0x6Eu8; 32];
        let plaintext = legacy_fixture_part_plaintext(1, 5 * 1024 * 1024);
        let mut ciphertext = Vec::new();
        let mut parts = Vec::new();
        for (number, body) in [(1, plaintext.as_slice()), (2, b"".as_slice())] {
            let start = ciphertext.len();
            rustfs_rio::EncryptReader::new_multipart_v2(Cursor::new(body), key, LEGACY_FIXTURE_BASE_NONCE, number)
                .read_to_end(&mut ciphertext)
                .await
                .expect("encrypt a v2 fixture part with an authenticated final frame");
            parts.push(ObjectPartInfo {
                number,
                size: ciphertext.len() - start,
                actual_size: i64::try_from(body.len()).expect("fixture plaintext size fits"),
                ..Default::default()
            });
        }
        let tail_start = parts[0].size;
        assert_eq!(parts[1].actual_size, 0);
        assert!(parts[1].size > 8, "the empty final frame carries more than an END marker");
        let object_info = ObjectInfo {
            bucket: "bucket".to_string(),
            name: "v2-empty-tail".to_string(),
            size: i64::try_from(ciphertext.len()).expect("fixture ciphertext size fits"),
            etag: Some(faster_hex::hex_string(Md5::digest(&plaintext).as_ref())),
            parts: Arc::new(parts),
            user_defined: Arc::new(legacy_ssec_multipart_metadata(key, plaintext.len())),
            ..Default::default()
        };
        for corrupt_tail in [false, true] {
            let mut stored = ciphertext.clone();
            if corrupt_tail {
                // The v2 header is authenticated associated data, including
                // the header of a final frame containing zero plaintext.
                stored[tail_start + 5] ^= 1;
            }
            let (mut reader, offset, length) = GetObjectReader::new(
                Box::new(Cursor::new(stored)),
                None,
                &object_info,
                &ObjectOptions::default(),
                &ssec_headers_from_key(key),
            )
            .await
            .expect("construct the full reader before consuming the final frame");
            assert_eq!((offset, length), (0, object_info.size));
            let result = tokio::io::copy(&mut reader.stream, &mut tokio::io::sink()).await;
            if corrupt_tail {
                let err = result.expect_err("EOF must authenticate the empty final frame after all plaintext is returned");
                assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
                assert_eq!(err.to_string(), "v2 encrypted frame failed authentication");
            } else {
                assert_eq!(
                    result.expect("valid empty final frame must reach EOF"),
                    u64::try_from(plaintext.len()).expect("plaintext length fits")
                );
            }
        }
    }

    #[tokio::test]
    async fn compressed_encrypted_multipart_range_crosses_part_boundary() {
        let key_bytes = [0x6Eu8; 32];
        let fixture = compressed_encrypted_multipart_fixture(key_bytes, &[3 * 1024 * 1024, 1024 * 1024]).await;
        let boundary = 3 * 1024 * 1024_i64;
        let rs = HTTPRangeSpec {
            is_suffix_length: false,
            start: boundary - 65_536,
            end: boundary + 65_536 - 1,
        };

        let read = read_compressed_encrypted_multipart(&fixture, key_bytes, Some(rs), &ObjectOptions::default()).await;

        let expected = &fixture.plaintext[(boundary - 65_536) as usize..(boundary + 65_536) as usize];
        assert_eq!(read, expected, "SSE-C + compression boundary-crossing range must splice both parts");
    }

    #[tokio::test]
    async fn compressed_encrypted_multipart_part_number_get_returns_single_part() {
        let key_bytes = [0x6Eu8; 32];
        let part_sizes = [3 * 1024 * 1024, 1024 * 1024];
        let fixture = compressed_encrypted_multipart_fixture(key_bytes, &part_sizes).await;

        let opts = ObjectOptions {
            part_number: Some(2),
            ..Default::default()
        };
        let read = read_compressed_encrypted_multipart(&fixture, key_bytes, None, &opts).await;

        let expected = &fixture.plaintext[part_sizes[0]..];
        assert_eq!(read.len(), part_sizes[1], "partNumber=2 GET must return the part's logical size");
        assert_eq!(read, expected, "partNumber=2 GET must return the original part bytes");
    }

    #[tokio::test]
    async fn test_get_object_reader_rejects_ssec_read_without_headers() {
        let object_info = ObjectInfo {
            size: 10,
            user_defined: Arc::new(HashMap::from([
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                ("x-amz-server-side-encryption-customer-original-size".to_string(), "20".to_string()),
            ])),
            ..Default::default()
        };

        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 8,
            end: -1,
        };

        let result = GetObjectReader::new(
            Box::new(Cursor::new(b"0123456789".to_vec())),
            Some(range),
            &object_info,
            &ObjectOptions::default(),
            &HeaderMap::new(),
        )
        .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_object_reader_restore_request_bypasses_encryption_range_rewrite() {
        let object_info = ObjectInfo {
            size: 10,
            user_defined: Arc::new(HashMap::from([
                ("x-rustfs-encryption-key".to_string(), "encrypted-key".to_string()),
                ("x-rustfs-encryption-original-size".to_string(), "20".to_string()),
            ])),
            ..Default::default()
        };

        let range = HTTPRangeSpec {
            is_suffix_length: true,
            start: 4,
            end: -1,
        };

        let mut opts = ObjectOptions::default();
        opts.transition.restore_request.days = Some(1);

        let (_, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(b"0123456789".to_vec())),
            Some(range),
            &object_info,
            &opts,
            &HeaderMap::new(),
        )
        .await
        .unwrap();

        assert_eq!(offset, 6);
        assert_eq!(length, 4);
    }

    #[tokio::test]
    async fn test_read_plan_restore_request_uses_plain_range() {
        let object_info = ObjectInfo {
            size: 10,
            user_defined: Arc::new(HashMap::from([
                ("x-rustfs-encryption-key".to_string(), "encrypted-key".to_string()),
                ("x-rustfs-encryption-original-size".to_string(), "20".to_string()),
            ])),
            ..Default::default()
        };

        let range = HTTPRangeSpec {
            is_suffix_length: true,
            start: 4,
            end: -1,
        };

        let mut opts = ObjectOptions::default();
        opts.transition.restore_request.days = Some(1);

        let plan = ReadPlan::build(Some(range), &object_info, &opts, &HeaderMap::new())
            .await
            .expect("restore requests should bypass rio transforms");

        assert_eq!(plan.storage_offset, 6);
        assert_eq!(plan.storage_length, 4);
        assert_eq!(plan.object_size, 10);
        assert!(matches!(
            plan.transform,
            ReadTransform::Plain {
                visible_offset: 6,
                visible_length: 4
            }
        ));
    }

    #[tokio::test]
    async fn test_raw_data_movement_read_plan_bypasses_compression_transform() {
        let object_info = ObjectInfo {
            size: 3_000_000,
            user_defined: Arc::new(HashMap::from([
                ("x-minio-internal-compression".to_string(), "klauspost/compress/s2".to_string()),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };
        let opts = ObjectOptions {
            raw_data_movement_read: true,
            ..Default::default()
        };

        let plan = ReadPlan::build(None, &object_info, &opts, &HeaderMap::new())
            .await
            .expect("raw data movement read should bypass compression planning");

        assert_eq!(plan.storage_offset, 0);
        assert_eq!(plan.storage_length, object_info.size);
        assert_eq!(plan.object_size, object_info.size);
        assert!(matches!(
            plan.transform,
            ReadTransform::Plain {
                visible_offset: 0,
                visible_length: 3_000_000
            }
        ));
    }

    #[tokio::test]
    async fn test_raw_data_movement_read_plan_bypasses_encryption_transform() {
        let object_info = ObjectInfo {
            size: 128,
            user_defined: Arc::new(HashMap::from([
                ("X-Amz-Server-Side-Encryption".to_string(), "aws:kms".to_string()),
                ("X-Amz-Server-Side-Encryption-Iv".to_string(), "AAAAAAAAAAAAAAAA".to_string()),
                (
                    "X-Amz-Server-Side-Encryption-Key".to_string(),
                    BASE64_STANDARD.encode_to_string([7_u8; 32]),
                ),
                ("x-rustfs-encryption-original-size".to_string(), "64".to_string()),
            ])),
            ..Default::default()
        };
        let opts = ObjectOptions {
            raw_data_movement_read: true,
            ..Default::default()
        };

        let plan = ReadPlan::build(None, &object_info, &opts, &HeaderMap::new())
            .await
            .expect("raw data movement read should not require decryption material");

        assert_eq!(plan.storage_offset, 0);
        assert_eq!(plan.storage_length, object_info.size);
        assert_eq!(plan.object_size, object_info.size);
        assert!(matches!(
            plan.transform,
            ReadTransform::Plain {
                visible_offset: 0,
                visible_length: 128
            }
        ));
    }

    #[tokio::test]
    async fn test_raw_data_movement_read_plan_bypasses_ssec_header_resolution() {
        let object_info = ObjectInfo {
            size: 256,
            user_defined: Arc::new(HashMap::from([
                (SSEC_ALGORITHM_HEADER.to_string(), "AES256".to_string()),
                (SSEC_KEY_MD5_HEADER.to_string(), "stored-key-md5".to_string()),
            ])),
            ..Default::default()
        };
        let opts = ObjectOptions {
            raw_data_movement_read: true,
            ..Default::default()
        };

        let plan = ReadPlan::build(None, &object_info, &opts, &HeaderMap::new())
            .await
            .expect("raw data movement read should not require SSE-C request headers");

        assert_eq!(plan.storage_offset, 0);
        assert_eq!(plan.storage_length, object_info.size);
        assert_eq!(plan.object_size, object_info.size);
        assert!(matches!(
            plan.transform,
            ReadTransform::Plain {
                visible_offset: 0,
                visible_length: 256
            }
        ));
    }

    #[tokio::test]
    async fn test_get_object_reader_compressed_range_returns_physical_offset_from_index() {
        let mut index = Index::new();
        index.add(0, 0).unwrap();
        index.add(1_048_576, 2_097_152).unwrap();

        let object_info = ObjectInfo {
            size: 3_000_000,
            parts: Arc::new(vec![ObjectPartInfo {
                etag: String::new(),
                number: 1,
                size: 3_000_000,
                actual_size: 4_194_304,
                index: Some(index.into_vec()),
                ..Default::default()
            }]),
            user_defined: Arc::new(HashMap::from([
                ("x-minio-internal-compression".to_string(), "gzip".to_string()),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };

        let decoded = crate::io_support::rio::decode_compression_index_bytes(object_info.parts[0].index.as_ref().unwrap())
            .expect("headerless MinIO-style compression index should decode");
        let (compressed_offset, uncompressed_offset) = decoded.find(2_097_152).expect("seek into decoded index");
        assert!(compressed_offset > 0);
        assert_eq!(uncompressed_offset, 2_097_152);
        let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, 2_097_152);
        assert!(physical_offset > 0);
        assert_eq!(decompressed_skip, 0);

        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 2_097_152,
            end: 2_097_161,
        };

        let (reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(Vec::<u8>::new())),
            Some(range),
            &object_info,
            &ObjectOptions::default(),
            &HeaderMap::new(),
        )
        .await
        .unwrap();

        assert!(offset > 0);
        assert!(offset < 2_097_152);
        assert_eq!(length, object_info.size - offset as i64);
        assert_eq!(reader.object_info.size, 10);
    }

    #[tokio::test]
    async fn test_read_plan_compressed_range_tracks_storage_and_visible_offsets() {
        let mut index = Index::new();
        index.add(0, 0).unwrap();
        index.add(1_048_576, 2_097_152).unwrap();

        let object_info = ObjectInfo {
            size: 3_000_000,
            parts: Arc::new(vec![ObjectPartInfo {
                etag: String::new(),
                number: 1,
                size: 3_000_000,
                actual_size: 4_194_304,
                index: Some(index.into_vec()),
                ..Default::default()
            }]),
            user_defined: Arc::new(HashMap::from([
                ("x-minio-internal-compression".to_string(), "gzip".to_string()),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };

        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 2_097_152,
            end: 2_097_161,
        };

        let plan = ReadPlan::build(Some(range), &object_info, &ObjectOptions::default(), &HeaderMap::new())
            .await
            .expect("compressed range should plan physical offset and visible range");

        assert!(plan.storage_offset > 0);
        assert!(plan.storage_offset < 2_097_152);
        assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
        assert_eq!(plan.object_size, 10);

        assert!(matches!(
            plan.transform,
            ReadTransform::Compressed {
                decompressed_offset,
                decompressed_length: 10,
                ..
            } if decompressed_offset < 2_097_152
        ));
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_read_plan_accepts_minio_s2_compression_scheme() {
        let object_info = ObjectInfo {
            size: 3_000_000,
            user_defined: Arc::new(HashMap::from([
                ("x-minio-internal-compression".to_string(), "klauspost/compress/s2".to_string()),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };

        let plan = ReadPlan::build(None, &object_info, &ObjectOptions::default(), &HeaderMap::new())
            .await
            .expect("MinIO S2 compression scheme should be accepted");

        assert!(matches!(
            plan.transform,
            ReadTransform::Compressed {
                decompressed_offset: 0,
                decompressed_length: 4_194_304,
                ..
            }
        ));
        assert_eq!(plan.object_size, 4_194_304);
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_read_plan_accepts_minio_headerless_compression_index() {
        let mut index = Index::new();
        index.add(0, 0).unwrap();
        index.add(1_048_576, 2_097_152).unwrap();
        let headerless_index = crate::io_support::rio::compression_index_storage_bytes(&index);
        assert!(
            !headerless_index.starts_with(&[0x50, 0x2A, 0x4D, 0x18]),
            "rio_v2 should store MinIO-style headerless compression indexes"
        );

        let object_info = ObjectInfo {
            size: 3_000_000,
            parts: Arc::new(vec![ObjectPartInfo {
                etag: String::new(),
                number: 1,
                size: 3_000_000,
                actual_size: 4_194_304,
                index: Some(headerless_index),
                ..Default::default()
            }]),
            user_defined: Arc::new(HashMap::from([
                ("x-minio-internal-compression".to_string(), "klauspost/compress/s2".to_string()),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };

        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 2_097_152,
            end: 2_097_161,
        };

        let decoded = crate::io_support::rio::decode_compression_index_bytes(object_info.parts[0].index.as_ref().unwrap())
            .expect("headerless MinIO-style compression index should decode");
        let (compressed_offset, uncompressed_offset) = decoded.find(range.start).expect("seek into decoded index");
        assert!(compressed_offset > 0);
        assert_eq!(uncompressed_offset, range.start);

        let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, range.start);
        assert!(physical_offset > 0);
        assert_eq!(decompressed_skip, 0);

        let plan = ReadPlan::build(Some(range), &object_info, &ObjectOptions::default(), &HeaderMap::new())
            .await
            .expect("MinIO headerless compression index should be decoded");

        assert_eq!(plan.storage_offset as i64, physical_offset);
        assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
        assert_eq!(plan.object_size, 10);
    }

    #[cfg(feature = "rio-v2")]
    #[test]
    fn test_get_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
        let mut index = Index::new();
        index.add(0, 0).unwrap();
        index.add(200_000, 2_097_152).unwrap();
        let stored_index = crate::io_support::rio::compression_index_storage_bytes(&index);
        let expected_comp_off = crate::io_support::rio::decode_compression_index_bytes(&stored_index)
            .expect("decode stored index")
            .find(2_097_152)
            .expect("find offset in stored index")
            .0;

        let object_info = ObjectInfo {
            size: 400_000,
            parts: Arc::new(vec![ObjectPartInfo {
                etag: String::new(),
                number: 1,
                size: 400_000,
                actual_size: 4_194_304,
                index: Some(stored_index),
                ..Default::default()
            }]),
            user_defined: Arc::new(HashMap::from([
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                ("x-amz-server-side-encryption-customer-original-size".to_string(), "4194304".to_string()),
                (
                    "x-minio-internal-compression".to_string(),
                    crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
                ),
                ("x-minio-internal-actual-size".to_string(), "4194304".to_string()),
            ])),
            ..Default::default()
        };

        let (physical_offset, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
            get_compressed_offsets(&object_info, 2_097_152);

        assert_eq!(first_part_idx, 0);
        assert_eq!(physical_offset, (expected_comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE);
        assert_eq!(decompressed_skip, 0);
        assert_eq!(decrypt_skip, expected_comp_off % DARE_PAYLOAD_SIZE);
        assert_eq!(seq_num, (expected_comp_off / DARE_PAYLOAD_SIZE) as u64);
    }

    #[tokio::test]
    async fn test_get_object_reader_decrypts_ssec_full_object() {
        let plaintext = b"ecstore-ssec-full-object".to_vec();
        let key_bytes = [0x31; 32];
        let bucket = "bucket";
        let object = "object";
        let nonce = md5_bytes(format!("{bucket}-{object}").as_bytes());
        let mut base_nonce = [0u8; 12];
        base_nonce.copy_from_slice(&nonce[..12]);

        let mut encrypted = Vec::new();
        rustfs_rio::EncryptReader::new(Cursor::new(plaintext.clone()), key_bytes, base_nonce)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt object");

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            user_defined: Arc::new(HashMap::from([
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(key_bytes)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
            ])),
            ..Default::default()
        };

        let (mut reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted.clone())),
            None,
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("ssec read should be supported");

        let mut actual = Vec::new();
        reader.read_to_end(&mut actual).await.expect("read decrypted ssec object");

        assert_eq!(offset, 0);
        assert_eq!(length, encrypted.len() as i64);
        assert_eq!(reader.object_info.size, plaintext.len() as i64);
        assert_eq!(actual, plaintext);
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_get_object_reader_decrypts_ssec_sealed_object_key_full_object() {
        let plaintext = b"ecstore-rio-v2-ssec-sealed-object-key".repeat(4096);
        let customer_key = [0x31; 32];
        let object_key = [0x67; 32];
        let bucket = "bucket";
        let object = "sealed-object";
        let mut encrypted = Vec::new();
        crate::io_support::rio::EncryptReader::new_with_object_key(Cursor::new(plaintext.clone()), object_key)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt object with rio-v2 object key");

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            user_defined: Arc::new(HashMap::from([
                (TEST_OBJECT_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(object_key)),
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(customer_key)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
            ])),
            ..Default::default()
        };

        let (mut reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted.clone())),
            None,
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(customer_key),
        )
        .await
        .expect("rio-v2 ssec sealed-object-key read should be supported");

        let mut actual = Vec::new();
        reader
            .read_to_end(&mut actual)
            .await
            .expect("read decrypted rio-v2 ssec object");

        assert_eq!(offset, 0);
        assert_eq!(length, encrypted.len() as i64);
        assert_eq!(reader.object_info.size, plaintext.len() as i64);
        assert_eq!(actual, plaintext);
    }

    #[tokio::test]
    async fn test_get_object_reader_decrypts_ssec_range_on_plaintext_semantics() {
        let plaintext = b"0123456789abcdefghijklmnopqrstuvwxyz".to_vec();
        let key_bytes = [0x41; 32];
        let bucket = "bucket";
        let object = "range-object";
        let nonce = md5_bytes(format!("{bucket}-{object}").as_bytes());
        let mut base_nonce = [0u8; 12];
        base_nonce.copy_from_slice(&nonce[..12]);

        let mut encrypted = Vec::new();
        rustfs_rio::EncryptReader::new(Cursor::new(plaintext.clone()), key_bytes, base_nonce)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt ranged object");

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            user_defined: Arc::new(HashMap::from([
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(key_bytes)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
            ])),
            ..Default::default()
        };
        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 5,
            end: 11,
        };

        let (mut reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted.clone())),
            Some(range),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("ssec range read should be supported");

        let mut actual = Vec::new();
        reader.read_to_end(&mut actual).await.expect("read ranged decrypted object");

        assert_eq!(offset, 0);
        assert_eq!(length, encrypted.len() as i64);
        assert_eq!(reader.object_info.size, 7);
        assert_eq!(actual, b"56789ab");
    }

    /// Counts every byte pulled from the underlying ciphertext stream, standing in
    /// for the physical bytes the erasure layer would decode for this read.
    struct SpyReader<R> {
        inner: R,
        bytes_read: Arc<std::sync::atomic::AtomicU64>,
    }

    impl<R> SpyReader<R> {
        fn new(inner: R) -> (Self, Arc<std::sync::atomic::AtomicU64>) {
            let bytes_read = Arc::new(std::sync::atomic::AtomicU64::new(0));
            (
                Self {
                    inner,
                    bytes_read: bytes_read.clone(),
                },
                bytes_read,
            )
        }
    }

    impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SpyReader<R> {
        fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
            let before = buf.filled().len();
            let poll = Pin::new(&mut self.inner).poll_read(cx, buf);
            if let Poll::Ready(Ok(())) = &poll {
                let filled = (buf.filled().len() - before) as u64;
                self.bytes_read.fetch_add(filled, std::sync::atomic::Ordering::Relaxed);
            }
            poll
        }
    }

    struct LegacyMultipartFixture {
        plaintext: Vec<u8>,
        ciphertext: Vec<u8>,
        object_info: ObjectInfo,
        part_physical_sizes: Vec<usize>,
    }

    impl LegacyMultipartFixture {
        /// Physical ciphertext offset where the given zero-based part starts.
        fn physical_part_start(&self, part_index: usize) -> usize {
            self.part_physical_sizes[..part_index].iter().sum()
        }
    }

    const LEGACY_FIXTURE_BASE_NONCE: [u8; 12] = [0x5A; 12];

    fn legacy_fixture_part_plaintext(part_number: usize, size: usize) -> Vec<u8> {
        (0..size).map(|i| ((i * 31 + part_number * 7) % 251) as u8).collect()
    }

    /// Encrypts every part as its own rio v1 segment with the per-part nonce,
    /// exactly like `WritePlan::apply` does for multipart uploads, and records the
    /// physical/plaintext part sizes the way `PutObjectPart` persists them.
    async fn build_legacy_multipart_fixture(
        bucket: &str,
        object: &str,
        key_bytes: [u8; 32],
        part_plain_sizes: &[usize],
        mut user_defined: HashMap<String, String>,
    ) -> LegacyMultipartFixture {
        let mut plaintext = Vec::new();
        let mut ciphertext = Vec::new();
        let mut parts = Vec::new();
        let mut part_physical_sizes = Vec::new();

        for (part_index, &part_plain_size) in part_plain_sizes.iter().enumerate() {
            let part_number = part_index + 1;
            let part_plain = legacy_fixture_part_plaintext(part_number, part_plain_size);
            let mut part_cipher = Vec::new();
            rustfs_rio::EncryptReader::new_multipart(
                Cursor::new(part_plain.clone()),
                key_bytes,
                LEGACY_FIXTURE_BASE_NONCE,
                part_number,
            )
            .read_to_end(&mut part_cipher)
            .await
            .expect("encrypt multipart fixture part");

            parts.push(ObjectPartInfo {
                number: part_number,
                size: part_cipher.len(),
                actual_size: part_plain.len() as i64,
                ..Default::default()
            });
            part_physical_sizes.push(part_cipher.len());
            plaintext.extend_from_slice(&part_plain);
            ciphertext.extend_from_slice(&part_cipher);
        }
        let data_dir = Uuid::from_u128(1);
        rustfs_utils::http::insert_str(&mut user_defined, ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX, data_dir.to_string());

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: ciphertext.len() as i64,
            data_dir: Some(data_dir),
            etag: Some(format!("d41d8cd98f00b204e9800998ecf8427e-{}", parts.len())),
            parts: Arc::new(parts),
            user_defined: Arc::new(user_defined),
            ..Default::default()
        };

        LegacyMultipartFixture {
            plaintext,
            ciphertext,
            object_info,
            part_physical_sizes,
        }
    }

    fn legacy_ssec_multipart_metadata(key_bytes: [u8; 32], total_plaintext: usize) -> HashMap<String, String> {
        HashMap::from([
            ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
            (
                "x-amz-server-side-encryption-customer-key-md5".to_string(),
                BASE64_STANDARD.encode_to_string(md5_bytes(key_bytes)),
            ),
            (
                "x-amz-server-side-encryption-customer-original-size".to_string(),
                total_plaintext.to_string(),
            ),
            (TEST_NONCE_HEADER.to_string(), BASE64_STANDARD.encode_to_string(LEGACY_FIXTURE_BASE_NONCE)),
        ])
    }

    async fn build_legacy_ssec_multipart_fixture(key_bytes: [u8; 32], part_plain_sizes: &[usize]) -> LegacyMultipartFixture {
        let total_plaintext: usize = part_plain_sizes.iter().sum();
        build_legacy_multipart_fixture(
            "bucket",
            "legacy-multipart",
            key_bytes,
            part_plain_sizes,
            legacy_ssec_multipart_metadata(key_bytes, total_plaintext),
        )
        .await
    }

    /// Single-part object encrypted with the v2 fixed-frame writer, carrying
    /// the frame-layout marker bound to its `data_dir`.
    async fn build_v2_singlepart_fixture(key_bytes: [u8; 32], plain_size: usize) -> LegacyMultipartFixture {
        let plaintext = legacy_fixture_part_plaintext(1, plain_size);
        let mut ciphertext = Vec::new();
        rustfs_rio::EncryptReader::new_v2(Cursor::new(plaintext.clone()), key_bytes, LEGACY_FIXTURE_BASE_NONCE)
            .read_to_end(&mut ciphertext)
            .await
            .expect("encrypt v2 single-part fixture");

        let data_dir = Uuid::from_u128(2);
        let mut user_defined = legacy_ssec_multipart_metadata(key_bytes, plain_size);
        rustfs_utils::http::insert_str(&mut user_defined, ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX, data_dir.to_string());

        let parts = vec![ObjectPartInfo {
            number: 1,
            size: ciphertext.len(),
            actual_size: plaintext.len() as i64,
            ..Default::default()
        }];
        let object_info = ObjectInfo {
            bucket: "bucket".to_string(),
            name: "v2-single-part".to_string(),
            size: ciphertext.len() as i64,
            data_dir: Some(data_dir),
            etag: Some("d41d8cd98f00b204e9800998ecf8427e".to_string()),
            parts: Arc::new(parts),
            user_defined: Arc::new(user_defined),
            ..Default::default()
        };

        LegacyMultipartFixture {
            plaintext,
            ciphertext,
            object_info,
            part_physical_sizes: Vec::new(),
        }
    }

    /// Serves exactly the ciphertext window the plan schedules — the contract the
    /// erasure layer honors for `(storage_offset, storage_length)` — then decodes
    /// the body end to end. Returns the body, the plan offsets, and the reported
    /// object size.
    async fn read_via_seek_window(
        fixture: &LegacyMultipartFixture,
        rs: Option<HTTPRangeSpec>,
        opts: &ObjectOptions,
        headers: &HeaderMap<HeaderValue>,
    ) -> (Vec<u8>, usize, i64, i64) {
        let plan = ReadPlan::build(rs.clone(), &fixture.object_info, opts, headers)
            .await
            .expect("plan should build for seek window read");
        let start = plan.storage_offset;
        let window_len = usize::try_from(plan.storage_length).expect("storage length fits usize");
        assert!(
            start + window_len <= fixture.ciphertext.len(),
            "plan window [{start}, {}) exceeds ciphertext length {}",
            start + window_len,
            fixture.ciphertext.len()
        );
        let window = fixture.ciphertext[start..start + window_len].to_vec();

        let (mut reader, offset, length) =
            GetObjectReader::new(Box::new(Cursor::new(window)), rs, &fixture.object_info, opts, headers)
                .await
                .expect("seek window read should build a reader");
        assert_eq!(offset, start, "reader offsets must match the probed plan");
        assert_eq!(length, plan.storage_length, "reader length must match the probed plan");

        let mut body = Vec::new();
        reader.read_to_end(&mut body).await.expect("decode seek window body");
        (body, offset, length, reader.object_info.size)
    }

    fn range(start: i64, end: i64) -> HTTPRangeSpec {
        HTTPRangeSpec {
            is_suffix_length: false,
            start,
            end,
        }
    }

    #[test]
    fn test_get_legacy_encrypted_offsets_math() {
        let parts = vec![
            ObjectPartInfo {
                number: 1,
                size: 1_000,
                actual_size: 800,
                ..Default::default()
            },
            ObjectPartInfo {
                number: 2,
                size: 700,
                actual_size: 500,
                ..Default::default()
            },
            ObjectPartInfo {
                number: 3,
                size: 400,
                actual_size: 300,
                ..Default::default()
            },
        ];
        let oi = ObjectInfo {
            size: 2_100,
            parts: Arc::new(parts),
            ..Default::default()
        };

        // Head range inside part 1 covers only part 1 but exposes the full tail plaintext.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 0, 10), Some((0, 1_000, 0, 0, 1_600)));
        // Range ending exactly on the part 1 plaintext boundary stays within part 1.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 700, 100), Some((0, 1_000, 700, 0, 1_600)));
        // One byte further crosses into part 2.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 700, 101), Some((0, 1_700, 700, 0, 1_600)));
        // Range starting exactly at the part 2 boundary skips part 1 physically.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 800, 10), Some((1_000, 700, 0, 1, 800)));
        // Last byte of the object covers only part 3.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 1_599, 1), Some((1_700, 400, 299, 2, 300)));
        // Range spanning all parts covers the whole physical object.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 10, 1_590), Some((0, 2_100, 10, 0, 1_600)));
        // Out-of-bounds offset yields no seek plan.
        assert_eq!(get_legacy_encrypted_offsets(&oi, 1_600, 1), None);
        assert_eq!(get_legacy_encrypted_offsets(&oi, 1_599, 2), None);
        assert_eq!(get_legacy_encrypted_offsets(&oi, -1, 1), None);
        assert_eq!(get_legacy_encrypted_offsets(&oi, 0, 0), None);
        assert_eq!(get_legacy_encrypted_offsets(&oi, i64::MAX, 2), None);
    }

    #[test]
    fn test_legacy_part_layout_validation_rejects_invalid_totals() {
        let assert_falls_back_to_object_size = |parts: Vec<ObjectPartInfo>| {
            let object_info = ObjectInfo {
                size: 123,
                parts: Arc::new(parts),
                ..Default::default()
            };
            assert_eq!(
                encrypted_plaintext_size(&object_info, true, false, None).expect("invalid legacy layout should fall back"),
                123
            );
        };
        let valid = vec![
            ObjectPartInfo {
                size: 7,
                actual_size: 5,
                ..Default::default()
            },
            ObjectPartInfo {
                size: 11,
                actual_size: 9,
                ..Default::default()
            },
        ];
        assert_eq!(legacy_part_layout_totals(&valid), Some((18, 14)));
        let object_info_without_recorded_size = ObjectInfo {
            size: 18,
            parts: Arc::new(valid.clone()),
            ..Default::default()
        };
        assert_eq!(
            encrypted_plaintext_size(&object_info_without_recorded_size, true, false, None).expect("legacy total should resolve"),
            14
        );
        assert_eq!(
            encrypted_plaintext_size(&object_info_without_recorded_size, true, false, Some(13))
                .expect("recorded total should win"),
            13
        );

        for actual_size in [0, -1] {
            let mut invalid = valid.clone();
            invalid[0].actual_size = actual_size;
            assert_eq!(legacy_part_layout_totals(&invalid), None);
            assert_falls_back_to_object_size(invalid);
        }
        assert_falls_back_to_object_size(Vec::new());

        let mut plaintext_overflow = valid.clone();
        plaintext_overflow[0].actual_size = i64::MAX;
        assert_eq!(legacy_part_layout_totals(&plaintext_overflow), None);
        assert_falls_back_to_object_size(plaintext_overflow.clone());
        let plaintext_overflow_info = ObjectInfo {
            parts: Arc::new(plaintext_overflow),
            ..Default::default()
        };
        assert_eq!(get_legacy_encrypted_offsets(&plaintext_overflow_info, 0, 1), None);

        let outer_plaintext_overflow = ObjectInfo {
            parts: Arc::new(vec![
                ObjectPartInfo {
                    size: 1,
                    actual_size: i64::MAX - 1,
                    ..Default::default()
                },
                ObjectPartInfo {
                    size: 1,
                    actual_size: 10,
                    ..Default::default()
                },
            ]),
            ..Default::default()
        };
        assert_eq!(get_legacy_encrypted_offsets(&outer_plaintext_overflow, i64::MAX - 1, 1), None);

        #[cfg(target_pointer_width = "64")]
        {
            let mut physical_overflow = valid;
            physical_overflow[0].size = usize::try_from(i64::MAX).expect("i64::MAX fits usize on 64-bit targets");
            assert_eq!(legacy_part_layout_totals(&physical_overflow), None);
            let physical_overflow_info = ObjectInfo {
                parts: Arc::new(physical_overflow),
                ..Default::default()
            };
            assert_eq!(get_legacy_encrypted_offsets(&physical_overflow_info, 5, 1), None);

            let conversion_overflow_size = usize::try_from(i64::MAX).expect("i64::MAX fits usize on 64-bit targets") + 1;
            let conversion_overflow = vec![ObjectPartInfo {
                size: conversion_overflow_size,
                actual_size: 1,
                ..Default::default()
            }];
            assert_eq!(legacy_part_layout_totals(&conversion_overflow), None);
            let conversion_overflow_info = ObjectInfo {
                parts: Arc::new(conversion_overflow),
                ..Default::default()
            };
            assert_eq!(get_legacy_encrypted_offsets(&conversion_overflow_info, 0, 1), None);

            let outer_physical_overflow = ObjectInfo {
                parts: Arc::new(vec![
                    ObjectPartInfo {
                        size: usize::try_from(i64::MAX).expect("i64::MAX fits usize on 64-bit targets"),
                        actual_size: 1,
                        ..Default::default()
                    },
                    ObjectPartInfo {
                        size: 1,
                        actual_size: 1,
                        ..Default::default()
                    },
                    ObjectPartInfo {
                        size: 1,
                        actual_size: 1,
                        ..Default::default()
                    },
                ]),
                ..Default::default()
            };
            assert_eq!(get_legacy_encrypted_offsets(&outer_physical_overflow, 2, 1), None);
        }
    }

    #[tokio::test]
    async fn test_legacy_ssec_multipart_range_seek_byte_exact_matrix() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x71; 32];
            // Part plaintexts exercise multi-block (2 x 8192 + tail), block + tail,
            // and short single-block segments.
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions::default();
            let total_plaintext = fixture.plaintext.len() as i64;
            let phys = &fixture.part_physical_sizes;

            // (range, expected physical offset, expected physical length)
            let cases: Vec<(HTTPRangeSpec, usize, i64, &str)> = vec![
                (range(0, 9), 0, phys[0] as i64, "head of part 1"),
                (range(20_100, 20_199), fixture.physical_part_start(1), phys[1] as i64, "inside part 2"),
                (range(33_900, 33_999), fixture.physical_part_start(2), phys[2] as i64, "tail of part 3"),
                (
                    HTTPRangeSpec {
                        is_suffix_length: true,
                        start: 100,
                        end: -1,
                    },
                    fixture.physical_part_start(2),
                    phys[2] as i64,
                    "suffix range",
                ),
                (range(19_999, 20_000), 0, (phys[0] + phys[1]) as i64, "part 1/2 boundary straddle"),
                (
                    range(8_191, 8_193),
                    0,
                    phys[0] as i64,
                    "8 KiB encrypted-block boundary straddle in part 1",
                ),
                (range(19_999, 19_999), 0, phys[0] as i64, "last byte of part 1"),
                (
                    range(20_000, 20_000),
                    fixture.physical_part_start(1),
                    phys[1] as i64,
                    "first byte of part 2",
                ),
                (range(100, 33_950), 0, fixture.ciphertext.len() as i64, "range spanning all parts"),
                (range(0, total_plaintext - 1), 0, fixture.ciphertext.len() as i64, "full range"),
                (
                    range(29_000, total_plaintext - 1),
                    fixture.physical_part_start(2),
                    phys[2] as i64,
                    "aligned suffix from part 3 start",
                ),
                (
                    range(20_000, 29_100),
                    fixture.physical_part_start(1),
                    (phys[1] + phys[2]) as i64,
                    "part 2 into part 3",
                ),
            ];

            for (rs, expected_offset, expected_length, label) in cases {
                let (start, len) = rs.get_offset_length(total_plaintext).expect("valid case range");
                let expected_body =
                    &fixture.plaintext[start..start + usize::try_from(len).expect("valid range length fits usize")];

                let (body, offset, length, reported_size) = read_via_seek_window(&fixture, Some(rs), &opts, &headers).await;

                assert_eq!(offset, expected_offset, "{label}: physical offset");
                assert_eq!(length, expected_length, "{label}: physical length");
                assert_eq!(reported_size, len, "{label}: reported plaintext size");
                assert_eq!(body.len(), expected_body.len(), "{label}: body length");
                assert_eq!(body, expected_body, "{label}: body bytes");
            }
        })
        .await;
    }

    /// The amplification-inversion guard: a small Range inside part 2 must schedule
    /// only part 2 and must not pull more than part 2's ciphertext. The stream is
    /// served from the planned offset all the way to the object end WITHOUT an end
    /// truncation, so the covering-part bound is a real measurement of what the
    /// decode chain pulls, not an artifact of window slicing. Reverting the Legacy
    /// plan to the conservative `(0, oi.size)` full read fails the offset/length
    /// assertions, and the pull bound as well: skipping the 20_100-byte plaintext
    /// prefix would force the chain to pull all of part 1 first.
    #[tokio::test]
    async fn test_legacy_ssec_multipart_mid_range_reads_only_covering_part() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x72; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions::default();
            // 100 plaintext bytes inside part 2 (global plaintext [20_100, 20_200)).
            let rs = range(20_100, 20_199);

            let plan = ReadPlan::build(Some(rs.clone()), &fixture.object_info, &opts, &headers)
                .await
                .expect("plan should build for mid range");
            let covering_part_physical = fixture.part_physical_sizes[1] as u64;
            let object_physical = fixture.ciphertext.len() as u64;
            assert_eq!(
                plan.storage_offset,
                fixture.physical_part_start(1),
                "must seek to the covering part boundary"
            );
            assert_eq!(plan.storage_length as u64, covering_part_physical, "must schedule only the covering part");

            // Serve everything from the planned offset to the object end; the chain
            // itself decides how much to pull.
            let (spy, spy_bytes) = SpyReader::new(Cursor::new(fixture.ciphertext[plan.storage_offset..].to_vec()));
            let (mut reader, _, _) = GetObjectReader::new(Box::new(spy), Some(rs), &fixture.object_info, &opts, &headers)
                .await
                .expect("mid range read should build a reader");
            let mut body = Vec::new();
            reader.read_to_end(&mut body).await.expect("decode mid range body");
            let pulled = spy_bytes.load(std::sync::atomic::Ordering::Relaxed);

            assert_eq!(body, &fixture.plaintext[20_100..20_200], "mid range body must stay byte-exact");
            assert!(
                pulled <= covering_part_physical,
                "physical read {pulled} exceeds covering part {covering_part_physical}"
            );
            assert!(
                pulled < object_physical,
                "physical read {pulled} must stay below the whole object {object_physical}"
            );
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_ssec_multipart_part_number_get_seeks_to_part() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x73; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions {
                part_number: Some(2),
                ..Default::default()
            };

            let (body, offset, length, reported_size) = read_via_seek_window(&fixture, None, &opts, &headers).await;

            assert_eq!(offset, fixture.physical_part_start(1), "partNumber GET must seek to part 2");
            assert_eq!(length, fixture.part_physical_sizes[1] as i64, "partNumber GET must cover only part 2");
            assert_eq!(reported_size, 9_000);
            assert_eq!(body, &fixture.plaintext[20_000..29_000], "partNumber body must stay byte-exact");
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_single_part_multipart_object_keeps_full_read_shape() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x75; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions::default();
            let rs = range(5_000, 5_099);

            let (body, offset, length, reported_size) = read_via_seek_window(&fixture, Some(rs), &opts, &headers).await;

            // A single-part object degenerates to the previous full-object plan.
            assert_eq!(offset, 0);
            assert_eq!(length, fixture.ciphertext.len() as i64);
            assert_eq!(reported_size, 100);
            assert_eq!(body, &fixture.plaintext[5_000..5_100]);
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_kill_switch_restores_full_read() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("false"))], async {
            let key_bytes = [0x76; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions::default();
            let rs = range(33_900, 33_999);

            let (body, offset, length, reported_size) = read_via_seek_window(&fixture, Some(rs), &opts, &headers).await;

            assert_eq!(offset, 0, "kill switch must restore the conservative full read");
            assert_eq!(length, fixture.ciphertext.len() as i64);
            assert_eq!(reported_size, 100);
            assert_eq!(body, &fixture.plaintext[33_900..34_000], "kill switch path must stay byte-exact");
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_defaults_enabled() {
        let key_bytes = [0x7D; 32];

        // The unset-env default must behave exactly like the explicit opt-in:
        // an eligible multipart object seeks to the covering part boundary
        // instead of reading the whole ciphertext.
        let default_plan = async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, None::<&str>)], async {
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let plan = ReadPlan::build(
                Some(range(33_900, 33_999)),
                &fixture.object_info,
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await
            .expect("default read plan should build");
            (plan.storage_offset, plan.storage_length, fixture.ciphertext.len())
        })
        .await;

        let opt_in_plan = async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let plan = ReadPlan::build(
                Some(range(33_900, 33_999)),
                &fixture.object_info,
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await
            .expect("opt-in read plan should build");
            (plan.storage_offset, plan.storage_length)
        })
        .await;

        assert_eq!((default_plan.0, default_plan.1), opt_in_plan, "unset env must match explicit opt-in");
        assert_ne!(default_plan.0, 0, "an eligible range read must seek past the leading parts");
        assert!(
            (default_plan.1 as usize) < default_plan.2,
            "an eligible range read must not span the whole ciphertext"
        );
    }

    #[tokio::test]
    async fn test_legacy_range_seek_marker_validation() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let fixture = build_legacy_ssec_multipart_fixture([0x7F; 32], &[20_000, 9_000, 5_000]).await;
            let recorded_size = fixture
                .object_info
                .encryption_original_size()
                .expect("original size metadata should parse");
            assert!(!legacy_encrypted_seek_eligible(&fixture.object_info, true, false, 100, None));
            let layout_token = fixture
                .object_info
                .data_dir
                .expect("fixture data dir should exist")
                .to_string();
            let rustfs_key = format!("x-rustfs-internal-{ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX}");
            let minio_key = format!("x-minio-internal-{ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX}");
            let cases = [
                (
                    "wrong",
                    HashMap::from([
                        (rustfs_key.clone(), "wrong-token".to_string()),
                        (minio_key.clone(), "wrong-token".to_string()),
                    ]),
                    false,
                ),
                (
                    "empty",
                    HashMap::from([(rustfs_key.clone(), String::new()), (minio_key.clone(), String::new())]),
                    false,
                ),
                (
                    "conflicting",
                    HashMap::from([
                        (rustfs_key.clone(), layout_token.clone()),
                        (minio_key.clone(), "wrong-token".to_string()),
                    ]),
                    false,
                ),
                ("rustfs only", HashMap::from([(rustfs_key, layout_token.clone())]), true),
                ("minio only", HashMap::from([(minio_key, layout_token)]), true),
            ];

            for (case, marker_metadata, expected) in cases {
                let mut object_info = fixture.object_info.clone();
                let metadata = Arc::make_mut(&mut object_info.user_defined);
                rustfs_utils::http::remove_str(metadata, ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX);
                metadata.extend(marker_metadata);
                assert_eq!(
                    legacy_encrypted_seek_eligible(&object_info, true, false, 100, recorded_size),
                    expected,
                    "{case}"
                );
            }
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_keeps_full_read_without_quorum_marker() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x7E; 32];
            let mut fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            rustfs_utils::http::remove_str(
                Arc::make_mut(&mut fixture.object_info.user_defined),
                ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
            );

            let (body, offset, length, reported_size) = read_via_seek_window(
                &fixture,
                Some(range(33_900, 33_999)),
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await;

            assert_eq!(offset, 0);
            assert_eq!(length, fixture.ciphertext.len() as i64);
            assert_eq!(reported_size, 100);
            assert_eq!(body, &fixture.plaintext[33_900..34_000]);
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_rejects_plaintext_total_mismatch() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x7C; 32];
            let mut fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let parts = Arc::make_mut(&mut fixture.object_info.parts);
            parts[0].actual_size = 19_000;

            let (body, offset, length, reported_size) = read_via_seek_window(
                &fixture,
                Some(range(33_900, 33_999)),
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await;

            assert_eq!(offset, 0, "a mismatched plaintext total must not control a physical seek");
            assert_eq!(length, fixture.ciphertext.len() as i64);
            assert_eq!(reported_size, 100);
            assert_eq!(body, &fixture.plaintext[33_900..34_000]);
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_gate_rejects_zero_actual_size_part() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x77; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let mut object_info = fixture.object_info.clone();
            {
                let parts = Arc::make_mut(&mut object_info.parts);
                parts[1].actual_size = 0;
            }
            let headers = ssec_headers_from_key(key_bytes);

            let plan = ReadPlan::build(Some(range(0, 9)), &object_info, &ObjectOptions::default(), &headers)
                .await
                .expect("plan should build for zero actual_size sample");

            assert_eq!(plan.storage_offset, 0, "a poisoned parts table must fall back to the full read");
            assert_eq!(plan.storage_length, object_info.size);
        })
        .await;
    }

    #[tokio::test]
    async fn multipart_full_read_preserves_legacy_zero_and_negative_part_sizes() {
        let key = [0x77; 32];
        let part_sizes = [5 * 1024 * 1024, 1024 * 1024];
        let encrypted = build_legacy_ssec_multipart_fixture(key, &part_sizes).await;
        // The encrypted case supplies the fixture key explicitly. This covers
        // full decrypted reads, not managed-key acquisition.
        for (kind, fixture, headers) in [
            ("compressed", compressed_multipart_fixture(&part_sizes).await, HeaderMap::new()),
            (
                "encrypted with supplied key",
                CompressedMultipartFixture {
                    object_info: encrypted.object_info,
                    stored: encrypted.ciphertext,
                    plaintext: encrypted.plaintext,
                },
                ssec_headers_from_key(key),
            ),
        ] {
            let source_etag = faster_hex::hex_string(Md5::digest(&fixture.plaintext).as_ref());
            assert_eq!(source_etag.len(), 32);
            assert_eq!(fixture.plaintext.len(), 6 * 1024 * 1024);
            for part_index in 0..part_sizes.len() {
                assert!(fixture.object_info.parts[part_index].actual_size > 0, "the selected part is nonempty");
                for actual_size in [0, -1] {
                    let mut object_info = fixture.object_info.clone();
                    object_info.etag = Some(source_etag.clone());
                    Arc::make_mut(&mut object_info.parts)[part_index].actual_size = actual_size;
                    let (mut reader, offset, length) = GetObjectReader::new(
                        Box::new(Cursor::new(fixture.stored.clone())),
                        None,
                        &object_info,
                        &ObjectOptions::default(),
                        &headers,
                    )
                    .await
                    .expect("the authoritative total size must keep full legacy reads available");
                    assert_eq!(offset, 0);
                    assert_eq!(length, i64::try_from(fixture.stored.len()).expect("stored size fits"));
                    let mut body = Vec::new();
                    reader
                        .stream
                        .read_to_end(&mut body)
                        .await
                        .expect("full read must reach EOF despite an unspecified per-part logical size");
                    assert_eq!(
                        body, fixture.plaintext,
                        "{kind}: part {part_index} with actual_size={actual_size} must not lose readable data"
                    );
                    assert_eq!(reader.object_info.etag.as_deref(), Some(source_etag.as_str()));
                }
            }
        }
    }

    /// The physical part sizes must add up to `oi.size` for a seek to be safe;
    /// inconsistent metadata must fall back to the previous full-object read
    /// instead of scheduling an erasure read past the object end.
    #[tokio::test]
    async fn test_legacy_range_seek_gate_rejects_inconsistent_physical_sum() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x7B; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let mut object_info = fixture.object_info.clone();
            object_info.size -= 3;
            let headers = ssec_headers_from_key(key_bytes);

            let plan = ReadPlan::build(Some(range(33_900, 33_999)), &object_info, &ObjectOptions::default(), &headers)
                .await
                .expect("plan should build for inconsistent physical sum sample");

            assert_eq!(plan.storage_offset, 0, "an inconsistent physical sum must fall back to the full read");
            assert_eq!(plan.storage_length, object_info.size);
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_range_seek_gate_rejects_compressed_encrypted_object() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x78; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let mut user_defined = fixture.object_info.user_defined.as_ref().clone();
            // "lz4" parses in both the default and the rio-v2 build (the MinIO
            // "klauspost/compress/s2" token is only recognized under rio-v2).
            user_defined.insert("x-minio-internal-compression".to_string(), "lz4".to_string());
            user_defined.insert("x-minio-internal-actual-size".to_string(), "34000".to_string());
            let mut object_info = fixture.object_info.clone();
            object_info.user_defined = Arc::new(user_defined);
            let headers = ssec_headers_from_key(key_bytes);

            let plan = ReadPlan::build(Some(range(33_900, 33_999)), &object_info, &ObjectOptions::default(), &headers)
                .await
                .expect("plan should build for compressed encrypted sample");

            assert_eq!(plan.storage_offset, 0, "compressed + encrypted must keep the conservative full read");
            assert_eq!(plan.storage_length, object_info.size);
        })
        .await;
    }

    #[tokio::test]
    async fn test_legacy_ssec_multipart_seek_tamper_fails_hard_with_no_plaintext() {
        async_with_vars([(ENV_RUSTFS_ENCRYPTED_RANGE_SEEK, Some("true"))], async {
            let key_bytes = [0x7A; 32];
            let fixture = build_legacy_ssec_multipart_fixture(key_bytes, &[20_000, 9_000, 5_000]).await;
            let headers = ssec_headers_from_key(key_bytes);
            let opts = ObjectOptions::default();
            let rs = range(33_900, 33_999);

            let plan = ReadPlan::build(Some(rs.clone()), &fixture.object_info, &opts, &headers)
                .await
                .expect("plan should build for tamper test");
            let start = plan.storage_offset;
            let window_len = usize::try_from(plan.storage_length).expect("tamper window length fits usize");
            assert_eq!(start, fixture.physical_part_start(2), "tamper test must exercise the seek path");

            let mut window = fixture.ciphertext[start..start + window_len].to_vec();
            // Flip one ciphertext byte inside the first encrypted block the seek
            // lands on (past the 8-byte header and the length prefix).
            window[64] ^= 0xFF;

            let (mut reader, _, _) =
                GetObjectReader::new(Box::new(Cursor::new(window)), Some(rs), &fixture.object_info, &opts, &headers)
                    .await
                    .expect("reader builds before the tampered block is decrypted");

            let mut body = Vec::new();
            let err = reader
                .read_to_end(&mut body)
                .await
                .expect_err("tampered ciphertext must fail the read");
            assert!(body.is_empty(), "no unauthenticated plaintext may be emitted, got {} bytes", body.len());
            let message = err.to_string();
            assert!(
                message.contains("decrypt") || message.contains("CRC32") || message.contains("Invalid encrypted block"),
                "unexpected tamper error: {message}"
            );
        })
        .await;
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_get_object_reader_uses_dare_package_offset_for_large_ssec_ranges() {
        const DARE_PACKAGE_SIZE: usize = 64 * 1024 + 32;

        let plaintext = vec![0x7Bu8; 2 * 64 * 1024 + 97];
        let customer_key = [0x61; 32];
        let object_key = [0x68; 32];
        let bucket = "bucket";
        let object = "large-range-object";
        let mut encrypted = Vec::new();
        crate::io_support::rio::EncryptReader::new_with_object_key(Cursor::new(plaintext.clone()), object_key)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt large ranged object");

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            user_defined: Arc::new(HashMap::from([
                (TEST_OBJECT_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(object_key)),
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(customer_key)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
            ])),
            ..Default::default()
        };
        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 70_000,
            end: 70_063,
        };

        let (mut reader, offset, _length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted[DARE_PACKAGE_SIZE..].to_vec())),
            Some(range),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(customer_key),
        )
        .await
        .expect("large ssec range read should be supported");

        let mut actual = Vec::new();
        reader.read_to_end(&mut actual).await.expect("read ranged decrypted object");

        assert_eq!(
            offset, DARE_PACKAGE_SIZE,
            "rio_v2 encrypted ranges should start from the second DARE package"
        );
        assert_eq!(reader.object_info.size, 64);
        assert_eq!(actual, plaintext[70_000..70_064]);
    }

    #[tokio::test]
    async fn test_get_object_reader_decrypts_then_decompresses_before_applying_range() {
        let plaintext = b"abcdefghijklmnopqrstuvwxyz".to_vec();
        let key_bytes = [0x51; 32];
        let bucket = "bucket";
        let object = "compressed-object";
        let nonce = md5_bytes(format!("{bucket}-{object}").as_bytes());
        let mut base_nonce = [0u8; 12];
        base_nonce.copy_from_slice(&nonce[..12]);

        let mut compressed = Vec::new();
        rustfs_rio::CompressReader::new(Cursor::new(plaintext.clone()), CompressionAlgorithm::default())
            .read_to_end(&mut compressed)
            .await
            .expect("compress plaintext");

        let mut encrypted = Vec::new();
        rustfs_rio::EncryptReader::new(Cursor::new(compressed.clone()), key_bytes, base_nonce)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt compressed plaintext");

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            user_defined: Arc::new(HashMap::from([
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(key_bytes)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
                ("x-minio-internal-compression".to_string(), CompressionAlgorithm::default().to_string()),
                ("x-minio-internal-actual-size".to_string(), plaintext.len().to_string()),
            ])),
            ..Default::default()
        };
        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 5,
            end: 11,
        };

        let (mut reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted.clone())),
            Some(range),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("encrypted+compressed range read should be supported");

        let mut actual = Vec::new();
        reader
            .read_to_end(&mut actual)
            .await
            .expect("read ranged decompressed plaintext");

        assert_eq!(offset, 0);
        assert_eq!(length, encrypted.len() as i64);
        assert_eq!(reader.object_info.size, 7);
        assert_eq!(actual, b"fghijkl");
    }

    #[cfg(feature = "rio-v2")]
    #[tokio::test]
    async fn test_get_object_reader_uses_compression_index_for_encrypted_ranges() {
        use crate::io_support::rio::TryGetIndex;

        let plaintext: Vec<u8> = (0..(10 * 1024 * 1024 + 123_456))
            .map(|i| (((i as u64).wrapping_mul(1_103_515_245).wrapping_add(12_345) >> 16) & 0xFF) as u8)
            .collect();
        let customer_key = [0x73; 32];
        let object_key = [0x74; 32];
        let bucket = "bucket";
        let object = "compressed-large-object";
        let mut compressor = crate::io_support::rio::CompressReader::with_encrypted_padding(
            Cursor::new(plaintext.clone()),
            CompressionAlgorithm::default(),
        );
        let mut compressed = Vec::new();
        compressor
            .read_to_end(&mut compressed)
            .await
            .expect("compress large plaintext");

        let index = compressor
            .try_get_index()
            .cloned()
            .expect("large rio_v2 encrypted+compressed object should expose a compression index");
        let stored_index = crate::io_support::rio::compression_index_storage_bytes(&index);
        let decoded_index = crate::io_support::rio::decode_compression_index_bytes(&stored_index)
            .expect("decode stored encrypted compression index");

        let range = HTTPRangeSpec {
            is_suffix_length: false,
            start: 5 * 1024 * 1024,
            end: 5 * 1024 * 1024 + 63,
        };
        let original_offsets = index
            .find(range.start)
            .expect("find large-range compression block in original index");
        let (comp_off, uncomp_off) = decoded_index
            .find(range.start)
            .expect("find large-range compression block in stored index");
        assert_eq!(original_offsets, (comp_off, uncomp_off));
        assert!(comp_off > DARE_PAYLOAD_SIZE);
        assert!(uncomp_off <= range.start);

        let expected_storage_offset = ((comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE) as usize;
        let expected_decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
        assert!(expected_storage_offset > 0);
        assert!(expected_decrypt_skip >= 0);

        let mut encrypted = Vec::new();
        crate::io_support::rio::EncryptReader::new_with_object_key(Cursor::new(compressed.clone()), object_key)
            .read_to_end(&mut encrypted)
            .await
            .expect("encrypt compressed plaintext");

        let expected_sequence_number = u32::try_from(comp_off / DARE_PAYLOAD_SIZE).expect("sequence number fits in u32");
        let chunk_offset = comp_off as usize;
        let chunk_type = compressed[chunk_offset];
        let chunk_len = (compressed[chunk_offset + 1] as usize)
            | ((compressed[chunk_offset + 2] as usize) << 8)
            | ((compressed[chunk_offset + 3] as usize) << 16);
        assert!(matches!(chunk_type, 0x00 | 0x01 | 0xff | 0xfe));
        assert!(chunk_offset + 4 + chunk_len <= compressed.len());

        let mut decrypted_tail = Vec::new();
        crate::io_support::rio::DecryptReader::new_with_object_key_and_sequence(
            Cursor::new(encrypted[expected_storage_offset..].to_vec()),
            object_key,
            expected_sequence_number,
        )
        .read_to_end(&mut decrypted_tail)
        .await
        .expect("decrypt package-aligned ciphertext tail");
        assert_eq!(
            &decrypted_tail[expected_decrypt_skip as usize..],
            &compressed[comp_off as usize..],
            "package-aligned decryption plus decrypt_skip must land on the indexed S2 chunk boundary"
        );

        let mut direct_reader = crate::io_support::rio::DecompressReader::new(
            Cursor::new(decrypted_tail[expected_decrypt_skip as usize..].to_vec()),
            CompressionAlgorithm::default(),
        );
        let mut direct_plaintext = Vec::new();
        direct_reader
            .read_to_end(&mut direct_plaintext)
            .await
            .expect("decompress tail starting at indexed S2 chunk boundary");
        assert_eq!(direct_plaintext, plaintext[uncomp_off as usize..]);

        let object_info = ObjectInfo {
            bucket: bucket.to_string(),
            name: object.to_string(),
            size: encrypted.len() as i64,
            parts: Arc::new(vec![ObjectPartInfo {
                etag: String::new(),
                number: 1,
                size: encrypted.len(),
                actual_size: plaintext.len() as i64,
                index: Some(stored_index),
                ..Default::default()
            }]),
            user_defined: Arc::new(HashMap::from([
                (TEST_OBJECT_KEY_HEADER.to_string(), BASE64_STANDARD.encode_to_string(object_key)),
                ("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
                (
                    "x-amz-server-side-encryption-customer-key-md5".to_string(),
                    BASE64_STANDARD.encode_to_string(md5_bytes(customer_key)),
                ),
                (
                    "x-amz-server-side-encryption-customer-original-size".to_string(),
                    plaintext.len().to_string(),
                ),
                (
                    "x-minio-internal-compression".to_string(),
                    crate::io_support::rio::compression_metadata_value(CompressionAlgorithm::default()),
                ),
                ("x-minio-internal-actual-size".to_string(), plaintext.len().to_string()),
            ])),
            ..Default::default()
        };

        let plan = ReadPlan::build(
            Some(range.clone()),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(customer_key),
        )
        .await
        .expect("build encrypted+compressed read plan");
        assert_eq!(plan.storage_offset, expected_storage_offset);
        assert_eq!(plan.storage_length, encrypted.len() as i64 - expected_storage_offset as i64);
        assert_eq!(plan.object_size, 64);
        match plan.transform {
            ReadTransform::Encrypted {
                sequence_number,
                decrypt_skip,
                plaintext_offset,
                plaintext_length,
                ..
            } => {
                assert_eq!(sequence_number, expected_sequence_number);
                assert_eq!(decrypt_skip, expected_decrypt_skip as usize);
                assert_eq!(plaintext_offset as i64, range.start - uncomp_off);
                assert_eq!(plaintext_length, 64);
            }
            _ => panic!("expected encrypted read plan"),
        }

        let (mut reader, offset, length) = GetObjectReader::new(
            Box::new(Cursor::new(encrypted[expected_storage_offset..].to_vec())),
            Some(range.clone()),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(customer_key),
        )
        .await
        .expect("encrypted+compressed indexed range read should be supported");

        let mut actual = Vec::new();
        reader
            .read_to_end(&mut actual)
            .await
            .expect("read indexed encrypted+compressed range");

        assert_eq!(offset, expected_storage_offset);
        assert_eq!(length, encrypted.len() as i64 - expected_storage_offset as i64);
        assert_eq!(reader.object_info.size, 64);
        assert_eq!(actual, plaintext[range.start as usize..range.start as usize + 64]);
    }

    // =============== v2 fixed-frame single-part seek ===============

    #[test]
    fn test_get_v2_frame_offsets_math() {
        let frame = V2_FRAME_CIPHERTEXT_LEN;
        let block = V2_FRAME_PLAINTEXT_LEN;
        // 3 full frames + a 500-byte final frame (2-byte uvarint) + end marker.
        let plaintext_size = 3 * block + 500;
        let final_frame = 8 + 2 + 500 + 16;
        let oi = ObjectInfo {
            size: 3 * frame + final_frame + 8,
            ..Default::default()
        };

        // Head range stays inside frame 0.
        let (off, len, skip, seq, remaining) = get_v2_frame_offsets(&oi, 0, 100, plaintext_size).expect("head range plans");
        assert_eq!((off, len, skip, seq), (0, frame, 0, 0));
        assert_eq!(remaining, plaintext_size);

        // A range crossing the first frame boundary covers frames 0..=1.
        let (off, len, skip, seq, _) = get_v2_frame_offsets(&oi, block - 1, 2, plaintext_size).expect("boundary range plans");
        assert_eq!((off, len, skip, seq), (0, 2 * frame, (block - 1) as usize, 0));

        // A range starting exactly on frame 1 seeks past frame 0.
        let (off, len, skip, seq, remaining) = get_v2_frame_offsets(&oi, block, 10, plaintext_size).expect("aligned range plans");
        assert_eq!((off, len, skip, seq), (frame, frame, 0, 1));
        assert_eq!(remaining, plaintext_size - block);

        // A tail range inside the final frame reads through the ciphertext end.
        let (off, len, skip, seq, remaining) =
            get_v2_frame_offsets(&oi, 3 * block + 100, 200, plaintext_size).expect("tail range plans");
        assert_eq!((off, len, skip, seq), (3 * frame, final_frame + 8, 100, 3));
        assert_eq!(remaining, 500);

        // A range ending inside the LAST full frame also extends to the
        // ciphertext end, so a drain-to-plaintext-end read still observes the
        // authenticated final frame.
        let (off, len, skip, seq, _) =
            get_v2_frame_offsets(&oi, 2 * block + 1, block - 1, plaintext_size).expect("last-full-frame range plans");
        assert_eq!((off, len, skip, seq), (2 * frame, oi.size - 2 * frame, 1, 2));

        // Out-of-bounds and degenerate requests fall back.
        assert!(get_v2_frame_offsets(&oi, plaintext_size - 10, 20, plaintext_size).is_none());
        assert!(get_v2_frame_offsets(&oi, -1, 10, plaintext_size).is_none());
        assert!(get_v2_frame_offsets(&oi, 0, 0, plaintext_size).is_none());
    }

    #[tokio::test]
    async fn test_v2_singlepart_range_seek_byte_exact_matrix() {
        let key_bytes = [0x6B; 32];
        let block = V2_FRAME_PLAINTEXT_LEN as usize;
        let fixture = build_v2_singlepart_fixture(key_bytes, 3 * block + 500).await;

        let cases = [
            (0_i64, 99_i64),
            ((block - 1) as i64, block as i64),
            (block as i64, (block + 9) as i64),
            ((2 * block + 5) as i64, (3 * block + 480) as i64),
        ];
        for (start, end) in cases {
            let (body, offset, length, _) = read_via_seek_window(
                &fixture,
                Some(range(start, end)),
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await;
            let expected = &fixture.plaintext[start as usize..=end as usize];
            assert_eq!(body, expected, "range {start}-{end} must be byte-exact");
            let expected_offset = (start / V2_FRAME_PLAINTEXT_LEN) * V2_FRAME_CIPHERTEXT_LEN;
            assert_eq!(offset, usize::try_from(expected_offset).expect("offset fits"), "range {start}-{end}");
            assert!(
                length < fixture.ciphertext.len() as i64 || start < V2_FRAME_PLAINTEXT_LEN,
                "a mid-object range must not span the whole ciphertext"
            );
        }
    }

    #[tokio::test]
    async fn test_v2_singlepart_block_aligned_object_serves_tail_ranges() {
        // A block-aligned object ends in an EMPTY authenticated final frame.
        // Ranges ending on the last plaintext byte plan a window that excludes
        // that final frame; the ranged reader must not misread the window end
        // as truncation.
        let key_bytes = [0x6E; 32];
        let block = V2_FRAME_PLAINTEXT_LEN as usize;
        let fixture = build_v2_singlepart_fixture(key_bytes, 3 * block).await;

        for (start, end) in [
            (2 * block as i64 + 10, 3 * block as i64 - 1),
            (3 * block as i64 - 1, 3 * block as i64 - 1),
            (0, 3 * block as i64 - 1),
        ] {
            let (body, _, _, _) = read_via_seek_window(
                &fixture,
                Some(range(start, end)),
                &ObjectOptions::default(),
                &ssec_headers_from_key(key_bytes),
            )
            .await;
            assert_eq!(
                body,
                &fixture.plaintext[start as usize..=end as usize],
                "aligned-object range {start}-{end} must be byte-exact"
            );
        }
    }

    #[tokio::test]
    async fn test_v2_singlepart_seek_requires_a_matching_marker() {
        let key_bytes = [0x6C; 32];
        let block = V2_FRAME_PLAINTEXT_LEN as usize;
        let fixture = build_v2_singlepart_fixture(key_bytes, 2 * block + 40).await;

        // Marker bound to another data_dir (a copied/re-homed object): full read.
        let mut foreign = (*fixture.object_info.user_defined).clone();
        rustfs_utils::http::insert_str(&mut foreign, ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX, Uuid::from_u128(9).to_string());
        let mut object_info = fixture.object_info.clone();
        object_info.user_defined = Arc::new(foreign);
        let plan = ReadPlan::build(
            Some(range(block as i64, (block + 5) as i64)),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("mismatched marker still plans a conservative read");
        assert_eq!(plan.storage_offset, 0);
        assert_eq!(plan.storage_length, fixture.ciphertext.len() as i64);

        // No marker at all: full read.
        let mut unmarked = (*fixture.object_info.user_defined).clone();
        unmarked.retain(|key, _| !rustfs_utils::http::has_internal_suffix(key, ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX));
        let mut object_info = fixture.object_info.clone();
        object_info.user_defined = Arc::new(unmarked);
        let plan = ReadPlan::build(
            Some(range(block as i64, (block + 5) as i64)),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("markerless object plans a conservative read");
        assert_eq!(plan.storage_offset, 0);
    }

    #[tokio::test]
    async fn test_v2_singlepart_lying_marker_fails_closed() {
        // v1 ciphertext with a v2 marker planted on it: the seek positions the
        // read at a fake frame boundary, and decryption must fail — never
        // serve bytes from the wrong offset. The v1 writer frames per upstream
        // read, so a small-buffered source yields short (non-8-KiB) frames and
        // the fixed-frame math lands mid-frame.
        struct ShortReads<R> {
            inner: R,
            cap: usize,
        }
        impl<R: AsyncRead + Unpin> AsyncRead for ShortReads<R> {
            fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
                let cap = self.cap.min(buf.remaining());
                let mut tmp = vec![0u8; cap];
                let mut limited = ReadBuf::new(&mut tmp);
                match Pin::new(&mut self.inner).poll_read(cx, &mut limited) {
                    Poll::Ready(Ok(())) => {
                        buf.put_slice(limited.filled());
                        Poll::Ready(Ok(()))
                    }
                    other => other,
                }
            }
        }

        let key_bytes = [0x6D; 32];
        let block = V2_FRAME_PLAINTEXT_LEN as usize;
        let plaintext = legacy_fixture_part_plaintext(1, 3 * block);
        let mut ciphertext = Vec::new();
        rustfs_rio::EncryptReader::new(
            ShortReads {
                inner: Cursor::new(plaintext.clone()),
                cap: 5_000,
            },
            key_bytes,
            LEGACY_FIXTURE_BASE_NONCE,
        )
        .read_to_end(&mut ciphertext)
        .await
        .expect("encrypt v1 fixture");
        // The fixture premise: short frames mean the fixed-frame boundary is
        // not a real frame boundary in this ciphertext.
        assert_ne!(ciphertext[0..8][1], ((V2_FRAME_CIPHERTEXT_LEN - 8) & 0xFF) as u8, "frames must be short");

        let data_dir = Uuid::from_u128(3);
        let mut user_defined = legacy_ssec_multipart_metadata(key_bytes, 3 * block);
        rustfs_utils::http::insert_str(&mut user_defined, ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX, data_dir.to_string());
        let object_info = ObjectInfo {
            bucket: "bucket".to_string(),
            name: "lying-marker".to_string(),
            size: ciphertext.len() as i64,
            data_dir: Some(data_dir),
            etag: Some("d41d8cd98f00b204e9800998ecf8427e".to_string()),
            parts: Arc::new(vec![ObjectPartInfo {
                number: 1,
                size: ciphertext.len(),
                actual_size: (3 * block) as i64,
                ..Default::default()
            }]),
            user_defined: Arc::new(user_defined),
            ..Default::default()
        };

        let rs = range(block as i64, (block + 50) as i64);
        let plan = ReadPlan::build(
            Some(rs.clone()),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("plan still builds; failure must come from authentication");
        let start = plan.storage_offset;
        let window_len = usize::try_from(plan.storage_length).expect("window fits");
        let window = ciphertext[start.min(ciphertext.len())..(start + window_len).min(ciphertext.len())].to_vec();

        let (mut reader, _, _) = GetObjectReader::new(
            Box::new(Cursor::new(window)),
            Some(rs),
            &object_info,
            &ObjectOptions::default(),
            &ssec_headers_from_key(key_bytes),
        )
        .await
        .expect("reader construction succeeds; decryption fails at read time");
        let mut body = Vec::new();
        reader
            .read_to_end(&mut body)
            .await
            .expect_err("a lying frame-layout marker must fail closed, not serve plaintext");
    }
}