aws-s3-transfer 1.0.0

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

//! Download transfer state machine.
//!
//! [`DownloadTransfer`] resolves metadata and validation requirements through
//! discovery, then issues range reads and destination drains under the state lock.
//! Workers collect bytes and calculate required digests outside the lock. Only
//! successfully published ranges and their required writes supply checksum evidence.
//! The last completed work item claims exclusive completion ownership under the
//! lock, then verifies integrity and finalizes the destination after releasing it.

use std::cmp;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use bytes::BufMut;
use futures_util::future::{select, Either};

use crate::sdk_v1::copy_download_input_fields_to_get_object as copy_fields_to_get_object_request;

use crate::error::{self, ChunkRef, Error};
use crate::operation::download::body::{BodySlot, BodyWriter, ChunkOutput, DrainError, Drained};
use crate::operation::download::checksum::{DownloadIntegrity, RangeCompletion, RangeDigestPlan};
use crate::operation::download::context::{
    CompletionClaim, DownloadPendingReason, DownloadState, PendingClaim,
};
use crate::operation::download::discovery::{discover_obj, InitialChunk, ObjectDiscovery};
use crate::operation::download::observability::{
    DownloadDestination, DownloadEvent, DownloadExecutionState, DownloadObservability,
    DownloadRequestKind, DownloadRequestMeasurement, DownloadStateSnapshot, DownloadTerminalReport,
};
use crate::operation::download::read_ahead::ReadAhead;
use crate::operation::download::recv_buffer::{DrainMode, FillOutcome};
use crate::operation::download::ChunkMetadata;
use crate::operation::download::DownloadInput;
use crate::operation::download::ObjectMetadata;
use crate::runtime::buffer_pool::{
    AcquireError, BufferPool, Reservation, ReserveError, SegmentedBytes,
};
use crate::telemetry::TARGET_TRANSFER_DOWNLOAD;
use crate::transfer::{IoRequest, PollWork, Transfer, TransferContext, TransferId, WorkOutcome};
use crate::types::BucketType;
use aws_smithy_observability::unit_of_work::checksums::ChecksumCapture;
use aws_smithy_observability::unit_of_work::Capture;
use aws_smithy_types::error::display::DisplayErrorContext;
use tracing::Instrument;

/// Download transfer that generates and executes download work.
///
/// Clone shares all state via `Arc`.
#[derive(Debug, Clone)]
pub(crate) struct DownloadTransfer {
    inner: Arc<DownloadTransferInner>,
}

/// Internal state for download transfer.
#[derive(Debug)]
struct DownloadTransferInner {
    /// Common transfer lifecycle management
    ctx: TransferContext,
    /// State machine for work progression
    state: Mutex<DownloadState>,
    /// Direction-specific observation kept outside correctness state.
    observability: DownloadObservability,
    /// The original request
    request: Arc<DownloadInput>,
    /// Type of S3 bucket targeted by this operation.
    // TODO(vnext): unify bucket representation (name + kind) across operations.
    #[allow(dead_code)]
    bucket_type: BucketType,
    /// Chunk delivery + disk-write surface.
    writer: BodyWriter,
    /// Read-ahead window: bounds resident occupancy by holding `issued - released`
    /// under `read_ahead.window()`.
    read_ahead: ReadAhead,
    /// Object metadata from discovery (set once discovery completes)
    object_meta: std::sync::OnceLock<ObjectMetadata>,
    /// Object-integrity result (set once the download completes successfully)
    integrity_checks: std::sync::OnceLock<crate::types::IntegrityChecks>,
    /// Expected total bytes produced by this download, discovered from the response.
    expected_download_len: std::sync::OnceLock<u64>,
    /// Notified when discovery completes (success or failure)
    discovery_notify: tokio::sync::Notify,
    /// The object as a `download_objects` listing reported it, for a child download.
    listed: Option<super::ListedObject>,
}

/// Download-specific work data.
#[derive(Debug)]
pub(super) enum DownloadWork {
    /// Resolves object metadata, range geometry and the validation plan.
    Discovery,
    /// Collects one range, then publishes its bytes and accepted checksum evidence.
    GetObjectRange {
        /// Inclusive source-object bounds of this request.
        range: std::ops::RangeInclusive<u64>,
        /// Claimed delivery slot; taken once when execution starts.
        slot: Option<BodySlot>,
        /// `If-Match` condition pinning the request to the discovered version, when available.
        etag: Option<Arc<str>>,
        /// Additional checksum calculation required for this range.
        digest_plan: RangeDigestPlan,
    },
    /// Memory-pressure relief: flush the resident filled run to disk, returning
    /// its carrier charges before the transfer waits for more memory. Handled in
    /// `execute`; carries no data because it operates on the writer.
    DrainResident,
}

impl DownloadWork {
    /// Short name of the work kind for span fields.
    fn kind(&self) -> &'static str {
        match self {
            Self::Discovery => "discovery",
            Self::GetObjectRange { .. } => "get_object_range",
            Self::DrainResident => "drain_resident",
        }
    }
}

/// Early return if transfer is terminal (failed/cancelled by another work item).
macro_rules! bail_if_terminal {
    ($self:expr) => {
        if !$self.inner.ctx.is_active() {
            // No occupancy is freed before a drain. If decrementing the in-flight
            // count claims completion, drop the claim: cancellation's terminal path
            // owns the destination (see `CompletionClaim`).
            let _ = $self.decrement_in_flight(0, None);
            return WorkOutcome::Cancelled;
        }
    };
}

impl DownloadTransfer {
    pub(crate) fn new(
        ctx: TransferContext,
        bucket_type: BucketType,
        input: DownloadInput,
        writer: BodyWriter,
    ) -> Self {
        Self::new_listed(ctx, bucket_type, input, writer, None)
    }

    /// [`Self::new`] for an object a listing reported as `listed`, which discovery
    /// may use to skip HeadObject.
    pub(crate) fn new_listed(
        ctx: TransferContext,
        bucket_type: BucketType,
        input: DownloadInput,
        writer: BodyWriter,
        listed: Option<super::ListedObject>,
    ) -> Self {
        // Resolve the read-ahead knob (per-request override, else client default)
        // to a window in parts before `ctx` and `input` are moved into the struct.
        let window =
            super::read_ahead::resolve_window(input.read_ahead(), ctx.handle.config.read_ahead());
        let read_ahead = ReadAhead::with_window(window);
        // Couple the disk drain batch to the initial window, so a window below the
        // segment size drains in smaller runs from the first part.
        writer.sync_drain_batch(window);
        let destination = if writer.has_sink() {
            DownloadDestination::File
        } else {
            DownloadDestination::Stream
        };
        let observability =
            DownloadObservability::new(ctx.handle.config.diagnostics().transfer(), destination);
        let inner = Arc::new(DownloadTransferInner {
            read_ahead,
            ctx,
            state: Mutex::new(DownloadState::new()),
            observability,
            request: Arc::new(input),
            bucket_type,
            writer,
            object_meta: std::sync::OnceLock::new(),
            integrity_checks: std::sync::OnceLock::new(),
            expected_download_len: std::sync::OnceLock::new(),
            discovery_notify: tokio::sync::Notify::new(),
            listed,
        });
        Self { inner }
    }

    /// Access the transfer context.
    pub(crate) fn ctx(&self) -> &TransferContext {
        &self.inner.ctx
    }

    /// The object as a `download_objects` listing reported it, for a child download.
    pub(super) fn listed_object(&self) -> Option<&super::ListedObject> {
        self.inner.listed.as_ref()
    }

    /// Starts one request measurement attributed to download request kind.
    pub(crate) fn start_request(&self, kind: DownloadRequestKind) -> DownloadRequestMeasurement {
        self.inner
            .observability
            .start_request(&self.inner.ctx, kind)
    }

    fn snapshot(&self, state: &DownloadState) -> DownloadStateSnapshot {
        snapshot_state(state, self.inner.read_ahead.window())
    }

    fn observe_event(&self, event: DownloadEvent, state: &DownloadState) {
        let snapshot = self.snapshot(state);
        self.inner
            .observability
            .observe_event(self.inner.ctx.id, event, snapshot);
    }

    /// Emits the download terminal summary before notifying the owning handle.
    fn report_terminal(&self, state_snapshot: DownloadStateSnapshot) {
        self.inner.ctx.finalize_terminal_metrics();
        if !self.inner.ctx.claim_terminal_report() {
            return;
        }
        let pending = self.inner.ctx.pending_stats().unwrap_or_default();
        let checksum_validation = self
            .inner
            .integrity_checks
            .get()
            .map(|checks| checks.checksum_validation().clone());
        let _ = self
            .inner
            .observability
            .report_terminal(DownloadTerminalReport {
                transfer_id: self.inner.ctx.id,
                status: self.inner.ctx.transfer_status(),
                error_kind: self.inner.ctx.error_kind(),
                metrics: self.inner.ctx.metrics(),
                request_total: self.inner.ctx.metrics.request_metrics(),
                pending,
                checksum_validation,
                state_snapshot,
            });
    }

    /// Get the transfer ID.
    pub(crate) fn id(&self) -> TransferId {
        self.inner.ctx.id
    }

    /// Body writer for chunk delivery and disk writes.
    pub(crate) fn writer(&self) -> &BodyWriter {
        &self.inner.writer
    }

    /// The read-ahead window. The gate reads `self.inner.read_ahead` directly and the
    /// control surface goes through [`set_read_ahead`](Self::set_read_ahead); this
    /// accessor is for tests.
    #[cfg(test)]
    pub(crate) fn read_ahead(&self) -> &ReadAhead {
        &self.inner.read_ahead
    }

    /// Returns the terminal diagnostic report emitted by this transfer.
    #[cfg(test)]
    pub(crate) fn test_terminal_summary(
        &self,
    ) -> Option<crate::operation::download::observability::DownloadTransferSummary> {
        self.inner.observability.test_terminal_summary()
    }

    /// I/O controls for this transfer, for exercising the public control surface in
    /// tests. Production access is via
    /// [`DownloadHandle::io_ctl`](super::handle::DownloadHandle::io_ctl).
    #[cfg(test)]
    pub(crate) fn io_ctl(&self) -> super::handle::DownloadIoCtl<'_> {
        super::handle::DownloadIoCtl::for_test(self)
    }

    /// Apply a dynamic read-ahead change, resolving the public knob to a window. The
    /// next issuance-gate read observes the new value, and the disk drain batch is
    /// re-coupled to it so a window below the segment size drains in smaller runs.
    pub(crate) fn set_read_ahead(&self, mode: &crate::config::ReadAhead) {
        let window = super::read_ahead::window_parts_for(mode);
        self.inner.read_ahead.set_window(window);
        self.inner.writer.sync_drain_batch(window);
    }

    /// Release one part of read-ahead occupancy for a stream delivery, then wake the
    /// issuer.
    ///
    /// Called from `Body::next` after `poll_next` delivers a chunk (which frees exactly
    /// one part's payload). The release runs **under the state lock** — the same lock
    /// `poll_work` holds while it reads the gate and arms `set_pending` — so the
    /// mutator protocol `lock → mutate → unlock → try_wake` holds: either the gate
    /// observes this release and returns `Ready` without parking, or it parks and the
    /// `try_wake` below (after the lock is dropped) fires. Without the shared lock the
    /// two are unordered and the wake can be lost (the store-buffer race).
    ///
    /// The wake is unconditional, mirroring the disk completion path
    /// ([`decrement_in_flight`](Self::decrement_in_flight)): `try_wake` is a no-op
    /// unless the issuer actually parked, so there is no need to compute whether this
    /// release reopened the gate — waking always is correct and adds only an atomic
    /// swap on the (cold, per-part) delivery path.
    pub(crate) fn release_stream_occupancy(&self) {
        {
            let mut work = self.inner.state.lock().unwrap();
            if let DownloadState::Transferring { gate, .. } = &mut *work {
                gate.release(1);
            }
            // Terminal (or pre-transfer): no gate to release.
        }
        self.inner.ctx.try_wake();
    }

    /// Object metadata from discovery.
    pub(crate) fn object_meta(&self) -> Option<&ObjectMetadata> {
        self.inner.object_meta.get()
    }

    /// Object-integrity result, set once the download completes successfully.
    pub(crate) fn integrity_checks(&self) -> Option<&crate::types::IntegrityChecks> {
        self.inner.integrity_checks.get()
    }

    /// Notified when discovery completes.
    pub(crate) fn discovery_notify(&self) -> &tokio::sync::Notify {
        &self.inner.discovery_notify
    }

    /// Whether download checksum validation is in effect, resolved the same way
    /// the SDK's GetObject mutator does: enabled if the request set
    /// `ChecksumMode=Enabled`, or it is unset and the client's
    /// `ResponseChecksumValidation` is not `WhenRequired` (`WhenSupported`, the
    /// default, and unknown values enable it).
    fn validation_enabled(&self, input: &DownloadInput) -> bool {
        match input.checksum_mode {
            Some(crate::model::ChecksumMode::Enabled) => true,
            _ => !matches!(
                self.ctx()
                    .s3_client()
                    .config()
                    .response_checksum_validation()
                    .copied()
                    .unwrap_or_default(),
                aws_sdk_s3::config::ResponseChecksumValidation::WhenRequired
            ),
        }
    }

    /// Poll for the next work item.
    ///
    /// Returns:
    /// - `PollWork::Ready { .. }` - work available to execute
    /// - `PollWork::Pending` - waiting for in-flight work to complete
    /// - `PollWork::Done` - transfer complete
    ///
    /// This issues work and parks; it never completes a transfer. Each item it
    /// issues is counted when issued, and the work item that finishes last with
    /// nothing left to issue claims completion and finalizes, as
    /// [`DownloadState`] describes.
    #[tracing::instrument(
        level = "trace",
        target = TARGET_TRANSFER_DOWNLOAD,
        skip_all,
        fields(tid = %self.id()),
    )]
    pub(crate) fn poll_work(&self) -> PollWork {
        if !self.inner.ctx.is_active() {
            tracing::debug!(
                target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                "not active, returning Done",
            );
            return PollWork::Done;
        }

        let mut state = self.inner.state.lock().unwrap();

        match &mut *state {
            DownloadState::PendingDiscovery => {
                *state = DownloadState::DiscoveryInFlight;
                self.observe_event(DownloadEvent::DiscoveryScheduled, &state);
                PollWork::ready(IoRequest {
                    data: Some(Box::new(DownloadWork::Discovery)),
                })
            }
            DownloadState::DiscoveryInFlight => {
                self.inner.ctx.set_pending(DownloadPendingReason::Discovery);
                self.inner
                    .observability
                    .observe_state(self.snapshot(&state));
                PollWork::Pending
            }
            DownloadState::Transferring {
                remaining,
                ranges_in_flight,
                drains_in_flight,
                etag,
                part_size,
                gate,
                pending,
                integrity,
            } => {
                // Resolve the slot to issue into this poll, if one is ready. Two gates
                // compose in order: the per-transfer read-ahead window, then shared
                // memory admission, so issuance takes their min. The window is gated first
                // (via `gate.try_issue`) so a window-blocked transfer never holds a slice
                // of shared capacity it cannot use yet, starving other transfers.
                let slot = if pending.is_some() {
                    // A memory-blocked claim takes priority: the gate already admitted and
                    // counted its slot (held in `pending`, not re-gated), waiting only on
                    // its queued memory reservation.
                    match self.resume_pending_claim(pending) {
                        Ok(Some(slot)) => slot,
                        // Not granted yet; the reservation future registered the
                        // scheduler waker. Flush any resident run first so it
                        // does not retain memory while this claim is blocked.
                        Ok(None) => {
                            let snapshot = transferring_snapshot(
                                remaining.as_ref(),
                                *ranges_in_flight,
                                gate,
                                self.inner.read_ahead.window(),
                                pending.is_some(),
                            );
                            return self.poll_memory_blocked(drains_in_flight, snapshot);
                        }
                        Err(error) => return self.fail_memory_admission(state, error),
                    }
                } else if let Some(range) = remaining.as_ref() {
                    // Read-ahead gate. The gate bounds resident occupancy at
                    // `issued - released < window`, where `released` counts both delivery
                    // surfaces (stream pull and disk drain), so a disk download paces to
                    // its drain rate rather than to the in-order delivery cursor.
                    // `try_issue` reads and mutates the gate under this state lock; the
                    // consumer's `release` does the same, so the two are ordered and a
                    // release that reopens the gate cannot be lost against the
                    // `set_pending` below (the mutator protocol).
                    //
                    // The gate guards issuance only. Once every range is generated
                    // (`remaining` is None) the branches below never consult it, so a
                    // transfer whose last parts are still resident (e.g. a disk tail
                    // below the drain batch, freed only by the terminal drain in
                    // `finalize_completion`) does not block on the gate with nothing
                    // left to issue.
                    let window = self.inner.read_ahead.window();
                    if !gate.try_issue(window) {
                        // Gate closed: issuance is `window` parts ahead of what the
                        // consumer has freed and waits for a drain before claiming more.
                        // Trace: fires every gated poll in steady state.
                        tracing::trace!(
                            target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                            issued = gate.issued(),
                            released = gate.released(),
                            in_flight = gate.resident(),
                            window,
                            "read-ahead gate closed: issuance paused until the consumer drains",
                        );
                        let snapshot = transferring_snapshot(
                            remaining.as_ref(),
                            *ranges_in_flight,
                            gate,
                            window,
                            pending.is_some(),
                        );
                        return self.park(DownloadPendingReason::ReadAhead, snapshot);
                    }
                    // Gate admitted (and counted) the slot. Claim it from the buffer and
                    // reserve its backing memory against the shared budget. A grant issues now;
                    // a queued reservation stashes the claimed slot in `pending` and
                    // waits until the reservation future wakes us. The gate's `issued`
                    // bump stays: the blocked claim occupies its one window seat, so it
                    // holds exactly the slot it will fill.
                    let range_len = chunk_len(range, *part_size);
                    match self.reserve_claim(range_len, pending) {
                        Ok(Some(slot)) => slot,
                        // Memory-blocked; `pending` now holds the claimed slot.
                        // Flush any resident run before returning `Pending`.
                        Ok(None) => {
                            let snapshot = transferring_snapshot(
                                remaining.as_ref(),
                                *ranges_in_flight,
                                gate,
                                self.inner.read_ahead.window(),
                                pending.is_some(),
                            );
                            return self.poll_memory_blocked(drains_in_flight, snapshot);
                        }
                        Err(error) => return self.fail_memory_admission(state, error),
                    }
                } else if *ranges_in_flight > 0 {
                    // All ranges generated, waiting for in-flight to complete.
                    let snapshot = transferring_snapshot(
                        remaining.as_ref(),
                        *ranges_in_flight,
                        gate,
                        self.inner.read_ahead.window(),
                        pending.is_some(),
                    );
                    return self.park(DownloadPendingReason::RangeCompletion, snapshot);
                } else if *drains_in_flight > 0 {
                    // Every range completed, but the memory-relief item is still in
                    // flight and may hold a claimed run that finalization cannot see.
                    // It completes the transfer when it finishes.
                    let snapshot = transferring_snapshot(
                        remaining.as_ref(),
                        *ranges_in_flight,
                        gate,
                        self.inner.read_ahead.window(),
                        pending.is_some(),
                    );
                    return self.park(DownloadPendingReason::DrainCompletion, snapshot);
                } else {
                    // Nothing left to issue and nothing in flight: the work item that
                    // uncounted the last one claimed completion under this lock and left
                    // the state `Terminal`, and discovery does the same for an object
                    // with no ranges. Reaching this is a bookkeeping bug. The scheduler
                    // contains a `poll_work` panic to this transfer, and `on_terminal`
                    // tolerates the state lock it poisons.
                    unreachable!(
                        "download completion is claimed by the work item that retires last"
                    );
                };

                // A slot is ready. Commit the range it issues, sliced from the unchanged
                // `remaining` (identical for a fresh claim or a resumed pending one).
                // Automatic COMPOSITE validation uses the stored first-part size;
                // other plans use the configured download part size. Discovery resolves it.
                let part_size = *part_size;
                let range = remaining
                    .as_ref()
                    .expect("a ready slot implies a remaining range to issue");
                let start = *range.start();
                let end = *range.end();
                let chunk_end = cmp::min(start + part_size - 1, end);
                let chunk_range = start..=chunk_end;

                *ranges_in_flight += 1;

                let all_ranges_issued;
                if chunk_end < end {
                    *remaining = Some((chunk_end + 1)..=end);
                    all_ranges_issued = false;
                } else {
                    // The final range was just issued: issuance is done and the transfer
                    // drains its in-flight tail, completed by the work item that finishes last.
                    // Logged once per transfer.
                    *remaining = None;
                    all_ranges_issued = true;
                    tracing::debug!(
                        target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                        issued = gate.issued(),
                        ranges_in_flight = *ranges_in_flight,
                        "all ranges issued; draining in-flight tail",
                    );
                }

                let snapshot = transferring_snapshot(
                    remaining.as_ref(),
                    *ranges_in_flight,
                    gate,
                    self.inner.read_ahead.window(),
                    pending.is_some(),
                );
                self.inner.observability.record_range_scheduled();
                self.inner.observability.observe_event(
                    self.inner.ctx.id,
                    DownloadEvent::RangeScheduled,
                    snapshot,
                );
                if all_ranges_issued {
                    self.inner.observability.observe_event(
                        self.inner.ctx.id,
                        DownloadEvent::AllRangesIssued,
                        snapshot,
                    );
                }

                PollWork::ready(IoRequest {
                    data: Some(Box::new(DownloadWork::GetObjectRange {
                        range: chunk_range,
                        slot: Some(slot),
                        etag: etag.clone(),
                        digest_plan: integrity.range_digest_plan(),
                    })),
                })
            }
            DownloadState::Terminal => PollWork::Done,
        }
    }

    /// Park the transfer: mark it pending so the scheduler stops polling it until a
    /// waker re-readies it: the consumer freeing occupancy, or a GET
    /// completion decrementing the in-flight count. Memory reservations use their
    /// own scheduler-backed task waker.
    fn park(&self, reason: DownloadPendingReason, snapshot: DownloadStateSnapshot) -> PollWork {
        self.inner.ctx.set_pending(reason);
        self.inner.observability.observe_state(snapshot);
        PollWork::Pending
    }

    /// Returns work that relieves memory pressure before a reservation wait.
    ///
    /// A transfer blocked on memory while holding a drainable resident run has
    /// no other path to release that run: it is below the normal drain batch,
    /// and the blocked part prevents terminal drain. Across concurrent disk
    /// transfers this can deadlock. Flush the resident run first, and return
    /// `Pending` only when there is nothing to flush.
    ///
    /// A relief item is counted in `drains_in_flight` here, when it is issued,
    /// and at most one is in flight. While one is, this parks on
    /// `MemoryAdmission` as it does when nothing is drainable: the item in
    /// flight drains every drainable run, and its completion wakes the
    /// transfer.
    ///
    /// The pending reservation future has already registered the context's
    /// scheduler waker. This path still records and arms the common pending
    /// state; the registered wake and `try_wake` paths reconcile through the
    /// same descriptor protocol. A `has_drainable_resident` guard keeps it from
    /// emitting empty drains when an in-flight gap blocks the prefix or stream
    /// delivery owns progress.
    fn poll_memory_blocked(
        &self,
        drains_in_flight: &mut u32,
        snapshot: DownloadStateSnapshot,
    ) -> PollWork {
        if *drains_in_flight == 0 && self.inner.writer.has_drainable_resident() {
            *drains_in_flight += 1;
            self.inner.observability.observe_event(
                self.inner.ctx.id,
                DownloadEvent::MemoryReliefScheduled,
                snapshot,
            );
            PollWork::ready(IoRequest {
                data: Some(Box::new(DownloadWork::DrainResident)),
            })
        } else {
            self.inner
                .ctx
                .set_pending(DownloadPendingReason::MemoryAdmission);
            self.inner.observability.observe_state(snapshot);
            PollWork::Pending
        }
    }

    /// Poll the reservation for a previously claimed slot.
    ///
    /// The read-ahead gate already counted this slot, so a pending claim is not
    /// re-gated. `Ok(None)` means the future remains linked in the
    /// memory-admission FIFO.
    fn resume_pending_claim(
        &self,
        pending: &mut Option<PendingClaim>,
    ) -> Result<Option<BodySlot>, ReserveError> {
        let waker = self.inner.ctx.waker();
        let mut context = Context::from_waker(&waker);
        let reservation =
            match Pin::new(&mut pending.as_mut().unwrap().reservation).poll(&mut context) {
                Poll::Ready(result) => result?,
                Poll::Pending => return Ok(None),
            };

        let mut claim = pending.take().unwrap();
        claim.slot.attach_reservation(reservation);
        Ok(Some(claim.slot))
    }

    /// Claim a slot and reserve its backing memory against the shared budget. The
    /// read-ahead gate has already admitted (and counted) this slot. Returns the slot
    /// with its reservation attached on an immediate grant; on a queued reservation,
    /// stashes the claimed slot in `pending` and returns `None`. The reservation
    /// future's scheduler waker requests the next poll when capacity is granted.
    fn reserve_claim(
        &self,
        range_len: usize,
        pending: &mut Option<PendingClaim>,
    ) -> Result<Option<BodySlot>, ReserveError> {
        let mut slot = self.inner.writer.claim();
        let mut reservation = self.inner.ctx.handle.buffer_pool.reserve(range_len);
        let waker = self.inner.ctx.waker();
        let mut context = Context::from_waker(&waker);

        match Pin::new(&mut reservation).poll(&mut context) {
            Poll::Ready(Ok(reservation)) => {
                slot.attach_reservation(reservation);
                Ok(Some(slot))
            }
            Poll::Ready(Err(error)) => Err(error),
            Poll::Pending => {
                *pending = Some(PendingClaim { slot, reservation });
                Ok(None)
            }
        }
    }

    /// Reserve memory capacity for a discovery chunk.
    ///
    /// Discovery has already issued the GET and runs inside async `execute`, so
    /// it awaits the same cancellation-safe reservation future used by
    /// `poll_work`. The wait races terminal notification because per-transfer
    /// cancellation does not abort an executing future.
    ///
    /// The terminal notification future is registered before checking status:
    /// `notify_waiters` stores no permit, so reversing those operations can lose
    /// a cancellation between the check and polling both futures.
    async fn reserve_discovery_chunk(
        &self,
        len: usize,
    ) -> Result<Option<Reservation>, ReserveError> {
        let mut reservation = std::pin::pin!(self.inner.ctx.handle.buffer_pool.reserve(len));

        loop {
            let terminal_wake = self.inner.discovery_notify.notified();
            let terminal_wake = std::pin::pin!(terminal_wake);
            if !self.inner.ctx.is_active() {
                return Ok(None);
            }
            match select(reservation.as_mut(), terminal_wake).await {
                Either::Left((result, _)) => {
                    tracing::debug!(
                        target: crate::telemetry::TARGET_SCHEDULING,
                        tid = %self.inner.ctx.id,
                        len,
                        "discovery chunk reservation granted; resuming",
                    );
                    return result.map(Some);
                }
                Either::Right(((), _)) => {}
            }
        }
    }

    /// Convert a terminal memory-admission failure into the download lifecycle.
    fn fail_memory_admission(
        &self,
        state: std::sync::MutexGuard<'_, DownloadState>,
        source: ReserveError,
    ) -> PollWork {
        let _ = self.fail(
            state,
            error::Error::new(error::ErrorKind::RuntimeError, source),
        );
        PollWork::Done
    }

    #[tracing::instrument(
        level = "trace",
        target = TARGET_TRANSFER_DOWNLOAD,
        skip_all,
        fields(tid = %self.id(), work = tracing::field::Empty),
    )]
    pub(crate) async fn execute(&self, work: &mut IoRequest) -> WorkOutcome {
        let data = work.data_mut::<DownloadWork>();
        tracing::Span::current().record("work", data.kind());
        match data {
            DownloadWork::Discovery => self.execute_discovery().await,
            DownloadWork::GetObjectRange {
                range,
                slot,
                etag,
                digest_plan,
            } => {
                self.execute_get_range(
                    range.clone(),
                    slot.take().expect("slot already consumed"),
                    etag.clone(),
                    *digest_plan,
                )
                .await
            }
            DownloadWork::DrainResident => self.execute_drain_resident(),
        }
    }

    /// Flush the resident filled run to disk, returning its pooled carriers,
    /// then release the freed read-ahead occupancy. Emitted when a transfer
    /// would otherwise wait for memory admission while retaining a resident run.
    ///
    /// The item was counted in `drains_in_flight` when `poll_memory_blocked`
    /// issued it, and is uncounted here, under the state lock, once it has
    /// written every run it claimed. Success therefore cannot be claimed while
    /// the item is queued or a claimed run is still being written, and whichever
    /// work item finishes last, the final range or the relief item, claims the
    /// terminal transition exactly once. A relief item that finds the transfer
    /// no longer active writes nothing: its count goes with the `Transferring`
    /// state, and the terminal drain owns any resident run. A failed write
    /// fails the transfer.
    ///
    /// Unlike a fill-triggered drain, no GET completed here, so `ranges_in_flight` is
    /// untouched; only occupancy is released (matching the gate side of
    /// [`decrement_in_flight`](Self::decrement_in_flight), under the same state lock so
    /// the release is ordered against the issuer's park). Dropping the drained
    /// `ChunkOutput`s returns their carrier charges, which memory admission
    /// re-grants FIFO; the `on_completion -> generate_work` after this returns
    /// re-polls this transfer.
    fn execute_drain_resident(&self) -> WorkOutcome {
        // Equivalent to checking the state for `Transferring`, without the
        // state lock. Failure and cancellation move the status off `Active`
        // before the state enters `Terminal`. The only point at which the state
        // is `Terminal` while the status is still `Active` is a claimed
        // completion, which cannot happen while this item is counted in
        // `drains_in_flight`. A status off `Active` with the state still
        // `Transferring` means the terminal transition is under way, and its
        // terminal drain takes the resident run.
        if !self.inner.ctx.is_active() {
            return WorkOutcome::Cancelled;
        }

        let flushed = self.inner.writer.flush_resident();
        self.record_disk_write(bytes_drained(&flushed));

        let mut work = self.inner.state.lock().unwrap();
        if let DownloadState::Transferring {
            drains_in_flight, ..
        } = &mut *work
        {
            *drains_in_flight -= 1;
        }
        let drained = match flushed {
            Ok(drained) => drained,
            Err(e) => {
                return self.fail(work, error::Error::new(error::ErrorKind::IOError, e.source))
            }
        };
        if let DownloadState::Transferring { gate, .. } = &mut *work {
            gate.release(drained.parts);
        }
        let snapshot = self.snapshot(&work);
        let completion = work.try_claim_completion();
        drop(work);

        self.inner
            .observability
            .record_memory_relief_completed(drained.parts);
        self.inner.observability.observe_event(
            self.inner.ctx.id,
            DownloadEvent::MemoryReliefCompleted,
            snapshot,
        );
        if let Some(claim) = completion {
            return self.finalize_completion(claim);
        }
        self.inner.ctx.try_wake();
        WorkOutcome::Success { data: None }
    }

    async fn execute_discovery(&self) -> WorkOutcome {
        let input = self.inner.request.as_ref();

        let validation_enabled = self.validation_enabled(input);

        let discovery = match discover_obj(self, input, validation_enabled).await {
            Ok(d) => d,
            Err(e) => {
                let guard = self.inner.state.lock().unwrap();
                return self.fail(guard, e);
            }
        };

        let ObjectDiscovery {
            remaining,
            object_range_start,
            object_meta,
            initial_chunk,
            chunk_meta,
            effective_part_size,
            validation_plan,
        } = discovery;

        // Store object_meta for object_meta() and join(), without checksum values
        // that don't describe the object's bytes: a composite value, and a value
        // from a response for part of the object. Whole-object checksum-mode HEAD
        // metadata keeps its other values. The local `object_meta` keeps the
        // discovery response unchanged.
        let _ = self
            .inner
            .object_meta
            .set(process_object_metadata(object_meta.clone()));

        // HEAD reports object values even when later GETs carry only part metadata.
        // GET-first discovery reports object values only for a whole-object response.
        let object_checksum_metadata =
            if input.range.is_none() && (validation_enabled || remaining.is_none()) {
                Some(object_meta.clone())
            } else {
                None
            };
        let integrity = Box::new(DownloadIntegrity::new(
            validation_plan,
            object_checksum_metadata,
        ));
        let digest_plan = integrity.range_digest_plan();

        // Notify waiters that discovery completed
        self.inner.discovery_notify.notify_waiters();

        let etag: Option<Arc<str>> = object_meta.e_tag.as_deref().map(Arc::from);

        // Prepare the destination before range writes begin. Owned temporary files
        // request best-effort allocation to reduce per-write metadata work. Linux
        // storage or quota exhaustion is terminal here; other preallocation failures
        // are logged and writes proceed. Successful completion establishes the exact
        // logical length after the terminal drain.
        let chunk_content_len = chunk_meta
            .as_ref()
            .and_then(|m| m.content_length)
            .and_then(|length| u64::try_from(length).ok())
            .unwrap_or(0);
        let expected_download_len =
            chunk_content_len + remaining.as_ref().map_or(0, |r| r.end() - r.start() + 1);
        if let Err(error) = self
            .inner
            .writer
            .prepare(object_range_start, expected_download_len)
        {
            let guard = self.inner.state.lock().unwrap();
            return self.fail(
                guard,
                crate::error::Error::new(crate::error::ErrorKind::IOError, error),
            );
        }
        self.inner.observability.destination_prepared();
        let _ = self.inner.expected_download_len.set(expected_download_len);
        self.inner.ctx.set_total_bytes(expected_download_len);

        // If there's an initial chunk, claim seq BEFORE waking to prevent race
        // where poll_work exhausts the window before we can claim our seq.
        // A GET discovery always supplies metadata. A nonempty GET also
        // supplies one body with its already-validated allocation length.
        //
        // Reserve the discovery chunk's memory here too: it is already resident (the
        // discovery GET fetched it), so it must be accounted before any read-ahead
        // range issues. Awaiting the reservation head-first keeps the memory FIFO
        // ordered: under tight capacity the head part is admitted before the window
        // fans out — and backpressures by holding this chunk undelivered rather than
        // returning `Pending` to the scheduler (discovery runs in async `execute`,
        // not `poll_work`).
        let initial_work = match (initial_chunk, chunk_meta) {
            (Some(mut initial), Some(meta)) => {
                let req_metrics = initial
                    .request_metrics
                    .take()
                    .expect("ranged discovery body carries its request measurement");
                let mut slot = self.inner.writer.claim();
                match self.reserve_discovery_chunk(initial.expected_len).await {
                    Ok(Some(reservation)) => {
                        slot.attach_reservation(reservation);
                        Some((initial, req_metrics, meta, slot))
                    }
                    // Terminal (cancel/fail by another path) while reserving the discovery
                    // chunk: the transfer is already in its terminal state, so drop the
                    // claimed slot (waking the consumer) and return without transitioning
                    // to Transferring. `execute` reports Cancelled.
                    Ok(None) => {
                        drop(slot);
                        return WorkOutcome::Cancelled;
                    }
                    Err(error) => {
                        drop(slot);
                        let guard = self.inner.state.lock().unwrap();
                        return self.fail(
                            guard,
                            crate::error::Error::new(crate::error::ErrorKind::RuntimeError, error),
                        );
                    }
                }
            }
            (None, _) => None,
            (Some(_), None) => {
                panic!("invalid discovery state: initial_chunk present without chunk_meta")
            }
        };

        let has_initial_work = initial_work.is_some();
        let all_ranges_issued = remaining.is_none();
        let (discovery_snapshot, completion) = {
            // The discovery chunk, if present, is one claimed part already in flight.
            let initial = u64::from(initial_work.is_some());
            let mut work = self.inner.state.lock().unwrap();
            *work = DownloadState::Transferring {
                remaining,
                ranges_in_flight: initial as usize,
                drains_in_flight: 0,
                etag: etag.clone(),
                part_size: effective_part_size,
                gate: super::context::OccupancyGate::with_issued(initial),
                pending: None,
                integrity,
            };
            let snapshot = self.snapshot(&work);
            // With no chunk and nothing remaining, discovery is the last work item to
            // finish, so it claims completion under the lock that publishes the state.
            // A transfer that is no longer active is not completed.
            let completion = if self.inner.ctx.is_active() {
                work.try_claim_completion()
            } else {
                None
            };
            (snapshot, completion)
        };
        if has_initial_work {
            self.inner.observability.record_range_scheduled();
        }
        self.inner.observability.observe_event(
            self.inner.ctx.id,
            DownloadEvent::DiscoveryCompleted,
            discovery_snapshot,
        );
        if all_ranges_issued {
            self.inner.observability.observe_event(
                self.inner.ctx.id,
                DownloadEvent::AllRangesIssued,
                discovery_snapshot,
            );
        }

        if let Some(claim) = completion {
            return self.finalize_completion(claim);
        }

        // State changed from DiscoveryInFlight - try to wake
        self.inner.ctx.try_wake();

        // If discovery returned an initial chunk, process it
        match initial_work {
            Some((initial, request, chunk_meta, slot)) => {
                self.execute_read_discovery_body(
                    initial,
                    request,
                    slot,
                    chunk_meta,
                    etag,
                    digest_plan,
                )
                .await
            }
            None => WorkOutcome::Success { data: None },
        }
    }

    async fn execute_read_discovery_body(
        &self,
        initial: InitialChunk,
        mut req_metrics: DownloadRequestMeasurement,
        slot: BodySlot,
        chunk_meta: ChunkMetadata,
        etag: Option<Arc<str>>,
        digest_plan: RangeDigestPlan,
    ) -> WorkOutcome {
        let InitialChunk {
            body,
            checksum,
            expected_len,
            request_metrics: _,
        } = initial;
        req_metrics.resume();
        let seq = slot.seq();
        let input = self.inner.request.as_ref();
        // The discovery GET already received this chunk's response headers; the
        // first read consumes its (lazy, not-yet-read) body stream with no extra
        // request. A retry has no stream to reuse, so it re-issues a ranged GET
        // for exactly the bytes this chunk covers, taken from the discovery
        // response's content-range. A partNumber=1 discovery maps to the same
        // byte range, so the re-issued aligned range returns the same per-part
        // checksum the SDK validates against.
        let reissue_range = chunk_meta
            .content_range
            .as_deref()
            .and_then(crate::http::header::parse_content_range);

        let mut initial = Some((body, checksum));
        let recv_latencies = &self.inner.ctx.handle.telemetry.recv_latencies;
        // The deadline guards only the GET response (TTFB); the body-read is
        // untimed. The first attempt reuses the discovery body — no network send
        // — so it skips the `guarded` timer entirely (timing/recording a ~0µs
        // "send" would drag the TTFB mean toward zero). Only a genuine re-issue
        // goes through `guarded`, which times and records its TTFB.
        let reservation = slot.reservation();
        let retry_classify = crate::retry::classify_body_retry;
        let result = crate::retry::retry(req_metrics.metrics_mut(), retry_classify, |allow_hedge| {
            let pre_issued = initial.take();
            let etag = etag.clone();
            let ctx = self.inner.ctx.clone();
            let reissue_range = reissue_range.clone();
            let mut builder =
                copy_fields_to_get_object_request(input, ctx.s3_client().get_object());
            if let Some(r) = reissue_range.as_ref() {
                builder = builder.set_range(Some(format!("bytes={}-{}", r.start(), r.end())));
            }
            if let Some(etag) = etag.as_ref() {
                builder = builder.if_match(etag.as_ref());
            }
            let checksum = ChecksumCapture::new();
            let req = builder
                .customize()
                .interceptor(Capture::new().with(&checksum))
                .config_override(ctx.download_get_override(input.bucket()));
            async move {
                // Obtain the body stream. First attempt reuses the discovery body
                // (no send, untimed); a re-issue is TTFB-guarded (times + records).
                let (body, checksum) = match pre_issued {
                    Some(initial) => initial,
                    None => {
                        // A re-issue without a byte range would fetch the whole
                        // object into this chunk's slot. S3 always returns a
                        // content-range for a ranged/partNumber GET, so a missing
                        // range is a contract violation — fail the chunk rather
                        // than issue an unbounded GET. Use a terminal kind
                        // (`RuntimeError`, NoRetry in `classify_body_retry`): the
                        // range cannot appear on a re-issue, so retrying would
                        // deterministically fail again and waste a backoff.
                        if reissue_range.is_none() {
                            return Err(crate::retry::GuardError::Inner(
                                crate::error::Error::new(
                                    crate::error::ErrorKind::RuntimeError,
                                    "cannot re-issue discovery chunk: response carried no content-range",
                                ),
                            ));
                        }
                        let body = recv_latencies
                            .guarded(allow_hedge, async {
                                req.send()
                                    .await
                                    .map(|resp| resp.body)
                                    .map_err(error::service_error)
                            })
                            .await?;
                        (body, checksum)
                    }
                };
                // Untimed: drain the body. Errors here are inner (retryable IO).
                collect_response_body(
                    &ctx.handle.buffer_pool,
                    body,
                    &checksum,
                    reservation,
                    expected_len,
                    || ctx.is_active(),
                )
                .await
                .map(|segmented| (segmented, checksum))
                .map_err(crate::retry::GuardError::Inner)
            }
        })
        .instrument(tracing::trace_span!(
            target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
            "download-part",
            tid = %self.id()
        ))
        .await;
        let _ = req_metrics.finish();

        let (segmented, checksum) = match result {
            Ok(val) => val,
            // Go terminal without completing this range work: fail() sets Terminal under
            // the lock, so no later work completion can claim completion over this
            // error. The in-flight count is abandoned with the Transferring state.
            Err(e) => {
                let guard = self.inner.state.lock().unwrap();
                return self.fail(guard, e.with_chunk(ChunkRef::new(seq, None)));
            }
        };

        // Collection may finish after cancellation; stop before hashing or publication.
        bail_if_terminal!(self);
        let offset = reissue_range
            .as_ref()
            .map(|range| *range.start())
            .unwrap_or(0);
        // Only the successful attempt supplies evidence. Hash frozen delivery bytes
        // before publishing them, outside both the retry loop and the state lock.
        let completed =
            match RangeCompletion::capture(offset, &segmented, checksum.try_outcome(), digest_plan)
            {
                Ok(completed) => completed,
                Err(error) => return self.fail_range(ChunkRef::new(seq, None), error),
            };
        let bytes_received = completed.range.end - completed.range.start;
        let chunk = ChunkOutput {
            seq,
            offset,
            data: segmented,
            metadata: chunk_meta,
        };

        // Edge-triggered disk write: a fill that brings the segment's filled count to
        // the drain batch attempts a drain of the batch-ready run(s). `freed` is the
        // occupancy this drain released, accounted under the lock in decrement_in_flight.
        let mut freed = 0u64;
        if slot.fill(chunk) == FillOutcome::DrainReady {
            let drain = self.inner.writer.drain(DrainMode::Batched);
            self.record_disk_write(bytes_drained(&drain));
            match drain {
                Ok(drained) => freed = drained.parts,
                Err(e) => {
                    // Go terminal before any wake (see fail_range).
                    let guard = self.inner.state.lock().unwrap();
                    return self.fail(
                        guard,
                        error::Error::new(error::ErrorKind::IOError, e.source),
                    );
                }
            }
        }

        self.inner.ctx.record_io(&crate::metrics::IoSample {
            network_rx: bytes_received,
            ..Default::default()
        });
        if let Some(claim) = self.decrement_in_flight(freed, Some(completed)) {
            return self.finalize_completion(claim);
        }

        WorkOutcome::Success { data: None }
    }

    async fn execute_get_range(
        &self,
        range: std::ops::RangeInclusive<u64>,
        slot: BodySlot,
        etag: Option<Arc<str>>,
        digest_plan: RangeDigestPlan,
    ) -> WorkOutcome {
        let seq = slot.seq();
        let input = self.inner.request.as_ref();
        let range_header = format!("bytes={}-{}", range.start(), range.end());
        let expected_len = match range
            .end()
            .checked_sub(*range.start())
            .and_then(|len| len.checked_add(1))
            .and_then(|len| usize::try_from(len).ok())
        {
            Some(len) if len != 0 => len,
            _ => {
                return self.fail_range(
                    ChunkRef::new(seq, Some(*range.start()..=*range.end())),
                    error::Error::new(
                        error::ErrorKind::RuntimeError,
                        "download range length exceeds platform representation",
                    ),
                )
            }
        };
        let reservation = slot.reservation();

        let recv_latencies = &self.inner.ctx.handle.telemetry.recv_latencies;
        // The deadline guards only the GET response (send → headers ≈ TTFB): the
        // `recv_latencies.guarded(send)` wrapper times the send, then the body is
        // read UNTIMED. A large part on a slow-but-healthy link takes a long time
        // to drain and must not be cancelled as a straggler; a dead mid-body
        // stream is caught by stalled-stream protection. A `GuardError`
        // (deadline timeout OR inner error from either phase) is classified by
        // the retry loop.
        let mut req_metrics = self.start_request(DownloadRequestKind::Range);
        let retry_classify = crate::retry::classify_body_retry;
        let object_len = self
            .inner
            .object_meta
            .get()
            .map(ObjectMetadata::total_object_size);
        let result =
            crate::retry::retry(req_metrics.metrics_mut(), retry_classify, |allow_hedge| {
                let rh = range_header.clone();
                let etag = etag.clone();
                let ctx = self.inner.ctx.clone();
                // Every chunk GET must carry the same request fields as discovery
                // (checksum_mode, SSE-C key, version_id, ...). Derive from the input
                // conversion, then pin this chunk's range and the discovered etag.
                let mut builder =
                    copy_fields_to_get_object_request(input, ctx.s3_client().get_object());
                builder = builder.set_range(Some(rh.clone()));
                if let Some(etag) = etag.as_ref() {
                    builder = builder.if_match(etag.as_ref());
                }
                let checksum = ChecksumCapture::new();
                let req = builder
                    .customize()
                    .interceptor(Capture::new().with(&checksum))
                    .config_override(ctx.download_get_override(input.bucket()));
                async move {
                    // Timed (TTFB): obtain response headers. Validate the range here
                    // so a mismatch is classified before we commit to the body read.
                    let rh_validate = rh.clone();
                    let resp = recv_latencies
                        .guarded(allow_hedge, async move {
                            let resp = req.send().await.map_err(error::service_error)?;
                            validate_content_range(
                                &rh_validate,
                                resp.content_range(),
                                resp.content_length(),
                                object_len,
                            )
                            .map_err(|message| {
                                error::invalid_service_response("GetObject", &resp, message)
                            })?;
                            Ok::<_, crate::error::Error>(resp)
                        })
                        .await?;
                    // Untimed: drain the body. Errors here are inner (retryable IO).
                    let chunk_meta = crate::sdk_v1::chunk_metadata_from_get_object(&resp);
                    let segmented = collect_response_body(
                        &ctx.handle.buffer_pool,
                        resp.body,
                        &checksum,
                        reservation,
                        expected_len,
                        || ctx.is_active(),
                    )
                    .await
                    .map_err(crate::retry::GuardError::Inner)?;
                    Ok::<_, crate::retry::GuardError<crate::error::Error>>((
                        chunk_meta, segmented, checksum,
                    ))
                }
            })
            .instrument(tracing::trace_span!(
                target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                "download-part-reissue",
                tid = %self.id()
            ))
            .await;
        let _ = req_metrics.finish();

        let (chunk_meta, segmented, checksum) = match result {
            Ok(val) => val,
            Err(e) => {
                return self.fail_range(ChunkRef::new(seq, Some(*range.start()..=*range.end())), e)
            }
        };

        // Collection may finish after cancellation; stop before hashing or publication.
        bail_if_terminal!(self);
        // Capture the immutable bytes that will be published, not response frames
        // or failed retry attempts. The delivery cursor remains unchanged.
        let completed = match RangeCompletion::capture(
            *range.start(),
            &segmented,
            checksum.try_outcome(),
            digest_plan,
        ) {
            Ok(completed) => completed,
            Err(error) => return self.fail_range(ChunkRef::new(seq, Some(range.clone())), error),
        };
        let bytes_received = completed.range.end - completed.range.start;
        let chunk = ChunkOutput {
            seq,
            offset: *range.start(),
            data: segmented,
            metadata: chunk_meta,
        };

        // Edge-triggered disk write: a fill that brings the segment's filled count to
        // the drain batch attempts a drain of the batch-ready run(s) — one positioned
        // write per coalesced run, not every fill. Stream mode's drain is a no-op.
        // `freed` is the occupancy this drain released, accounted under the lock in
        // decrement_in_flight.
        let mut freed = 0u64;
        if slot.fill(chunk) == FillOutcome::DrainReady {
            let drain = self.inner.writer.drain(DrainMode::Batched);
            self.record_disk_write(bytes_drained(&drain));
            match drain {
                Ok(drained) => freed = drained.parts,
                Err(e) => {
                    // Go terminal before any wake (see fail_range).
                    let guard = self.inner.state.lock().unwrap();
                    return self.fail(
                        guard,
                        error::Error::new(error::ErrorKind::IOError, e.source),
                    );
                }
            }
        }

        self.inner.ctx.record_io(&crate::metrics::IoSample {
            network_rx: bytes_received,
            ..Default::default()
        });
        if let Some(claim) = self.decrement_in_flight(freed, Some(completed)) {
            return self.finalize_completion(claim);
        }

        tracing::trace!(
            target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
            seq,
            offset = *range.start(),
            "chunk downloaded",
        );

        WorkOutcome::Success { data: None }
    }

    /// Fail a range request with an error, tagging the chunk it belongs to.
    fn fail_range(&self, location: ChunkRef, e: Error) -> WorkOutcome {
        // Go terminal before any wake (see the discovery-body error path). Do not
        // decrement_in_flight first: as the last work item to finish it would claim
        // completion and finalize over this error.
        let guard = self.inner.state.lock().unwrap();
        self.fail(guard, e.with_chunk(location))
    }

    /// Completes one in-flight range work item and releases its read-ahead occupancy.
    ///
    /// Under the state lock, records `completed` evidence, decrements the range
    /// count and releases `freed` parts. Claims completion exactly once when no
    /// range remains and no range or memory-relief work is still in flight.
    /// The claim carries every successfully completed range's evidence; its owner
    /// verifies integrity and finalizes the destination outside the lock.
    ///
    /// `completed` describes bytes successfully published and written where required.
    /// Cancelled work supplies `None`; failed work must fail the transfer before
    /// decrementing the in-flight count so it cannot claim completion over an error.
    ///
    /// Releasing the occupancy under the same lock `poll_work` reads the gate and arms
    /// `set_pending` under is what orders this completion's release against the issuer's
    /// park (the mutator protocol `lock -> mutate -> unlock -> try_wake`). `freed` is the
    /// disk drain's freed count (0 if this fill did not hit a drain edge).
    fn decrement_in_flight(
        &self,
        freed: u64,
        completed: Option<RangeCompletion>,
    ) -> Option<CompletionClaim> {
        let (completion, snapshot) = {
            let mut work = self.inner.state.lock().unwrap();
            match &mut *work {
                DownloadState::Transferring {
                    ranges_in_flight,
                    gate,
                    remaining,
                    pending,
                    integrity,
                    ..
                } => {
                    if let Some(completed) = completed {
                        integrity.record(completed);
                    }
                    *ranges_in_flight = ranges_in_flight.saturating_sub(1);
                    gate.release(freed);
                    let snapshot = transferring_snapshot(
                        remaining.as_ref(),
                        *ranges_in_flight,
                        gate,
                        self.inner.read_ahead.window(),
                        pending.is_some(),
                    );
                    (work.try_claim_completion(), Some(snapshot))
                }
                _ => (None, None),
            }
        };
        if let Some(snapshot) = snapshot {
            self.inner.observability.record_range_completed(freed);
            self.inner.observability.observe_event(
                self.inner.ctx.id,
                DownloadEvent::RangeCompleted,
                snapshot,
            );
        }
        // Wake the issuer on every non-terminal completion so a pending poll_work can
        // issue more. A claimed completion is finalized by the caller in `execute`.
        if completion.is_none() {
            self.inner.ctx.try_wake();
        }
        completion
    }

    /// Verifies accepted checksum evidence, flushes the destination tail, establishes
    /// its length and publishes successful completion in that order.
    ///
    /// Integrity or coverage failure skips destination finalization and publishes no
    /// verdict. Destination failure reports `ErrorKind::IOError`. The state is already
    /// `Terminal`; verification and disk IO run after releasing the state lock.
    fn finalize_completion(&self, claim: CompletionClaim) -> WorkOutcome {
        let integrity_checks = match claim.finish_integrity() {
            Ok(checks) => checks,
            Err(error) => {
                let guard = self.inner.state.lock().unwrap();
                return self.fail(guard, error);
            }
        };
        let expected_len = *self
            .inner
            .expected_download_len
            .get()
            .expect("completed download must have a discovered length");
        let finalization = self.finalize_destination(expected_len);
        if let Err(e) = finalization {
            // Finalize failed: transition to failed. The state is already Terminal; `fail`
            // calls `enter_terminal` which is idempotent on Terminal (returns None).
            let guard = self.inner.state.lock().unwrap();
            return self.fail(guard, error::Error::new(error::ErrorKind::IOError, e));
        }
        let _ = self.inner.integrity_checks.set(integrity_checks);
        let state_snapshot = {
            let state = self.inner.state.lock().expect("lock poisoned");
            self.snapshot(&state)
        };
        if self.inner.writer.has_sink() {
            self.inner.observability.observe_event(
                self.inner.ctx.id,
                DownloadEvent::DestinationFinalized,
                state_snapshot,
            );
        }
        self.inner.ctx.set_completed();
        self.inner.writer.notify_consumer();
        self.report_terminal(state_snapshot);
        self.inner.ctx.signal_terminal();
        WorkOutcome::Success { data: None }
    }

    /// Transition to terminal failed state. Requires holding the work lock.
    fn fail(
        &self,
        mut guard: std::sync::MutexGuard<'_, DownloadState>,
        error: Error,
    ) -> WorkOutcome {
        let description = DisplayErrorContext(&error).to_string();
        tracing::debug!(
            target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
            error = %description,
            "download failed",
        );
        let classification = crate::scheduler::classify_error(&error);
        // Order matters: set status/error before any wakeups
        if !self.inner.ctx.set_failed(error)
            && self.inner.ctx.transfer_status() == crate::types::TransferStatus::Completed
        {
            // Unreachable under the counting rule on `DownloadState`: `fail`
            // runs from a work item that is still counted, from discovery
            // before `Transferring`, from `poll_work` while the transfer is
            // active, or from `finalize_completion` before `set_completed`, and
            // completion requires every counted item to have finished. Release
            // builds log instead, since a panic would change nothing there:
            // success was already reported, and the scheduler contains panics.
            debug_assert!(
                false,
                "download failed after it had completed: {description}"
            );
            tracing::error!(
                target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
                tid = %self.inner.ctx.id,
                error = %description,
                "download failed after it had completed; the failure is not reported to the caller",
            );
        }
        let snapshot = self.snapshot(&guard);
        // Transition to Terminal, taking any memory-blocked claim so cancelling
        // its reservation future happens after releasing the state lock.
        let pending = guard.enter_terminal();
        drop(guard); // release lock before dropping the claim and signaling waiters
        drop(pending);
        // Wake all waiters
        self.inner.discovery_notify.notify_waiters();
        self.run_terminal_drain();
        self.inner.writer.notify_consumer();
        self.report_terminal(snapshot);
        self.inner.ctx.signal_terminal();
        WorkOutcome::Failed { classification }
    }

    /// Records `bytes` the destination accepted as `disk_write`. Zero records
    /// nothing.
    fn record_disk_write(&self, bytes: u64) {
        if bytes > 0 {
            self.inner.ctx.record_io(&crate::metrics::IoSample {
                disk_write: bytes,
                ..Default::default()
            });
        }
    }

    /// Writes every remaining filled run at a terminal transition, recording the
    /// bytes written and the drain's outcome. A drain error is observed but not
    /// returned: the transfer is already terminal.
    fn run_terminal_drain(&self) {
        let drain = self.inner.writer.terminal_drain();
        self.record_disk_write(bytes_drained(&drain));
        self.inner
            .observability
            .terminal_drain_completed(&drain.map(|drained| drained.parts).map_err(|e| e.source));
    }

    /// Finalizes the destination for a successful transfer, then records the
    /// bytes written, whether or not finalization succeeded, and its outcome.
    fn finalize_destination(&self, expected_len: u64) -> Result<(), std::io::Error> {
        let finalization = self.inner.writer.finalize(expected_len);
        self.record_disk_write(bytes_drained(&finalization));
        let finalization = finalization
            .map(|drained| drained.parts)
            .map_err(|e| e.source);
        self.inner
            .observability
            .destination_finalized(&finalization);
        finalization.map(|_| ())
    }
}

impl Transfer for DownloadTransfer {
    fn ctx(&self) -> &TransferContext {
        DownloadTransfer::ctx(self)
    }

    fn poll_work(&self) -> PollWork {
        DownloadTransfer::poll_work(self)
    }

    fn execute<'a>(
        &'a self,
        work: &'a mut IoRequest,
    ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>> {
        Box::pin(DownloadTransfer::execute(self, work))
    }

    fn on_terminal(&self) {
        // Release a memory-blocked claim if one is held. External cancellation
        // does not run `fail` or claim completion, so it must explicitly extract
        // the claim and cancel its reservation future after releasing state.
        let (pending, snapshot) = {
            // The transfer is already terminal: snapshot and take the pending
            // claim even if a panic left the state inconsistent.
            let mut state = self
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let snapshot = self.snapshot(&state);
            (state.enter_terminal(), snapshot)
        };
        drop(pending);

        self.inner.discovery_notify.notify_waiters();
        self.run_terminal_drain();
        self.inner.writer.notify_consumer();
        self.report_terminal(snapshot);
    }
}

/// Bytes the destination accepted during one drain, whether it succeeded or
/// failed part-way.
///
/// Each drain reports only the runs it wrote, so recording this once per drain
/// counts every accepted byte exactly once.
fn bytes_drained(drain: &Result<Drained, DrainError>) -> u64 {
    match drain {
        Ok(drained) => drained.bytes,
        Err(e) => e.drained.bytes,
    }
}

fn snapshot_state(state: &DownloadState, read_ahead_window: u64) -> DownloadStateSnapshot {
    match state {
        DownloadState::PendingDiscovery => DownloadStateSnapshot::inactive(
            DownloadExecutionState::PendingDiscovery,
            read_ahead_window,
        ),
        DownloadState::DiscoveryInFlight => DownloadStateSnapshot::inactive(
            DownloadExecutionState::DiscoveryInFlight,
            read_ahead_window,
        ),
        DownloadState::Transferring {
            remaining,
            ranges_in_flight,
            gate,
            pending,
            ..
        } => transferring_snapshot(
            remaining.as_ref(),
            *ranges_in_flight,
            gate,
            read_ahead_window,
            pending.is_some(),
        ),
        DownloadState::Terminal => {
            DownloadStateSnapshot::inactive(DownloadExecutionState::Terminal, read_ahead_window)
        }
    }
}

fn transferring_snapshot(
    remaining: Option<&std::ops::RangeInclusive<u64>>,
    ranges_in_flight: usize,
    gate: &super::context::OccupancyGate,
    read_ahead_window: u64,
    memory_claim_pending: bool,
) -> DownloadStateSnapshot {
    DownloadStateSnapshot {
        state: DownloadExecutionState::Transferring,
        remaining_bytes: remaining.map(|range| {
            range
                .end()
                .checked_sub(*range.start())
                .and_then(|length| length.checked_add(1))
                .expect("download state contains an invalid remaining range")
        }),
        ranges_in_flight,
        ranges_issued: gate.issued(),
        ranges_released: gate.released(),
        resident_parts: gate.resident(),
        read_ahead_window,
        memory_claim_pending,
    }
}

/// Bytes in the next chunk sliced from `remaining` at `part_size`: the reservation
/// size for that chunk. Peek only — does not advance `remaining`.
fn chunk_len(remaining: &std::ops::RangeInclusive<u64>, part_size: u64) -> usize {
    let start = *remaining.start();
    let end = *remaining.end();
    let chunk_end = cmp::min(start + part_size - 1, end);
    (chunk_end - start + 1) as usize
}

/// Copies one transport response into reserved pooled storage.
///
/// The complete validated response length is acquired before reading frames.
/// Transport framing therefore does not determine carrier acquisition or
/// immutable segmentation. A failed attempt drops the complete mutable buffer
/// before returning to the retry loop, restoring its authority to `reservation`.
///
/// A zero expected length is invalid. Empty objects complete without issuing a
/// response-collection operation.
///
/// `checksum` is the capture attached to the request that returned `body`; a body
/// error is classified from its outcome.
async fn collect_response_body(
    pool: &BufferPool,
    body: aws_sdk_s3::primitives::ByteStream,
    checksum: &ChecksumCapture,
    reservation: &Reservation,
    expected_len: usize,
    is_active: impl Fn() -> bool,
) -> Result<SegmentedBytes, Error> {
    if expected_len == 0 {
        return Err(response_length_error(0, 0));
    }
    let mut pooled = pool
        .acquire(reservation, expected_len)
        .map_err(pool_acquisition_error)?;
    let mut bytes_received = 0usize;
    let mut body_stream = body;

    while let Some(result) = body_stream.next().await {
        let data = result.map_err(|error| error::body_read_error(error, checksum.try_outcome()))?;
        let remaining = expected_len
            .checked_sub(bytes_received)
            .ok_or_else(|| response_length_error(expected_len, bytes_received))?;
        if data.len() > remaining {
            return Err(response_length_error(
                expected_len,
                bytes_received.saturating_add(data.len()),
            ));
        }

        if !data.is_empty() {
            debug_assert!(pooled.remaining_mut() >= data.len());
            pooled.put_slice(&data);
            bytes_received += data.len();
        }

        if !is_active() {
            return Err(Error::new(
                error::ErrorKind::OperationCancelled,
                "transfer cancelled during body read",
            ));
        }
    }

    if bytes_received != expected_len {
        return Err(response_length_error(expected_len, bytes_received));
    }

    Ok(pooled.freeze())
}

/// Maps a malformed response length to the body-read retry class.
fn response_length_error(expected: usize, received: usize) -> Error {
    Error::new(
        error::ErrorKind::IOError,
        format!("response body length mismatch: expected {expected} bytes, received {received}"),
    )
}

/// Pool acquisition cannot be repaired by reissuing the network request.
fn pool_acquisition_error(source: AcquireError) -> Error {
    Error::new(error::ErrorKind::RuntimeError, source)
}

/// Parse a byte range from either the request format (`bytes=START-END`) or the
/// response format (`bytes START-END/TOTAL` or `bytes START-END/*`).
///
/// Strips a leading `bytes=` or `bytes ` prefix, discards a `/TOTAL` suffix if
/// present, splits on `-`, and parses both halves as `u64`. Returns `Some((start, end))`
/// only when both parse and `start <= end`; returns `None` for any malformed input.
fn parse_byte_range(s: &str) -> Option<(u64, u64)> {
    let s = s
        .strip_prefix("bytes=")
        .or_else(|| s.strip_prefix("bytes "))
        .unwrap_or(s);
    // Strip "/TOTAL" or "/*" suffix (Content-Range format).
    let range_part = s.split('/').next()?;
    let (start_str, end_str) = range_part.split_once('-')?;
    let start: u64 = start_str.trim().parse().ok()?;
    let end: u64 = end_str.trim().parse().ok()?;
    (start <= end).then_some((start, end))
}

/// Validate that a range response delivered the requested range.
///
/// Both the requested range and the response's Content-Range are parsed to numeric
/// `(start, end)` and compared for equality. A response without Content-Range is
/// accepted only when the request covers the whole `object_len`-byte object and the
/// response's Content-Length is `object_len`, as from a server that ignores Range
/// and returns the complete object with `200 OK`. Those bytes are exactly the
/// requested range. Returns the mismatch description otherwise.
fn validate_content_range(
    requested_range: &str,
    response_content_range: Option<&str>,
    response_content_length: Option<i64>,
    object_len: Option<u64>,
) -> Result<(), String> {
    let requested = parse_byte_range(requested_range);
    let response = response_content_range.and_then(parse_byte_range);

    let whole_object = |len: u64| len.checked_sub(1).map(|end| (0, end));
    match (requested, response) {
        (Some(req), Some(resp)) if req == resp => Ok(()),
        (Some(req), None)
            if response_content_range.is_none()
                && object_len.and_then(whole_object) == Some(req)
                && response_content_length.and_then(|len| u64::try_from(len).ok())
                    == object_len =>
        {
            Ok(())
        }
        _ => Err(format!(
            "content range mismatch: requested {}, response {:?}",
            requested_range, response_content_range
        )),
    }
}

/// Converts the discovery response's metadata into the stored object's metadata.
///
/// Checksum values are kept only when they are the object's checksum: the
/// response returned the whole object ([`ObjectMetadata::covers_whole_object`]),
/// and the type is not
/// [`ChecksumType::Composite`](crate::model::ChecksumType::Composite), whose
/// value is a checksum of part checksums. Otherwise every checksum value is
/// cleared. The checksum type and every other member are kept.
fn process_object_metadata(mut meta: ObjectMetadata) -> ObjectMetadata {
    let composite = meta.checksum_type == Some(crate::model::ChecksumType::Composite);
    if composite || !meta.covers_whole_object() {
        meta.checksum_crc32 = None;
        meta.checksum_crc32_c = None;
        meta.checksum_crc64_nvme = None;
        meta.checksum_md5 = None;
        meta.checksum_sha1 = None;
        meta.checksum_sha256 = None;
        meta.checksum_sha512 = None;
        meta.checksum_xxhash64 = None;
        meta.checksum_xxhash3 = None;
        meta.checksum_xxhash128 = None;
    }
    meta
}

#[cfg(test)]
mod tests {
    use crate::types::ByteSize;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::task::{Context, Poll, Waker};

    use bytes::{Buf, Bytes};
    use http_body_1x::{Body as HttpBody, Frame, SizeHint};

    use super::*;
    use crate::model::ChecksumType;
    use crate::operation::download::sink::FileSinkFactory;
    use crate::operation::download::test_util::fixtures::{
        assert_discovery_succeeds, assert_first_range_succeeds, crc32_object_client,
        disk_test_handle, disk_transfer, execute, finalize_started, head_rule,
        object_client_failing_at, relief_scenario, spawn_relief,
    };
    use crate::operation::download::DownloadInput;
    use crate::scheduler::test_util::{assert_done, assert_pending, assert_ready};
    use crate::transfer::TransferContext;
    use crate::transfer::WorkOutcome;
    use crate::types::BucketType;
    use aws_sdk_s3::operation::get_object::GetObjectError;
    use aws_sdk_s3::operation::get_object::GetObjectOutput;
    use aws_sdk_s3::primitives::ByteStream;
    use aws_smithy_mocks::{mock, mock_client, RuleMode};
    use aws_smithy_types::error::metadata::ErrorMetadata;

    const MB: u64 = 1024 * 1024;

    #[test]
    fn download_state_snapshot_classifies_execution_and_occupancy() {
        assert_eq!(
            snapshot_state(&DownloadState::PendingDiscovery, 4),
            DownloadStateSnapshot::inactive(DownloadExecutionState::PendingDiscovery, 4)
        );
        assert_eq!(
            snapshot_state(&DownloadState::DiscoveryInFlight, 4),
            DownloadStateSnapshot::inactive(DownloadExecutionState::DiscoveryInFlight, 4)
        );
        assert_eq!(
            snapshot_state(&DownloadState::Terminal, 4),
            DownloadStateSnapshot::inactive(DownloadExecutionState::Terminal, 4)
        );

        let mut gate = super::super::context::OccupancyGate::with_issued(3);
        gate.release(1);
        let transferring = DownloadState::Transferring {
            remaining: Some(8..=15),
            ranges_in_flight: 2,
            drains_in_flight: 0,
            etag: None,
            part_size: 8,
            gate,
            pending: None,
            integrity: Box::default(),
        };
        assert_eq!(
            snapshot_state(&transferring, 4),
            DownloadStateSnapshot {
                state: DownloadExecutionState::Transferring,
                remaining_bytes: Some(8),
                ranges_in_flight: 2,
                ranges_issued: 3,
                ranges_released: 1,
                resident_parts: 2,
                read_ahead_window: 4,
                memory_claim_pending: false,
            }
        );
    }

    /// Deterministic multi-frame body separating transport frames from carriers.
    struct TestFrameBody {
        frames: std::collections::VecDeque<Bytes>,
        remaining: usize,
    }

    impl TestFrameBody {
        fn new(frames: impl IntoIterator<Item = Bytes>) -> Self {
            let frames: std::collections::VecDeque<_> = frames.into_iter().collect();
            let remaining = frames.iter().map(Bytes::len).sum();
            Self { frames, remaining }
        }

        fn into_byte_stream(self) -> aws_sdk_s3::primitives::ByteStream {
            aws_sdk_s3::primitives::ByteStream::from_body_1_x(self)
        }
    }

    impl HttpBody for TestFrameBody {
        type Data = Bytes;
        type Error = std::convert::Infallible;

        fn poll_frame(
            mut self: Pin<&mut Self>,
            _context: &mut Context<'_>,
        ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
            let Some(frame) = self.frames.pop_front() else {
                return Poll::Ready(None);
            };
            self.remaining = self
                .remaining
                .checked_sub(frame.len())
                .expect("test frame accounting underflow");
            Poll::Ready(Some(Ok(Frame::data(frame))))
        }

        fn is_end_stream(&self) -> bool {
            self.frames.is_empty()
        }

        fn size_hint(&self) -> SizeHint {
            SizeHint::with_exact(self.remaining as u64)
        }
    }

    struct CountedFrame {
        bytes: Vec<u8>,
        drops: Arc<AtomicUsize>,
    }

    impl AsRef<[u8]> for CountedFrame {
        fn as_ref(&self) -> &[u8] {
            &self.bytes
        }
    }

    impl Drop for CountedFrame {
        fn drop(&mut self) {
            self.drops.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn test_pool() -> BufferPool {
        crate::memory::BufferPool::builder()
            .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                128 * 1024,
            )))
            .build()
            .expect("response collector test pool")
    }

    fn collect_ready(
        pool: &BufferPool,
        body: aws_sdk_s3::primitives::ByteStream,
        reservation: &Reservation,
        expected_len: usize,
    ) -> Result<SegmentedBytes, Error> {
        collect_ready_with(pool, body, reservation, expected_len, || true)
    }

    fn collect_ready_with(
        pool: &BufferPool,
        body: aws_sdk_s3::primitives::ByteStream,
        reservation: &Reservation,
        expected_len: usize,
        is_active: impl Fn() -> bool,
    ) -> Result<SegmentedBytes, Error> {
        let checksum = ChecksumCapture::new();
        let mut future = std::pin::pin!(collect_response_body(
            pool,
            body,
            &checksum,
            reservation,
            expected_len,
            is_active,
        ));
        let mut context = Context::from_waker(Waker::noop());
        match future.as_mut().poll(&mut context) {
            Poll::Ready(result) => result,
            Poll::Pending => panic!("in-memory test body unexpectedly yielded Pending"),
        }
    }

    /// Transport frame boundaries do not become acquisition or segment
    /// boundaries when the complete response length is known.
    #[test]
    fn test_collection_acquires_response_once_and_releases_foreign_frames() {
        const FRAME_LEN: usize = 9_000;
        const EXPECTED_LEN: usize = FRAME_LEN * 3;

        let pool = test_pool();
        let reservation = pool
            .try_reserve(EXPECTED_LEN)
            .unwrap()
            .expect("collector reservation");
        let expected: Vec<u8> = (0..EXPECTED_LEN)
            .map(|index| (index.wrapping_mul(31) % 251) as u8)
            .collect();
        let drops = Arc::new(AtomicUsize::new(0));
        let first = Bytes::from_owner(CountedFrame {
            bytes: expected[..FRAME_LEN].to_vec(),
            drops: Arc::clone(&drops),
        });
        let body = TestFrameBody::new([
            Bytes::new(),
            first,
            Bytes::copy_from_slice(&expected[FRAME_LEN..FRAME_LEN * 2]),
            Bytes::copy_from_slice(&expected[FRAME_LEN * 2..]),
        ])
        .into_byte_stream();

        let acquisitions_before = pool.acquisition_attempts();
        let mut output = collect_ready(&pool, body, &reservation, EXPECTED_LEN)
            .expect("response fits its reserved envelope");

        assert_eq!(
            pool.acquisition_attempts() - acquisitions_before,
            1,
            "one response must perform one carrier acquisition"
        );
        assert_eq!(output.len(), EXPECTED_LEN);
        let mut slices = [std::io::IoSlice::new(&[]); 4];
        assert_eq!(
            output.chunks_vectored(&mut slices),
            1,
            "adjacent carriers from one acquisition should form one segment"
        );
        assert_eq!(
            drops.load(Ordering::Relaxed),
            1,
            "transport owner must drop after its frame is copied"
        );
        assert_ne!(pool.metrics().in_use_bytes(), 0);
        assert_eq!(output.copy_to_bytes(EXPECTED_LEN).as_ref(), expected);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_collection_rejects_zero_length_without_acquiring_storage() {
        let pool = test_pool();
        let reservation = pool
            .try_reserve(pool.carrier_size())
            .unwrap()
            .expect("collector reservation");
        let acquisitions_before = pool.acquisition_attempts();

        let error = collect_ready(
            &pool,
            TestFrameBody::new([]).into_byte_stream(),
            &reservation,
            0,
        )
        .expect_err("zero-length collection unexpectedly succeeded");

        assert_eq!(error.kind(), &error::ErrorKind::IOError);
        assert_eq!(pool.acquisition_attempts(), acquisitions_before);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_short_attempt_restores_reservation_authority_before_retry() {
        const EXPECTED_LEN: usize = 20_000;

        let pool = test_pool();
        let reservation = pool
            .try_reserve(EXPECTED_LEN)
            .unwrap()
            .expect("collector reservation");
        let short = TestFrameBody::new([
            Bytes::from(vec![0x11; 9_000]),
            Bytes::from(vec![0x22; 9_000]),
        ])
        .into_byte_stream();

        let error = collect_ready(&pool, short, &reservation, EXPECTED_LEN)
            .expect_err("short attempt unexpectedly succeeded");
        assert_eq!(error.kind(), &error::ErrorKind::IOError);
        assert_eq!(pool.metrics().in_use_bytes(), 0);

        let expected: Vec<u8> = (0..EXPECTED_LEN)
            .map(|index| (index.wrapping_mul(17) % 251) as u8)
            .collect();
        let retry = TestFrameBody::new([
            Bytes::copy_from_slice(&expected[..7_000]),
            Bytes::copy_from_slice(&expected[7_000..]),
        ])
        .into_byte_stream();
        let output = collect_ready(&pool, retry, &reservation, EXPECTED_LEN)
            .expect("retry reacquires returned authority");

        assert_eq!(
            output.clone().copy_to_bytes(EXPECTED_LEN).as_ref(),
            expected
        );
        reservation.close_acquisition();
        assert_ne!(
            pool.metrics().in_use_bytes(),
            0,
            "immutable output retains pooled owners after reservation close"
        );
        drop(output);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_collection_rejects_same_carrier_length_overrun() {
        const EXPECTED_LEN: usize = 8;

        let pool = test_pool();
        let reservation = pool
            .try_reserve(EXPECTED_LEN)
            .unwrap()
            .expect("collector reservation");
        let body = TestFrameBody::new([Bytes::from_static(b"123456789")]).into_byte_stream();

        let error = collect_ready(&pool, body, &reservation, EXPECTED_LEN)
            .expect_err("oversized attempt unexpectedly succeeded");

        assert_eq!(error.kind(), &error::ErrorKind::IOError);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_collection_observes_cancellation_after_an_empty_frame() {
        let pool = test_pool();
        let reservation = pool.try_reserve(4).unwrap().expect("collector reservation");
        let body =
            TestFrameBody::new([Bytes::new(), Bytes::from_static(b"data")]).into_byte_stream();

        let error = collect_ready_with(&pool, body, &reservation, 4, || false)
            .expect_err("cancelled attempt unexpectedly succeeded");

        assert_eq!(error.kind(), &error::ErrorKind::OperationCancelled);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_collection_rejects_reservation_envelope_exhaustion() {
        const RESPONSE_LEN: usize = 128 * 1024;

        let pool = test_pool();
        let reservation = pool.try_reserve(1).unwrap().expect("one-carrier envelope");
        let body = TestFrameBody::new([Bytes::from(vec![0; RESPONSE_LEN])]).into_byte_stream();

        let error = collect_ready(&pool, body, &reservation, RESPONSE_LEN)
            .expect_err("acquisition escaped its reservation envelope");

        assert_eq!(error.kind(), &error::ErrorKind::RuntimeError);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
        drop(
            pool.acquire(&reservation, 1)
                .expect("failed acquisition did not consume direct authority"),
        );
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    // ref: RUST-1676
    #[test]
    fn object_metadata_clears_checksum_values_that_do_not_describe_the_object() {
        let meta = |checksum_type, content_range: Option<&str>| {
            let mut m = ObjectMetadata::default();
            m.checksum_crc32 = Some("DUoRhQ==".to_string());
            m.checksum_type = Some(checksum_type);
            m.content_range = content_range.map(str::to_owned);
            m
        };

        // A response covering the whole object keeps its value.
        for range in [None, Some("bytes 0-99/100")] {
            let m = process_object_metadata(meta(ChecksumType::FullObject, range));
            assert_eq!(m.checksum_crc32(), Some("DUoRhQ=="), "{range:?}");
        }

        // A part or range of the object describes that part, whatever its type.
        for range in ["bytes 0-49/100", "bytes 50-99/100"] {
            let m = process_object_metadata(meta(ChecksumType::FullObject, Some(range)));
            assert_eq!(m.checksum_crc32(), None, "{range}");
            assert_eq!(m.checksum_type(), Some(&ChecksumType::FullObject));
        }

        // A composite value is a checksum of part checksums.
        let m = process_object_metadata(meta(ChecksumType::Composite, None));
        assert_eq!(m.checksum_crc32(), None);
        assert_eq!(m.checksum_type(), Some(&ChecksumType::Composite));
    }

    /// Names of the checksum value members of `ObjectMetadata`, read from its `Debug`
    /// output so a member added by regeneration is seen without being listed here.
    fn checksum_value_members(meta: &ObjectMetadata) -> Vec<String> {
        format!("{meta:#?}")
            .lines()
            .filter_map(|line| line.trim().split_once(": "))
            .map(|(name, _)| name)
            .filter(|name| name.starts_with("checksum_") && *name != "checksum_type")
            .map(str::to_owned)
            .collect()
    }

    /// This is a guard test to make sure every checksum value member is cleared.
    /// Fails when `ObjectMetadata` gains a checksum value member that this test
    /// does not populate, which is the signal to extend both this test and
    /// `process_object_metadata`.
    /// TODO: update `process_object_metadata` to handle extended checksum member.
    #[test]
    fn object_metadata_clears_every_checksum_value_member() {
        let mut meta = ObjectMetadata::default();
        meta.checksum_crc32 = Some("v".to_owned());
        meta.checksum_crc32_c = Some("v".to_owned());
        meta.checksum_crc64_nvme = Some("v".to_owned());
        meta.checksum_md5 = Some("v".to_owned());
        meta.checksum_sha1 = Some("v".to_owned());
        meta.checksum_sha256 = Some("v".to_owned());
        meta.checksum_sha512 = Some("v".to_owned());
        meta.checksum_xxhash64 = Some("v".to_owned());
        meta.checksum_xxhash3 = Some("v".to_owned());
        meta.checksum_xxhash128 = Some("v".to_owned());
        meta.checksum_type = Some(ChecksumType::Composite);

        let members = checksum_value_members(&meta);
        assert!(
            !members.is_empty(),
            "no checksum members found in Debug output"
        );
        let populated = format!("{meta:#?}");
        for member in &members {
            assert!(
                populated.contains(&format!("{member}: Some(")),
                "`{member}` is not populated by this test; set it and clear it in process_object_metadata"
            );
        }

        let cleared = format!("{:#?}", process_object_metadata(meta));
        for member in &members {
            assert!(
                cleared.contains(&format!("{member}: None")),
                "`{member}` was not cleared"
            );
        }
    }

    fn create_download(object_size: u64, part_size: u64) -> DownloadTransfer {
        create_download_with_detail(object_size, part_size, 0)
    }

    fn create_download_with_detail(
        object_size: u64,
        part_size: u64,
        detail: u64,
    ) -> DownloadTransfer {
        let chunk = vec![0u8; part_size as usize];
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_output(move || {
            GetObjectOutput::builder()
                .content_length(part_size as i64)
                .content_range(format!("bytes 0-{}/{}", part_size - 1, object_size))
                .e_tag("test-etag")
                .body(ByteStream::from(chunk.clone()))
                .build()
        });
        create_get_first_download_with_client_and_detail(
            mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj]),
            part_size,
            detail,
            Some(object_size),
        )
    }

    fn create_get_first_download_with_client_and_detail(
        client: aws_sdk_s3::Client,
        part_size: u64,
        detail: u64,
        object_size: Option<u64>,
    ) -> DownloadTransfer {
        let config = crate::Config::builder()
            .sdk_client(client)
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
            .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), detail)
            .build()
            .expect("valid config");

        let handle = crate::client::Handle::test_handle_tokio(config);

        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .set_range(object_size.map(|len| format!("bytes=0-{}", len - 1)))
            .build()
            .unwrap();

        let (writer, _consumer) = crate::operation::download::body::new_recv_body();
        let (ctx, _completion_rx) = TransferContext::new(handle);

        DownloadTransfer::new(ctx, BucketType::Standard, input, writer)
    }

    /// Request mode overrides client policy; an unset mode follows the client default.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn validation_enabled_resolves_request_and_client_settings() {
        use aws_sdk_s3::config::ResponseChecksumValidation::{WhenRequired, WhenSupported};

        for (client_setting, unset_enabled) in [
            (None, true),
            (Some(WhenSupported), true),
            (Some(WhenRequired), false),
        ] {
            let client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[head_rule(0)], |conf| {
                match client_setting {
                    Some(setting) => conf.response_checksum_validation(setting),
                    None => conf,
                }
            });
            let transfer =
                create_get_first_download_with_client_and_detail(client, 8 * MB, 0, None);
            for (request_mode, expected) in [
                (None, unset_enabled),
                (Some(crate::model::ChecksumMode::Enabled), true),
            ] {
                let input = DownloadInput::builder()
                    .bucket("test-bucket")
                    .key("test-key")
                    .set_checksum_mode(request_mode)
                    .build()
                    .unwrap();
                assert_eq!(
                    transfer.validation_enabled(&input),
                    expected,
                    "client={client_setting:?}, request={:?}",
                    input.checksum_mode,
                );
            }
        }
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_initial_poll_returns_discovery() {
        let transfer = create_download(24 * MB, 8 * MB);
        let mut work = assert_ready(transfer.poll_work());
        let data = work.data_mut::<DownloadWork>();
        assert!(matches!(data, DownloadWork::Discovery));
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_pending_while_discovery_in_flight() {
        let transfer = create_download(24 * MB, 8 * MB);
        let _work = assert_ready(transfer.poll_work());
        assert_pending(transfer.poll_work());
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_generates_ranges_after_discovery() {
        let transfer = create_download(24 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;
        assert_eq!(
            transfer.ctx().metrics.request_metrics().requests,
            1,
            "discovery headers and its lazy response body are one request"
        );

        let mut work = assert_ready(transfer.poll_work());
        let data = work.data_mut::<DownloadWork>();
        assert!(matches!(data, DownloadWork::GetObjectRange { .. }));
    }

    /// Transfer diagnostic levels must not alter the download outcome. Summary
    /// levels report S3 receive completion while the stream still owns its
    /// unread resident chunk.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn diagnostic_levels_preserve_stream_download_outcome() {
        for detail in 0..=2 {
            let transfer = create_download_with_detail(8 * MB, 8 * MB, detail);
            assert_discovery_succeeds(&transfer).await;

            assert_eq!(
                transfer.ctx().transfer_status(),
                crate::types::TransferStatus::Completed
            );

            let summary = transfer.test_terminal_summary();
            if detail == 0 {
                assert!(summary.is_none());
                continue;
            }

            let summary = summary.expect("summary diagnostics enabled");
            assert_eq!(
                summary.outcome,
                crate::operation::download::observability::DownloadTerminalOutcome::Completed
            );
            assert_eq!(summary.destination, DownloadDestination::Stream);
            assert_eq!(summary.metrics.network_rx, 8 * MB);
            assert_eq!(summary.metrics.disk_write, 0);
            assert_eq!(summary.requests.discovery_range.requests, 1);
            assert_eq!(summary.requests.range.requests, 0);
            assert_eq!(summary.request_total.requests, 1);
            assert_eq!(summary.ranges_scheduled, 1);
            assert_eq!(summary.ranges_completed, 1);
            assert_eq!(
                summary.last_active_snapshot.resident_parts, 1,
                "terminal receive does not imply stream-consumer delivery"
            );
            assert!(!summary.destination_work.file_finalized);
        }
    }

    /// Empty-object discovery falls back from an invalid initial range to
    /// part-number discovery, then completes without synthesizing range work.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn empty_download_summary_records_discovery_without_ranges() {
        let part_size = 8 * MB;
        let expected_range = format!("bytes=0-{}", part_size - 1);
        let ranged = mock!(aws_sdk_s3::Client::get_object)
            .match_requests(move |request| request.range() == Some(expected_range.as_str()))
            .then_error(|| {
                GetObjectError::generic(ErrorMetadata::builder().code("InvalidRange").build())
            });
        let part = mock!(aws_sdk_s3::Client::get_object)
            .match_requests(|request| request.part_number() == Some(1))
            .then_output(|| GetObjectOutput::builder().content_length(0).build());
        let client = mock_client!(
            aws_sdk_s3,
            RuleMode::Sequential,
            &[&ranged, &part],
            |conf| {
                conf.response_checksum_validation(
                    aws_sdk_s3::config::ResponseChecksumValidation::WhenRequired,
                )
            }
        );
        let transfer = create_get_first_download_with_client_and_detail(client, part_size, 1, None);

        assert_discovery_succeeds(&transfer).await;
        assert_done(transfer.poll_work());

        let summary = transfer
            .test_terminal_summary()
            .expect("summary diagnostics enabled");
        assert_eq!(
            summary.outcome,
            crate::operation::download::observability::DownloadTerminalOutcome::Completed
        );
        assert_eq!(summary.metrics.total_bytes, Some(0));
        assert_eq!(summary.metrics.network_rx, 0);
        assert_eq!(summary.requests.discovery_range.requests, 1);
        assert_eq!(summary.requests.discovery_part.requests, 1);
        assert_eq!(summary.request_total.requests, 2);
        assert_eq!(summary.ranges_scheduled, 0);
        assert_eq!(summary.ranges_completed, 0);
    }

    /// A zero-byte object has no ranges, so discovery is the last work item to
    /// finish: its `execute` claims completion and finalizes the destination,
    /// and the next poll finds the transfer done.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn zero_byte_object_completes_from_discovery() {
        use crate::operation::download::test_util::sink::{
            Event, Op, ScriptedSinkFactory, WriteScript,
        };

        let part_size = 8 * MB;
        let client = mock_client!(aws_sdk_s3, &[head_rule(0)]);
        let script = Arc::new(WriteScript::default());
        let (transfer, _consumer, _dir) = disk_transfer(
            disk_test_handle(client, part_size),
            &ScriptedSinkFactory(Arc::clone(&script)),
        );

        let mut discovery = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut discovery).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );
        let finalize = Op::Finalize { len: 0 };
        assert_eq!(
            script.events(),
            [Event::Started(finalize), Event::Finished(finalize, Ok(()))],
            "discovery's execute finalized the destination"
        );
        assert_done(transfer.poll_work());
    }

    /// The terminal hook completes cleanup and reports a summary when a worker
    /// panicked while holding the state lock.
    #[cfg_attr(miri, ignore)]
    #[test]
    fn on_terminal_tolerates_poisoned_state() {
        let transfer = create_download_with_detail(24 * MB, 8 * MB, 1);
        let _discovery = assert_ready(transfer.poll_work());
        std::thread::scope(|scope| {
            let poisoner = scope.spawn(|| {
                let _guard = transfer.inner.state.lock().unwrap();
                panic!("invalid discovery state");
            });
            assert!(poisoner.join().is_err());
        });
        assert!(
            transfer.inner.state.lock().is_err(),
            "state should be poisoned"
        );
        transfer.ctx().set_failed(error::Error::new(
            error::ErrorKind::RuntimeError,
            "worker panic during execute",
        ));

        let cleanup =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| transfer.on_terminal()));
        assert!(
            cleanup.is_ok(),
            "on_terminal must tolerate a poisoned state"
        );

        let summary = transfer
            .test_terminal_summary()
            .expect("poisoned state should still emit a terminal summary");
        assert_eq!(
            summary.outcome,
            crate::operation::download::observability::DownloadTerminalOutcome::Failed
        );
    }

    /// External cancellation must close pending diagnostics and report one
    /// terminal summary through the scheduler-owned terminal hook.
    #[cfg_attr(miri, ignore)]
    #[test]
    fn external_cancellation_reports_pending_discovery_once() {
        let transfer = create_download_with_detail(24 * MB, 8 * MB, 1);
        let _discovery = assert_ready(transfer.poll_work());
        assert_pending(transfer.poll_work());

        transfer.ctx().set_cancelled();
        transfer.on_terminal();
        transfer.ctx().signal_terminal();
        transfer.on_terminal();

        let summary = transfer
            .test_terminal_summary()
            .expect("cancellation summary");
        assert_eq!(
            summary.outcome,
            crate::operation::download::observability::DownloadTerminalOutcome::Cancelled
        );
        assert_eq!(
            summary
                .pending
                .category(crate::transfer::PendingCategory::InFlightWork)
                .count,
            1
        );
        assert_eq!(
            summary.last_active_snapshot.state,
            DownloadExecutionState::DiscoveryInFlight
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_seq_starts_at_one_with_initial_chunk() {
        let transfer = create_download(24 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        let mut work = assert_ready(transfer.poll_work());
        let data = work.data_mut::<DownloadWork>();
        match data {
            DownloadWork::GetObjectRange { slot, .. } => {
                assert_eq!(
                    slot.as_ref().unwrap().seq(),
                    1,
                    "seq should start at 1 when initial chunk claims seq=0"
                );
            }
            _ => panic!("expected GetObjectRange"),
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_seq_starts_at_zero_without_initial_chunk() {
        let head_obj = mock!(aws_sdk_s3::Client::head_object).then_output(|| {
            aws_sdk_s3::operation::head_object::HeadObjectOutput::builder()
                .content_length(24 * MB as i64)
                .content_range(format!("bytes 0-{}/{}", 24 * MB - 1, 24 * MB))
                .e_tag("test-etag")
                .build()
        });
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_output(|| {
            aws_sdk_s3::operation::get_object::GetObjectOutput::builder()
                .content_length(8 * MB as i64)
                .content_range(format!("bytes 0-{}/{}", 8 * MB - 1, 24 * MB))
                .e_tag("test-etag")
                .body(ByteStream::from(vec![0u8; 8 * MB as usize]))
                .build()
        });
        let client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[head_obj, get_obj]);

        let config = crate::Config::builder()
            .sdk_client(client)
            .part_size(crate::config::PartSize::Target(ByteSize::new(8 * MB)))
            .build()
            .expect("valid config");

        let handle = crate::client::Handle::test_handle_tokio(config);

        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .range("bytes=0-")
            .build()
            .unwrap();

        let (writer, _consumer) = crate::operation::download::body::new_recv_body();
        let (ctx, _completion_rx) = TransferContext::new(handle);
        let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer);

        assert_discovery_succeeds(&transfer).await;

        let mut work = assert_ready(transfer.poll_work());
        let data = work.data_mut::<DownloadWork>();
        match data {
            DownloadWork::GetObjectRange { slot, .. } => {
                assert_eq!(
                    slot.as_ref().unwrap().seq(),
                    0,
                    "seq should start at 0 when no initial chunk"
                );
            }
            _ => panic!("expected GetObjectRange"),
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_seq_increments_sequentially() {
        let transfer = create_download(32 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        let mut seqs = Vec::new();
        while let PollWork::Ready { io: mut w, .. } = transfer.poll_work() {
            let data = w.data_mut::<DownloadWork>();
            if let DownloadWork::GetObjectRange { slot, .. } = data {
                seqs.push(slot.as_ref().unwrap().seq());
            }
        }

        assert_eq!(seqs.len(), 3, "expected multiple ranges");
        for i in 1..seqs.len() {
            assert_eq!(seqs[i], seqs[i - 1] + 1, "seqs should be sequential");
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_pending_when_range_in_flight() {
        let transfer = create_download(12 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        // generate range work but don't complete
        let _range = assert_ready(transfer.poll_work());
        // transfer is considered active and shouldn't transition to done until all in-flight work is complete and handle is joined/dropped
        assert_pending(transfer.poll_work());
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_done_when_all_complete() {
        let transfer = create_download(12 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        let mut range = assert_ready(transfer.poll_work());
        execute(&transfer, &mut range).await;

        assert_done(transfer.poll_work());
        assert_eq!(transfer.ctx().metrics.request_metrics().requests, 2);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_out_of_order_completion() {
        let transfer = create_download(24 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        let mut range1 = assert_ready(transfer.poll_work()); // seq=1
        let mut range2 = assert_ready(transfer.poll_work()); // seq=2

        // Complete in reverse order
        execute(&transfer, &mut range2).await;
        execute(&transfer, &mut range1).await;

        assert_done(transfer.poll_work());
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_failure_transitions_to_failed() {
        let _logs = show_test_logs();
        // Fail seq 1 (first range after discovery)
        let transfer = FailureConfig::new(24 * MB, 8 * MB)
            .fail(1)
            .detail(1)
            .build();

        assert_discovery_succeeds(&transfer).await;

        let mut range = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut range).await;

        assert!(matches!(outcome, WorkOutcome::Failed { .. }));
        assert!(transfer.ctx().is_failed());
        let summary = transfer
            .test_terminal_summary()
            .expect("failure summary diagnostics enabled");
        assert_eq!(
            summary.outcome,
            crate::operation::download::observability::DownloadTerminalOutcome::Failed
        );
        assert_eq!(summary.requests.discovery_range.requests, 1);
        assert_eq!(summary.requests.range.requests, 1);
        assert_eq!(summary.requests.range.retry_reissues, 0);
        assert_eq!(summary.requests.range.retry_exhaustions, 0);
        assert_eq!(summary.ranges_scheduled, 2);
        assert_eq!(summary.ranges_completed, 1);
    }

    /// Discovery and post-discovery range requests retain separate request
    /// aggregates while contributing to the same transfer total.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn multi_range_summary_separates_discovery_and_range_requests() {
        let transfer = FailureConfig::new(12 * MB, 8 * MB).detail(1).build();

        assert_discovery_succeeds(&transfer).await;
        let mut range = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut range).await;

        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        let summary = transfer
            .test_terminal_summary()
            .expect("summary diagnostics enabled");
        assert_eq!(summary.requests.discovery_range.requests, 1);
        assert_eq!(summary.requests.range.requests, 1);
        assert_eq!(summary.request_total.requests, 2);
        assert_eq!(summary.ranges_scheduled, 2);
        assert_eq!(summary.ranges_completed, 2);
        assert_eq!(summary.metrics.network_rx, 12 * MB);
    }

    /// A ranged discovery request remains one logical request while its lazy
    /// body is validated and reissued. The reissue is attributed to that
    /// discovery kind rather than counted as a second standalone request.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn discovery_body_reissue_stays_with_discovery_request_metrics() {
        let part_size = 8 * MB;
        let calls = Arc::new(AtomicUsize::new(0));
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_compute_response({
            let calls = Arc::clone(&calls);
            move |_| {
                let call = calls.fetch_add(1, Ordering::SeqCst);
                let body_len = if call == 0 { part_size / 2 } else { part_size };
                MockResponse::Output(
                    GetObjectOutput::builder()
                        .content_length(part_size as i64)
                        .content_range(format!("bytes 0-{}/{}", part_size - 1, part_size))
                        .e_tag("test-etag")
                        .body(ByteStream::from(vec![0u8; body_len as usize]))
                        .build(),
                )
            }
        });
        let client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj], |conf| {
            conf.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
        });
        let transfer =
            create_get_first_download_with_client_and_detail(client, part_size, 1, Some(part_size));

        assert_discovery_succeeds(&transfer).await;

        assert_eq!(calls.load(Ordering::SeqCst), 2);
        let summary = transfer
            .test_terminal_summary()
            .expect("summary diagnostics enabled");
        assert_eq!(summary.requests.discovery_range.requests, 1);
        assert_eq!(summary.requests.discovery_range.retry_reissues, 1);
        assert_eq!(summary.request_total.requests, 1);
        assert_eq!(summary.request_total.retry_reissues, 1);
        assert_eq!(summary.requests.range.requests, 0);
    }

    /// Time a discovery body spends waiting for memory admission is not part of
    /// the discovery request's elapsed time.
    #[cfg_attr(miri, ignore)]
    #[tokio::test(start_paused = true)]
    async fn discovery_memory_wait_is_excluded_from_request_elapsed() {
        let part_size = 8 * MB;
        let memory_wait = std::time::Duration::from_secs(10);
        let (transfer, _consumer) =
            create_download_for_gate_with_capacity(part_size, part_size, Some(part_size as usize));
        let pool = transfer.ctx().handle.buffer_pool.clone();
        let blocker = pool
            .try_reserve(part_size as usize)
            .unwrap()
            .expect("test blocker");

        let mut work = assert_ready(transfer.poll_work());
        let executing = transfer.clone();
        let task = tokio::spawn(async move { execute(&executing, &mut work).await });

        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            while pool.metrics().waiting_requests() != 1 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("discovery reservation should enter the memory FIFO");

        tokio::time::sleep(memory_wait).await;
        drop(blocker);

        assert!(matches!(task.await.unwrap(), WorkOutcome::Success { .. }));
        let requests = transfer.ctx().metrics.request_metrics();
        assert_eq!(requests.requests, 1);
        assert!(
            requests.max_elapsed < memory_wait / 10,
            "discovery request elapsed {:?} includes the {memory_wait:?} memory wait",
            requests.max_elapsed,
        );
    }

    /// S3 connector for a two-part multipart object whose `partNumber=1`
    /// response is delayed. Ranged GETs are answered immediately with the
    /// requested bytes.
    #[derive(Debug)]
    struct DelayedFirstPartConnector {
        object_size: u64,
        stored_part_size: u64,
        part_delay: std::time::Duration,
    }

    impl aws_smithy_runtime_api::client::http::HttpConnector for DelayedFirstPartConnector {
        fn call(
            &self,
            request: aws_smithy_runtime_api::client::orchestrator::HttpRequest,
        ) -> aws_smithy_runtime_api::client::http::HttpConnectorFuture {
            use aws_smithy_runtime_api::client::http::HttpConnectorFuture;
            use aws_smithy_runtime_api::client::orchestrator::HttpResponse;

            if request.method() == "HEAD" {
                let mut response = HttpResponse::new(
                    200.try_into().unwrap(),
                    aws_smithy_types::body::SdkBody::empty(),
                );
                response
                    .headers_mut()
                    .insert("content-length", self.object_size.to_string());
                response.headers_mut().insert("etag", "\"abc-2\"");
                response
                    .headers_mut()
                    .insert("x-amz-checksum-crc32", "AAAAAA==-2");
                response
                    .headers_mut()
                    .insert("x-amz-checksum-type", "COMPOSITE");
                return HttpConnectorFuture::ready(Ok(response));
            }
            let is_part_request = request.uri().contains("partNumber=1");
            let (start, end) = if is_part_request {
                (0, self.stored_part_size - 1)
            } else {
                request
                    .headers()
                    .get("range")
                    .and_then(parse_byte_range)
                    .unwrap_or_else(|| panic!("unexpected request: {}", request.uri()))
            };
            let len = end - start + 1;
            let mut response = HttpResponse::new(
                206.try_into().unwrap(),
                aws_smithy_types::body::SdkBody::from(vec![0u8; len as usize]),
            );
            let headers = response.headers_mut();
            headers.insert("Content-Length", len.to_string());
            headers.insert(
                "Content-Range",
                format!("bytes {start}-{end}/{}", self.object_size),
            );
            headers.insert("ETag", "\"abc-2\"");

            if is_part_request {
                let delay = self.part_delay;
                HttpConnectorFuture::new(async move {
                    tokio::time::sleep(delay).await;
                    Ok(response)
                })
            } else {
                HttpConnectorFuture::ready(Ok(response))
            }
        }
    }

    /// The layout GET accrues its own latency independently of the completed HEAD.
    #[cfg_attr(miri, ignore)]
    #[tokio::test(start_paused = true)]
    async fn layout_get_latency_is_excluded_from_head_discovery_elapsed() {
        let stored_part_size = 8 * MB;
        let part_delay = std::time::Duration::from_secs(10);
        let connector = aws_smithy_runtime_api::client::http::SharedHttpConnector::new(
            DelayedFirstPartConnector {
                object_size: 2 * stored_part_size,
                stored_part_size,
                part_delay,
            },
        );
        let http_client =
            aws_smithy_runtime_api::client::http::http_client_fn(move |_, _| connector.clone());
        let client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client)
                .region(aws_sdk_s3::config::Region::new("us-west-2"))
                .with_test_defaults()
                .build(),
        );
        // Automatic sizing uses the stored first part after checksum-mode HEAD.
        let config = crate::Config::builder()
            .sdk_client(client)
            .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), 1)
            .build()
            .expect("valid config");
        let handle = crate::client::Handle::test_handle_tokio(config);
        assert!(!handle.user_set_part_size());
        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .build()
            .unwrap();
        let (writer, _consumer) = crate::operation::download::body::new_recv_body();
        let (ctx, _completion_rx) = TransferContext::new(handle);
        let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer);

        assert_discovery_succeeds(&transfer).await;
        let mut range = assert_ready(transfer.poll_work());
        assert!(matches!(
            execute(&transfer, &mut range).await,
            WorkOutcome::Success { .. }
        ));

        let summary = transfer
            .test_terminal_summary()
            .expect("summary diagnostics enabled");
        assert_eq!(summary.requests.discovery_head.requests, 1);
        assert_eq!(summary.requests.discovery_part.requests, 1);
        assert_eq!(summary.requests.range.requests, 1);
        assert!(
            summary.requests.discovery_part.elapsed >= part_delay,
            "the delayed layout GET accrues to its own request: {:?}",
            summary.requests.discovery_part.elapsed,
        );
        assert!(
            summary.requests.discovery_head.elapsed < part_delay / 10,
            "HEAD discovery elapsed {:?} includes the {part_delay:?} re-issue",
            summary.requests.discovery_head.elapsed,
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancellation_transitions_to_cancelled() {
        let transfer = create_download(24 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;

        transfer.ctx().set_cancelled();
        transfer.ctx().signal_terminal();

        assert!(transfer.ctx().is_cancelled());
        assert_done(transfer.poll_work());
    }

    fn create_download_for_gate(
        object_size: u64,
        part_size: u64,
    ) -> (
        DownloadTransfer,
        crate::operation::download::body::RecvBodyConsumer,
    ) {
        create_download_for_gate_with_capacity(object_size, part_size, None)
    }

    fn create_download_for_gate_with_capacity(
        object_size: u64,
        part_size: u64,
        capacity_bytes: Option<usize>,
    ) -> (
        DownloadTransfer,
        crate::operation::download::body::RecvBodyConsumer,
    ) {
        let chunk = vec![0u8; part_size as usize];
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_output(move || {
            GetObjectOutput::builder()
                .content_length(part_size as i64)
                .content_range(format!("bytes 0-{}/{}", part_size - 1, object_size))
                .e_tag("test-etag")
                .body(ByteStream::from(chunk.clone()))
                .build()
        });
        let client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj]);

        let mut config = crate::Config::builder()
            .sdk_client(client)
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)));
        if let Some(capacity_bytes) = capacity_bytes {
            let pool = crate::memory::BufferPool::builder()
                .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                    capacity_bytes as u64,
                )))
                .build()
                .expect("test pool");
            config = config.memory(crate::config::MemoryConfig::Explicit(pool));
        }
        let config = config.build().expect("valid config");

        let handle = crate::client::Handle::test_handle_tokio(config);

        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .range(format!("bytes=0-{}", object_size - 1))
            .build()
            .unwrap();

        let (writer, consumer) = crate::operation::download::body::new_recv_body();
        let (ctx, _completion_rx) = TransferContext::new(handle);
        let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer);
        (transfer, consumer)
    }

    /// The read-ahead gate bounds issuance at the current window: with a small window,
    /// issuance proceeds up to `issued − released == window()`, then stalls. Tests the
    /// gate wiring; `read_ahead`'s own tests cover resolving the window value.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_read_ahead_gate_bounds_issuance() {
        let (transfer, _consumer) = create_download_for_gate(128 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;
        // Force a small window so a few polls exercise the gate; the default is large.
        transfer.read_ahead().force_window(3);
        let w = transfer.read_ahead().window();
        // Discovery claimed seq 0 (issued=1, consumed=0). Drive until the gate stalls.
        let mut issued = 1u64;
        loop {
            match transfer.poll_work() {
                PollWork::Ready { .. } => {
                    issued += 1;
                    assert!(issued <= w, "issuance ran past the window");
                }
                PollWork::Spawned => {}
                PollWork::Pending => break,
                PollWork::Done => panic!("unexpected Done"),
            }
        }
        assert_eq!(issued, w, "issuance should fill the window then stall");
    }

    /// On the stream path, delivering a chunk frees one part; the download layer
    /// releases that occupancy under the state lock (as `Body::next` does via
    /// `release_stream_occupancy`), so `issued − released` drops below the window and
    /// the gate admits another claim.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_consume_reopens_gate() {
        let (transfer, mut consumer) = create_download_for_gate(128 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;
        transfer.read_ahead().force_window(3);
        // Fill the window.
        while let PollWork::Ready { .. } = transfer.poll_work() {}
        assert_pending(transfer.poll_work());

        // Consume seq 0 (filled by discovery) — the buffer delivers the chunk, then the
        // download layer releases one part of occupancy under the state lock. This is
        // exactly what `Body::next` does; the test drives the two steps directly.
        assert!(
            consumer.try_take_next().is_some(),
            "discovery chunk should deliver"
        );
        transfer.release_stream_occupancy();

        // Gate reopens for exactly one more claim.
        assert_ready(transfer.poll_work());
        assert_pending(transfer.poll_work());
    }

    /// Shared memory admission is the second issuance gate. With the read-ahead
    /// window open, a transfer still returns `Pending` when its memory budget is
    /// exhausted. It retains the claimed slot and resumes when a delivered chunk
    /// returns its carrier charge and capacity is granted to the FIFO head.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_admission_blocks_then_resumes_in_fifo_order() {
        let part_size = 8 * MB;
        let object_size = 3 * part_size;
        let capacity_bytes = 2 * part_size as usize;
        let (transfer, mut consumer) =
            create_download_for_gate_with_capacity(object_size, part_size, Some(capacity_bytes));

        assert_discovery_succeeds(&transfer).await;
        let pool = transfer.ctx().handle.buffer_pool.clone();
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            0,
            "the completed discovery response has closed acquisition authority"
        );
        assert_eq!(
            pool.metrics().admitted_bytes(),
            part_size,
            "the delivered discovery payload remains charged"
        );

        // The discovery chunk plus one range exactly fill configured capacity.
        let _w1 = assert_ready(transfer.poll_work());
        assert_eq!(pool.metrics().active_planned_demand_bytes(), part_size);
        assert_eq!(pool.metrics().admitted_bytes(), 2 * part_size);

        // Part 2 cannot fit and waits in the memory-admission FIFO, holding
        // the claimed slot in `pending` until a chunk frees.
        assert_pending(transfer.poll_work());
        assert_eq!(pool.metrics().waiting_requests(), 1);
        {
            let state = transfer.inner.state.lock().unwrap();
            match &*state {
                DownloadState::Transferring { pending, .. } => {
                    assert!(pending.is_some(), "claim should be waiting for memory");
                }
                _ => panic!("expected Transferring"),
            }
        }

        // Dropping the discovery chunk returns its carrier. Memory admission
        // grants that capacity directly to the FIFO head.
        drop(consumer.try_take_next().expect("discovery chunk is filled"));
        assert_eq!(
            pool.metrics().admitted_bytes(),
            2 * part_size,
            "freed capacity re-granted to the memory waiter"
        );
        assert_eq!(pool.metrics().waiting_requests(), 0);

        // Poll #3: the waiting claim was granted, so it is ready and no longer pending.
        let _w2 = assert_ready(transfer.poll_work());
        {
            let state = transfer.inner.state.lock().unwrap();
            match &*state {
                DownloadState::Transferring { pending, .. } => {
                    assert!(pending.is_none(), "waiting claim should be consumed");
                }
                _ => panic!("expected Transferring"),
            }
        }
        assert_eq!(pool.metrics().active_planned_demand_bytes(), 2 * part_size);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_memory_reservation_failure_terminates_without_dispatch() {
        let (transfer, _consumer) = create_download_for_gate(3 * 8 * MB, 8 * MB);
        assert_discovery_succeeds(&transfer).await;
        transfer
            .ctx()
            .handle
            .buffer_pool
            .inject_reservation_failure(ReserveError::MetadataAllocationFailed);

        assert_done(transfer.poll_work());
        assert!(transfer.ctx().is_failed());
        assert_eq!(
            transfer.ctx().error_kind(),
            Some(crate::error::ErrorKind::RuntimeError),
        );
        assert!(matches!(
            &*transfer.inner.state.lock().unwrap(),
            DownloadState::Terminal
        ));
    }

    /// A stream-mode transfer blocked on memory must return `Pending`, never a
    /// `DrainResident` work item. The consumer drives stream release, so the
    /// deadlock relief does not apply and must not spin emitting empty drains.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_stream_memory_wait_does_not_emit_drain_resident() {
        // Stream-mode transfer (create_download_for_gate uses new_recv_body). 3 parts.
        let part_size = 8 * MB;
        let object_size = 3 * part_size;
        let (transfer, _consumer) = create_download_for_gate_with_capacity(
            object_size,
            part_size,
            Some(2 * part_size as usize),
        );

        assert_discovery_succeeds(&transfer).await;

        // The completed discovery payload remains charged while part 1 retains
        // open acquisition authority. Part 2 therefore waits for that retained
        // ownership to return.
        let _part_1 = assert_ready(transfer.poll_work());

        // Because this is stream mode, the relief path is off: poll_work
        // returns Pending, not Ready(DrainResident).
        match transfer.poll_work() {
            PollWork::Pending => {}
            PollWork::Spawned => panic!("unexpected Spawned"),
            PollWork::Ready { .. } => {
                panic!("stream-mode memory wait must not emit DrainResident")
            }
            PollWork::Done => panic!("unexpected Done"),
        }
    }

    /// Cancelling a transfer while it is waiting for memory must cancel the queued
    /// reservation future and release the held slot. `on_terminal` owns this
    /// cleanup because external cancellation does not run `fail` or claim completion.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_while_memory_blocked_releases_future_and_slot() {
        let part_size = 8 * MB;
        let object_size = 3 * part_size;
        let (transfer, mut consumer) = create_download_for_gate_with_capacity(
            object_size,
            part_size,
            Some(2 * part_size as usize),
        );

        assert_discovery_succeeds(&transfer).await;
        let pool = transfer.ctx().handle.buffer_pool.clone();

        // Poll 1 issues part 1; poll 2 queues part 2 for memory.
        let _w1 = assert_ready(transfer.poll_work());
        assert_pending(transfer.poll_work());
        assert_eq!(
            pool.metrics().waiting_requests(),
            1,
            "part 2's reservation is queued for memory"
        );

        // Cancel and run the terminal hook, exactly as `cancel_descriptor` does.
        assert!(transfer.ctx().set_cancelled());
        transfer.on_terminal();

        // The waiting PendingClaim was dropped: its future left the queue and its
        // held slot released. The queue is empty, so a freed chunk cannot be misgranted
        // to the dead transfer.
        assert_eq!(
            pool.metrics().waiting_requests(),
            0,
            "cancel must dequeue the memory waiter"
        );

        // No planned demand was granted to the cancelled waiter.
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            part_size,
            "only part 1 retains acquisition authority; the waiter was not granted"
        );
        assert_eq!(
            pool.metrics().admitted_bytes(),
            2 * part_size,
            "the discovery payload and part-1 reservation remain charged"
        );

        // The consumer is woken and sees terminal rather than hanging on seq.
        // (Discovery chunk may still deliver; the point is no deadlock.)
        let _ = consumer.try_take_next();
    }

    /// Discovery awaits memory admission inside `execute`, rather than returning
    /// `Pending` to the scheduler. External cancellation must wake that await,
    /// drop the queued future, and return the worker slot.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_cancel_while_discovery_waits_for_memory_admission() {
        let part_size = 8 * MB;
        let (transfer, _consumer) =
            create_download_for_gate_with_capacity(part_size, part_size, Some(part_size as usize));
        let pool = transfer.ctx().handle.buffer_pool.clone();
        let blocker = pool
            .try_reserve(part_size as usize)
            .unwrap()
            .expect("test blocker");

        let mut work = assert_ready(transfer.poll_work());
        let executing = transfer.clone();
        let task = tokio::spawn(async move { execute(&executing, &mut work).await });

        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            while pool.metrics().waiting_requests() != 1 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("discovery reservation should enter the memory FIFO");

        assert!(transfer.ctx().set_cancelled());
        transfer.on_terminal();

        assert!(matches!(task.await.unwrap(), WorkOutcome::Cancelled));
        assert_eq!(
            pool.metrics().waiting_requests(),
            0,
            "terminal notification must cancel the discovery reservation future"
        );
        drop(blocker);
        assert_eq!(pool.metrics().active_planned_demand_bytes(), 0);
    }

    /// The failure path must release a memory-blocked claim. `enter_terminal`
    /// extracts it under download state, then `fail` drops it after unlocking so
    /// cancellation can safely enter memory admission.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_fail_while_memory_blocked_releases_future_and_slot() {
        let part_size = 8 * MB;
        let object_size = 3 * part_size;
        let (transfer, mut consumer) = create_download_for_gate_with_capacity(
            object_size,
            part_size,
            Some(2 * part_size as usize),
        );

        assert_discovery_succeeds(&transfer).await;
        let pool = transfer.ctx().handle.buffer_pool.clone();

        // Poll 1 issues part 1; poll 2 queues part 2 for memory.
        let _w1 = assert_ready(transfer.poll_work());
        assert_pending(transfer.poll_work());
        assert_eq!(
            pool.metrics().waiting_requests(),
            1,
            "part 2's reservation is queued for memory"
        );

        // Fail the transfer while the claim waits for memory, exactly as
        // `fail_range` does: take the state lock and run the fail transition.
        let err = error::Error::new(error::ErrorKind::RuntimeError, "injected test failure");
        {
            let guard = transfer.inner.state.lock().unwrap();
            let _ = transfer.fail(guard, err);
        }

        // The waiting PendingClaim was dropped by `enter_terminal`.
        assert_eq!(
            pool.metrics().waiting_requests(),
            0,
            "fail must dequeue the memory waiter"
        );
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            part_size,
            "only part 1 retains acquisition authority; the waiter was not granted"
        );
        assert_eq!(
            pool.metrics().admitted_bytes(),
            2 * part_size,
            "the discovery payload and part-1 reservation remain charged"
        );

        let _ = consumer.try_take_next();
    }

    /// A single-chunk disk download must flush its tail and return its carrier
    /// charge from `execute`, not from a later `poll_work`.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_terminal_drain_and_carrier_return_happen_in_execute() {
        let part_size = 8 * MB;
        // Single chunk: object_size == part_size. Discovery fetches the entire object in
        // one chunk; no range requests are generated. The terminal completion path runs
        // when execute_read_discovery_body finishes filling that single chunk.
        let object_size = part_size;

        let chunk = vec![0u8; part_size as usize];
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_output(move || {
            GetObjectOutput::builder()
                .content_length(part_size as i64)
                .content_range(format!("bytes 0-{}/{}", part_size - 1, object_size))
                .e_tag("test-etag")
                .body(ByteStream::from(chunk.clone()))
                .build()
        });
        let client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj]);

        let pool = crate::memory::BufferPool::builder()
            .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                (part_size as usize) as u64,
            )))
            .build()
            .expect("test pool");
        let config = crate::Config::builder()
            .sdk_client(client)
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
            .memory(crate::config::MemoryConfig::Explicit(pool.clone()))
            .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), 1)
            .build()
            .expect("valid config");

        let handle = crate::client::Handle::test_handle_tokio(config);

        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .range(format!("bytes=0-{}", object_size - 1))
            .build()
            .unwrap();

        // Disk-mode body so finalize drains to a file and returns carrier charges.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) =
            crate::operation::download::body::new_recv_body_with_sink(file, false);
        let (ctx, _completion_rx) = TransferContext::new(handle);
        let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer);

        assert_eq!(pool.metrics().active_planned_demand_bytes(), 0);

        // Drive discovery: poll_work returns discovery work, execute fetches it.
        // The discovery chunk is the complete object, so its execute path fills
        // and terminally drains it without another scheduler poll.
        let mut work = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut work).await;

        // The terminal execute must have finalized and returned the carrier
        // charge, all without any subsequent poll_work.
        assert!(
            matches!(outcome, WorkOutcome::Success { .. }),
            "expected Success, got {:?}",
            outcome
        );
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            0,
            "terminal drain + carrier return must happen in execute, not a later poll_work"
        );
        assert!(
            !transfer.ctx().is_active(),
            "transfer must be completed after terminal execute"
        );
        let summary = transfer
            .test_terminal_summary()
            .expect("file summary diagnostics enabled");
        assert_eq!(summary.destination, DownloadDestination::File);
        assert!(summary.destination_work.prepared);
        assert!(summary.destination_work.file_finalized);
        assert_eq!(summary.destination_work.terminal_drain_parts, 1);
        assert_eq!(summary.metrics.disk_write, part_size);

        // Verify data landed on disk.
        let written = std::fs::read(&path).unwrap();
        assert_eq!(
            written.len(),
            part_size as usize,
            "all bytes should be flushed to disk"
        );
    }

    /// `disk_write` counts bytes the destination accepted, not bytes received:
    /// nothing while every filled part is below the drain batch, then the whole
    /// object once the completing range's terminal drain has written it.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn disk_write_counts_bytes_written_not_received() {
        use crate::operation::download::test_util::fixtures::{object_bytes, object_client};

        let part_size = 5 * MB;
        let object = object_bytes(3 * part_size as usize);
        let handle = disk_test_handle(object_client(Arc::clone(&object)), part_size);
        let (transfer, _consumer, dir) = disk_transfer(handle, &FileSinkFactory);
        let path = dir.path().join("out");

        assert_first_range_succeeds(&transfer).await;
        let mut second = assert_ready(transfer.poll_work());
        execute(&transfer, &mut second).await;
        let metrics = transfer.ctx().metrics();
        assert_eq!(metrics.network_rx, 2 * part_size);
        assert_eq!(
            metrics.disk_write, 0,
            "two parts received below the drain batch, none written"
        );
        assert!(std::fs::read(&path).unwrap().is_empty());

        let mut last = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut last).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );
        assert_eq!(transfer.ctx().metrics().disk_write, object.len() as u64);
        assert_eq!(std::fs::read(&path).unwrap(), &object[..]);
    }

    /// A drain that fails part-way still counts the runs it wrote before the
    /// failing one. The failed transfer's terminal drain takes the head run of
    /// each of three receive-buffer segments, and the destination rejects the
    /// third.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn disk_write_counts_runs_written_before_a_drain_fails() {
        use crate::operation::download::recv_buffer::DEFAULT_SEG_SIZE;
        use crate::operation::download::test_util::fixtures::{object_bytes, object_client};
        use crate::operation::download::test_util::sink::{
            Action, Event, Match, Op, ScriptedSinkFactory, WriteScript,
        };

        const RUN_LEN: u64 = 4;
        let script = Arc::new(WriteScript::default()).on(
            Match::NthWrite(3),
            Action::Fail(std::io::ErrorKind::StorageFull),
        );
        let handle = disk_test_handle(object_client(object_bytes(1)), 5 * MB);
        let (transfer, _consumer, dir) =
            disk_transfer(handle, &ScriptedSinkFactory(Arc::clone(&script)));
        let writer = transfer.writer();
        writer.prepare(0, 3 * RUN_LEN).unwrap();

        // Fill only the first slot of each segment, so an eager drain takes three
        // separate runs, in order.
        let seg = DEFAULT_SEG_SIZE as u64;
        for seq in 0..=2 * seg {
            let slot = writer.claim();
            if seq % seg == 0 {
                let run = seq / seg;
                slot.fill(ChunkOutput {
                    seq,
                    offset: run * RUN_LEN,
                    data: SegmentedBytes::from(Bytes::from(vec![run as u8 + 1; RUN_LEN as usize])),
                    metadata: Default::default(),
                });
            }
        }

        let guard = transfer.inner.state.lock().unwrap();
        let outcome = transfer.fail(
            guard,
            error::Error::new(
                error::ErrorKind::IOError,
                std::io::Error::other("range failed"),
            ),
        );
        assert!(matches!(outcome, WorkOutcome::Failed { .. }));

        let third = Op::Write {
            pos: 2 * RUN_LEN,
            len: RUN_LEN as usize,
        };
        assert!(
            script.events().contains(&Event::Finished(
                third,
                Err(std::io::ErrorKind::StorageFull)
            )),
            "the terminal drain reached the third run"
        );
        let disk_write = transfer.ctx().metrics().disk_write;
        assert_eq!(
            disk_write,
            2 * RUN_LEN,
            "the two runs written before the failing one are counted"
        );
        assert_eq!(disk_write, writer.written());
        assert_eq!(
            std::fs::read(dir.path().join("out")).unwrap(),
            [[1u8; RUN_LEN as usize], [2u8; RUN_LEN as usize]].concat()
        );
    }

    /// A finalize that fails its length check still counts the tail its
    /// terminal drain wrote. A drain the transfer does not track holds the
    /// first part's run claimed but unwritten when the final range completes,
    /// so the destination is one part short at finalization.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn disk_write_counts_the_tail_written_by_a_failed_finalize() {
        use crate::operation::download::test_util::fixtures::{object_bytes, object_client};
        use crate::operation::download::test_util::sink::{
            Action, Event, Match, Op, ScriptedSinkFactory, WriteScript,
        };

        const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
        let part_size = 5 * MB;
        let object = object_bytes(2 * part_size as usize);
        let script = Arc::new(WriteScript::default()).on(Match::NthWrite(1), Action::Hold);
        let handle = disk_test_handle(object_client(Arc::clone(&object)), part_size);
        let (transfer, _consumer, _dir) =
            disk_transfer(handle, &ScriptedSinkFactory(Arc::clone(&script)));

        assert_first_range_succeeds(&transfer).await;
        let writer = transfer.writer().clone();
        let untracked = std::thread::spawn(move || writer.drain(DrainMode::Eager));
        let held = script.wait_held(TIMEOUT);
        assert_eq!(
            held.op(),
            Op::Write {
                pos: 0,
                len: part_size as usize
            }
        );

        let mut last = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut last).await;
        assert!(matches!(outcome, WorkOutcome::Failed { .. }));
        let error = transfer
            .ctx()
            .take_error()
            .expect("the failure is reported");
        assert_eq!(error.kind(), &crate::error::ErrorKind::IOError);
        let tail = Op::Write {
            pos: part_size,
            len: part_size as usize,
        };
        assert!(
            script.events().contains(&Event::Finished(tail, Ok(()))),
            "finalization's terminal drain wrote the tail"
        );
        let disk_write = transfer.ctx().metrics().disk_write;
        assert_eq!(disk_write, part_size, "the tail is counted");
        assert_eq!(disk_write, transfer.writer().written());

        held.release();
        untracked.join().unwrap().unwrap();
    }

    /// After a failure, `disk_write` is what the terminal drain wrote: the filled
    /// prefix ahead of the failed range. A part received behind the failed range
    /// is never written and is not counted.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn disk_write_after_failure_counts_only_bytes_written() {
        use crate::operation::download::test_util::fixtures::object_bytes;

        let part_size = 5 * MB;
        let object = object_bytes(3 * part_size as usize);
        let client = object_client_failing_at(Arc::clone(&object), part_size);
        let (transfer, _consumer, dir) =
            disk_transfer(disk_test_handle(client, part_size), &FileSinkFactory);

        assert_first_range_succeeds(&transfer).await;
        let mut failing = assert_ready(transfer.poll_work());
        let mut behind = assert_ready(transfer.poll_work());
        execute(&transfer, &mut behind).await;
        assert_eq!(transfer.ctx().metrics().disk_write, 0);

        let outcome = execute(&transfer, &mut failing).await;
        assert!(matches!(outcome, WorkOutcome::Failed { .. }));
        let metrics = transfer.ctx().metrics();
        assert_eq!(metrics.network_rx, 2 * part_size);
        assert_eq!(
            metrics.disk_write, part_size,
            "only the part ahead of the failed range was written"
        );
        assert_eq!(
            std::fs::read(dir.path().join("out")).unwrap(),
            &object[..part_size as usize]
        );
    }

    /// Accepted range evidence must hash the published bytes, independently of
    /// the SDK's per-response verdict. A later range supplies the remaining
    /// coverage so missing or incorrect evidence from the worker fails finish.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn accepted_range_supplies_frozen_crc_evidence() {
        use crate::operation::download::test_util::fixtures::object_bytes;

        let part_size = 5 * MB;
        let object = object_bytes(2 * part_size as usize);
        let (transfer, _consumer, dir) = disk_transfer(
            disk_test_handle(crc32_object_client(Arc::clone(&object), None), part_size),
            &FileSinkFactory,
        );
        transfer.inner.writer.sync_drain_batch(1);
        assert_first_range_succeeds(&transfer).await;
        let mut integrity = {
            let mut state = transfer.inner.state.lock().unwrap();
            let DownloadState::Transferring { integrity, .. } =
                std::mem::replace(&mut *state, DownloadState::Terminal)
            else {
                panic!("first range must leave the second range outstanding");
            };
            integrity
        };
        let remaining = SegmentedBytes::from(Bytes::copy_from_slice(&object[part_size as usize..]));
        integrity.record(
            RangeCompletion::capture(part_size, &remaining, None, integrity.range_digest_plan())
                .unwrap(),
        );
        assert_eq!(
            integrity.finish().unwrap().checksum_validation(),
            &crate::types::ChecksumValidation::Validated {
                algorithm: crate::types::ChecksumAlgorithm::Crc32,
            },
        );
        assert!(std::fs::read(dir.path().join("out")).unwrap() == object[..part_size as usize]);
    }

    /// SDK-valid ranges cannot bypass a failed stored-object CRC. Verification
    /// must precede the destination's scripted finalize failure and publish no verdict.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn whole_object_mismatch_precedes_destination_finalization() {
        use crate::operation::download::test_util::fixtures::{
            crc32_object_client_with_stored_checksum, object_bytes,
        };
        use crate::operation::download::test_util::sink::{
            Action, Event, Match, Op, ScriptedSinkFactory, WriteScript,
        };

        let part_size = 5 * MB;
        let object = object_bytes(part_size as usize + 37);
        let expected = aws_smithy_types::base64::encode(0u32.to_be_bytes());
        let mut crc = aws_smithy_checksums::ChecksumAlgorithm::Crc32.into_impl();
        crc.update(&object);
        let computed = aws_smithy_types::base64::encode(crc.finalize());
        assert_ne!(expected, computed, "the stored checksum must mismatch");
        let script = Arc::new(WriteScript::default()).on(
            Match::Finalize,
            Action::Fail(std::io::ErrorKind::StorageFull),
        );
        let (transfer, _consumer, _dir) = disk_transfer(
            disk_test_handle(
                crc32_object_client_with_stored_checksum(object, None, expected.clone()),
                part_size,
            ),
            &ScriptedSinkFactory(Arc::clone(&script)),
        );
        assert_first_range_succeeds(&transfer).await;
        let mut last = assert_ready(transfer.poll_work());
        assert!(matches!(
            execute(&transfer, &mut last).await,
            WorkOutcome::Failed { .. }
        ));
        let error = transfer
            .ctx()
            .take_error()
            .expect("failed transfer records its error");
        let error::ErrorKind::IntegrityError(detail) = error.kind() else {
            panic!("whole-object mismatch must win over destination failure: {error:?}");
        };
        assert_eq!(
            detail.algorithm(),
            Some(&crate::types::ChecksumAlgorithm::Crc32)
        );
        assert_eq!(detail.expected(), Some(expected.as_str()));
        assert_eq!(detail.computed(), Some(computed.as_str()));
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Failed
        );
        assert!(transfer.integrity_checks().is_none());
        assert!(!script
            .events()
            .iter()
            .any(|event| matches!(event, Event::Started(Op::Finalize { .. }))));
        assert_done(transfer.poll_work());
    }

    /// Losing one range's calculated evidence is a terminal coverage error,
    /// even though the SDK validated every response. It must not finalize the file.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn missing_whole_object_evidence_prevents_destination_finalization() {
        use crate::operation::download::test_util::fixtures::object_bytes;
        use crate::operation::download::test_util::sink::{
            Event, Op, ScriptedSinkFactory, WriteScript,
        };

        let part_size = 5 * MB;
        let script = Arc::new(WriteScript::default());
        let (transfer, _consumer, _dir) = disk_transfer(
            disk_test_handle(
                crc32_object_client(object_bytes(part_size as usize + 37), None),
                part_size,
            ),
            &ScriptedSinkFactory(Arc::clone(&script)),
        );
        assert_first_range_succeeds(&transfer).await;
        let mut last = assert_ready(transfer.poll_work());
        let DownloadWork::GetObjectRange { digest_plan, .. } = last.data_mut::<DownloadWork>()
        else {
            panic!("last work item must be the second range");
        };
        *digest_plan = RangeDigestPlan::None;
        assert!(matches!(
            execute(&transfer, &mut last).await,
            WorkOutcome::Failed { .. }
        ));
        assert_eq!(
            transfer.ctx().take_error().unwrap().kind(),
            &error::ErrorKind::RuntimeError
        );
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Failed
        );
        assert!(transfer.integrity_checks().is_none());
        assert!(!script
            .events()
            .iter()
            .any(|event| matches!(event, Event::Started(Op::Finalize { .. }))));
        assert_done(transfer.poll_work());
    }

    /// Runs a three-part disk download over `crc32_object_client` whose part
    /// `failing_part` (0-based), if set, fails, and returns the checksum verdict its
    /// terminal report carries.
    async fn crc32_download_terminal_checksum_validation(
        failing_part: Option<u64>,
    ) -> Option<crate::types::ChecksumValidation> {
        use crate::operation::download::test_util::fixtures::object_bytes;

        let part_size = 5 * MB;
        let object = object_bytes(3 * part_size as usize);
        let config = crate::Config::builder()
            .sdk_client(crc32_object_client(
                object,
                failing_part.map(|n| n * part_size),
            ))
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
            .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), 1)
            .build()
            .expect("valid config");
        let (transfer, _consumer, _dir) = disk_transfer(
            crate::client::Handle::test_handle_tokio(config),
            &FileSinkFactory,
        );

        assert_first_range_succeeds(&transfer).await;
        let mut second = assert_ready(transfer.poll_work());
        let mut third = assert_ready(transfer.poll_work());
        let outcome = execute(&transfer, &mut second).await;
        assert!(
            matches!(outcome, WorkOutcome::Success { .. }),
            "{outcome:?}"
        );
        let outcome = execute(&transfer, &mut third).await;
        assert_eq!(
            matches!(outcome, WorkOutcome::Failed { .. }),
            failing_part.is_some(),
            "{outcome:?}"
        );

        transfer
            .test_terminal_summary()
            .expect("summary diagnostics enabled")
            .checksum_validation
    }

    /// A download whose third part fails after its first two validated reports no
    /// checksum verdict: the verdict is decided only when a download completes.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn failed_download_reports_no_checksum_verdict() {
        assert_eq!(
            crc32_download_terminal_checksum_validation(Some(2)).await,
            None
        );
    }

    /// The same download with no failing part completes, and its terminal report
    /// carries `Validated{Crc32}`, so the parts the failed download delivered were
    /// validated.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn completed_download_reports_checksum_verdict() {
        assert_eq!(
            crc32_download_terminal_checksum_validation(None).await,
            Some(crate::types::ChecksumValidation::Validated {
                algorithm: crate::model::ChecksumAlgorithm::Crc32,
            })
        );
    }

    /// How long a test waits for a scripted hold to start.
    const HOLD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

    /// The checksum verdict `transfer` has published, if any.
    fn published_verdict(transfer: &DownloadTransfer) -> Option<&crate::types::ChecksumValidation> {
        transfer
            .integrity_checks()
            .map(crate::types::IntegrityChecks::checksum_validation)
    }

    /// The verdict of a download whose every part carried a matching CRC32.
    fn validated_crc32() -> crate::types::ChecksumValidation {
        crate::types::ChecksumValidation::Validated {
            algorithm: crate::model::ChecksumAlgorithm::Crc32,
        }
    }

    /// The final range completing while a memory-relief write is still landing does
    /// not complete the transfer: finalization cannot see the run that write
    /// claimed. The relief write completes the transfer when it finishes, and the
    /// destination then holds the whole object.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn final_range_waits_for_an_in_flight_relief_write() {
        use crate::operation::download::test_util::sink::{Action, Match, Op, WriteScript};

        let script = Arc::new(WriteScript::default()).on(Match::NthWrite(1), Action::Hold);
        let scenario = relief_scenario(&script).await;
        let (transfer, path, object) = (&scenario.transfer, &scenario.path, &scenario.object);

        let relief = spawn_relief(transfer, scenario.relief);
        let held = script.wait_held(HOLD_TIMEOUT);
        assert_eq!(
            held.op(),
            Op::Write {
                pos: 0,
                len: scenario.part_size as usize
            }
        );

        // Memory freed outside the transfer admits the final range while the relief
        // write still holds the first part.
        drop(scenario.blocker);
        let mut last = assert_ready(transfer.poll_work());
        let outcome = execute(transfer, &mut last).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));

        assert!(
            transfer.ctx().is_active(),
            "the transfer completed while a destination write was in flight"
        );
        assert_eq!(published_verdict(transfer), None);
        assert_pending(transfer.poll_work());
        assert_eq!(
            std::fs::metadata(path).unwrap().len(),
            0,
            "the destination was resized while a destination write was in flight"
        );
        assert!(!finalize_started(&script.events()));

        held.release();
        let outcome = relief.join().unwrap();
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );
        assert_eq!(published_verdict(transfer), Some(&validated_crc32()));
        assert_eq!(std::fs::read(path).unwrap(), &object[..]);
        assert_eq!(transfer.ctx().metrics().disk_write, object.len() as u64);
        assert_done(transfer.poll_work());
    }

    /// A memory-relief write that fails after every range has completed fails the
    /// transfer instead of being discarded behind a completion.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn failed_relief_write_after_final_range_fails_the_transfer() {
        use crate::operation::download::test_util::sink::{Action, Match, WriteScript};

        let script = Arc::new(WriteScript::default()).on(Match::NthWrite(1), Action::Hold);
        let scenario = relief_scenario(&script).await;
        let transfer = &scenario.transfer;

        let relief = spawn_relief(transfer, scenario.relief);
        let held = script.wait_held(HOLD_TIMEOUT);
        drop(scenario.blocker);
        let mut last = assert_ready(transfer.poll_work());
        execute(transfer, &mut last).await;
        assert!(transfer.ctx().is_active());

        held.release_err(std::io::ErrorKind::StorageFull);
        let outcome = relief.join().unwrap();
        assert!(matches!(outcome, WorkOutcome::Failed { .. }));
        assert!(transfer.ctx().is_failed());
        let error = transfer
            .ctx()
            .take_error()
            .expect("the failure is reported");
        assert_eq!(error.kind(), &crate::error::ErrorKind::IOError);
        assert_eq!(published_verdict(transfer), None);
        assert!(
            !finalize_started(&script.events()),
            "a failed transfer must not finalize its destination"
        );
        assert_eq!(
            transfer.ctx().metrics().disk_write,
            scenario.part_size,
            "only the final part, written by the terminal drain, reached the destination"
        );
    }

    /// A relief item that starts after the transfer went terminal writes nothing.
    /// The terminal drain already took the resident run.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn relief_after_terminal_transition_writes_nothing() {
        use crate::operation::download::test_util::sink::WriteScript;

        let script = Arc::new(WriteScript::default());
        let scenario = relief_scenario(&script).await;
        let transfer = &scenario.transfer;

        assert!(transfer.ctx().set_cancelled());
        transfer.on_terminal();
        let events = script.events();

        let outcome = spawn_relief(transfer, scenario.relief).join().unwrap();
        assert!(matches!(outcome, WorkOutcome::Cancelled));
        assert_eq!(script.events(), events, "a moot relief item must not write");
    }

    /// A poll of a memory-blocked transfer whose relief item is queued parks
    /// instead of issuing a second relief item for the same resident run.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn memory_blocked_poll_with_a_queued_relief_item_parks() {
        use crate::operation::download::test_util::sink::{Event, Op, WriteScript};

        let script = Arc::new(WriteScript::default());
        let mut scenario = relief_scenario(&script).await;
        let transfer = &scenario.transfer;
        assert!(
            transfer.writer().has_drainable_resident(),
            "the queued item has not drained the first part yet"
        );

        assert_pending(transfer.poll_work());

        let outcome = execute(transfer, &mut scenario.relief).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        let first_part = Op::Write {
            pos: 0,
            len: scenario.part_size as usize,
        };
        assert_eq!(
            script.events(),
            [
                Event::Started(first_part),
                Event::Finished(first_part, Ok(()))
            ],
            "one relief item drained the resident run"
        );
    }

    /// The final range completing while a relief item is queued does not complete
    /// the transfer, since the item has yet to claim and write the run it
    /// relieves. The relief item completes the transfer when it finishes.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn final_range_waits_for_a_queued_relief_item() {
        use crate::operation::download::test_util::sink::WriteScript;

        let script = Arc::new(WriteScript::default());
        let mut scenario = relief_scenario(&script).await;
        let transfer = &scenario.transfer;

        drop(scenario.blocker);
        let mut last = assert_ready(transfer.poll_work());
        let outcome = execute(transfer, &mut last).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        assert!(
            transfer.ctx().is_active(),
            "the transfer completed while a relief item was queued"
        );
        assert_eq!(published_verdict(transfer), None);
        assert_pending(transfer.poll_work());
        assert!(!finalize_started(&script.events()));

        let outcome = execute(transfer, &mut scenario.relief).await;
        assert!(matches!(outcome, WorkOutcome::Success { .. }));
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );
        assert_eq!(published_verdict(transfer), Some(&validated_crc32()));
        assert_eq!(std::fs::read(&scenario.path).unwrap(), &scenario.object[..]);
        assert_done(transfer.poll_work());
    }

    /// Result of [`write_to_path_with_held_relief_write`].
    struct HeldReliefDownload {
        result: Result<crate::operation::download::DownloadOutput, crate::error::Error>,
        object: std::sync::Arc<[u8]>,
        dest: std::path::PathBuf,
        dir: tempfile::TempDir,
    }

    /// Runs a path download of a two-part object, orchestrated as
    /// `write_to_path` does, on the managed runtime with the first destination
    /// write held.
    ///
    /// The memory budget fits two parts and a reservation outside the transfer
    /// holds one, so the second part's claim waits on memory and the first
    /// destination write is the memory relief for the discovery part. Once that
    /// write is held, the reservation is dropped so the final range is received.
    /// `join` must then stay pending for 200 ms without publishing the
    /// destination. The held write is then released, failing with
    /// `release_err` if given.
    ///
    /// A concurrency target of 2 lets the final range dispatch while the held
    /// write occupies one slot, and keeps it off the held write's thread.
    /// Relief is issued one item at a time, so the held write is the only
    /// relief item, and the final range gets the second slot only once
    /// discovery has finished. The held write's thread is then the only loaded
    /// one, and routing, which picks the less loaded of two threads, picks
    /// another. With one detected partition, the final range instead waits
    /// for the held write to be released.
    async fn write_to_path_with_held_relief_write(
        release_err: Option<std::io::ErrorKind>,
        max_partitions: usize,
    ) -> HeldReliefDownload {
        use crate::operation::download::test_util::fixtures::{
            managed_test_handle_with_max_partitions, object_bytes,
        };
        use crate::operation::download::test_util::sink::{
            Action, Match, Op, ScriptedSinkFactory, WriteScript,
        };
        use crate::operation::download::Download;
        use std::sync::Arc;
        use std::time::Duration;

        const TIMEOUT: Duration = Duration::from_secs(5);
        let part_size = 8 * 1024 * 1024;
        let object = object_bytes(2 * part_size);
        let pool = crate::memory::BufferPool::builder()
            .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                2 * part_size as u64,
            )))
            .build()
            .expect("test pool");
        let blocker = pool
            .try_reserve(part_size)
            .unwrap()
            .expect("the budget fits the blocker");
        let script = Arc::new(WriteScript::default()).on(Match::NthWrite(1), Action::Hold);
        let config = crate::Config::builder()
            .sdk_client(crc32_object_client(Arc::clone(&object), None))
            .part_size(crate::config::PartSize::Target(ByteSize::new(
                part_size as u64,
            )))
            .memory(crate::config::MemoryConfig::Explicit(pool))
            .build()
            .expect("valid config");
        let (handle, partition_count) =
            managed_test_handle_with_max_partitions(config, 2, max_partitions);
        let input = DownloadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .build()
            .unwrap();
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("object");

        let download = Download::orchestrate_to_path(
            Arc::clone(&handle),
            input,
            dest.clone(),
            None,
            &ScriptedSinkFactory(Arc::clone(&script)),
        )
        .await
        .unwrap();

        let held = tokio::task::spawn_blocking({
            let script = Arc::clone(&script);
            move || script.wait_held(TIMEOUT)
        })
        .await
        .unwrap();
        assert_eq!(
            held.op(),
            Op::Write {
                pos: 0,
                len: part_size
            }
        );

        drop(blocker);
        if partition_count > 1 {
            tokio::time::timeout(TIMEOUT, async {
                while download.metrics().network_rx < 2 * part_size as u64 {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            })
            .await
            .expect("the final range is received while the relief write is held");
        }
        // On one partition, the held synchronous write also holds the only
        // managed thread. Join must still wait and publication must still wait;
        // the final range can run after that write is released.

        let join = tokio::spawn(download.join());
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert!(
            !join.is_finished(),
            "join returned while a destination write was in flight"
        );
        assert!(
            !dest.exists(),
            "the destination was published while a destination write was in flight"
        );

        match release_err {
            None => held.release(),
            Some(kind) => held.release_err(kind),
        }
        let result = tokio::time::timeout(TIMEOUT, join)
            .await
            .expect("join returns once the write is released")
            .unwrap();
        crate::runtime::test_util::shutdown(&handle).await;
        HeldReliefDownload {
            result,
            object,
            dest,
            dir,
        }
    }

    /// `join` waits for an in-flight memory-relief write, then publishes the
    /// complete object and its verdict.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn write_to_path_join_waits_for_a_held_relief_write() {
        let download = write_to_path_with_held_relief_write(None, 4).await;
        let output = download.result.expect("the download succeeds");
        assert_eq!(std::fs::read(&download.dest).unwrap(), &download.object[..]);
        assert_eq!(
            output.integrity_checks().checksum_validation(),
            &validated_crc32()
        );
    }

    /// A memory-relief write that fails after the final range was received fails
    /// `join` with an I/O error and leaves no destination or temporary file.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn write_to_path_fails_without_publishing_when_a_relief_write_fails() {
        let download =
            write_to_path_with_held_relief_write(Some(std::io::ErrorKind::StorageFull), 4).await;
        let error = download.result.expect_err("the relief write failed");
        assert_eq!(error.kind(), &crate::error::ErrorKind::IOError);
        assert!(
            !download.dest.exists(),
            "a failed download must not publish"
        );
        assert_eq!(
            std::fs::read_dir(download.dir.path()).unwrap().count(),
            0,
            "the temporary file must be removed"
        );
    }

    /// Holding the only managed partition must not publish early, and an I/O
    /// failure must still leave neither a destination nor a temporary file.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn held_relief_write_on_one_partition_preserves_completion_and_cleanup() {
        let download = write_to_path_with_held_relief_write(None, 1).await;
        let output = download
            .result
            .expect("download succeeds after the write is released");
        assert_eq!(std::fs::read(&download.dest).unwrap(), &download.object[..]);
        assert_eq!(
            output.integrity_checks().checksum_validation(),
            &validated_crc32()
        );

        let download =
            write_to_path_with_held_relief_write(Some(std::io::ErrorKind::StorageFull), 1).await;
        assert_eq!(
            download.result.unwrap_err().kind(),
            &crate::error::ErrorKind::IOError
        );
        assert!(!download.dest.exists());
        assert_eq!(std::fs::read_dir(download.dir.path()).unwrap().count(), 0);
    }

    /// A failure after the transfer completed panics in debug builds. The case
    /// is unreachable in practice, since completion is claimed only once every
    /// counted work item has finished. The test reaches it by construction,
    /// calling `fail` directly on a completed single-part download.
    #[cfg(debug_assertions)]
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    #[should_panic(expected = "download failed after it had completed")]
    async fn failure_after_completion_panics_in_debug_builds() {
        // A single-part object: discovery receives it whole and completes.
        let transfer = create_download(8 * MB, 8 * MB);
        assert_first_range_succeeds(&transfer).await;
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );

        let guard = transfer.inner.state.lock().unwrap();
        let _ = transfer.fail(
            guard,
            error::Error::new(
                error::ErrorKind::IOError,
                std::io::Error::other("late destination failure"),
            ),
        );
    }

    /// In release builds, a failure after the transfer completed leaves it
    /// completed and is logged at error level with its cause. The case is
    /// unreachable in practice, since completion is claimed only once every
    /// counted work item has finished. The test reaches it by construction,
    /// calling `fail` directly on a completed single-part download.
    #[cfg(not(debug_assertions))]
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn failure_after_completion_is_logged_in_release_builds() {
        use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;

        // A single-part object: discovery receives it whole and completes.
        let transfer = create_download(8 * MB, 8 * MB);
        assert_first_range_succeeds(&transfer).await;
        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );

        let (_guard, logs) = capture_test_logs();
        let guard = transfer.inner.state.lock().unwrap();
        let _ = transfer.fail(
            guard,
            error::Error::new(
                error::ErrorKind::IOError,
                std::io::Error::other("late destination failure"),
            ),
        );

        assert_eq!(
            transfer.ctx().transfer_status(),
            crate::types::TransferStatus::Completed
        );
        let logs = logs.contents();
        let logged = |level: &str, message: &str| {
            logs.lines().any(|line| {
                line.contains(level)
                    && line.contains(message)
                    && line.contains("late destination failure")
            })
        };
        assert!(logged("DEBUG", "download failed"), "{logs}");
        assert!(
            logged("ERROR", "download failed after it had completed"),
            "{logs}"
        );
    }

    /// Drive several transfers under one shared memory budget by round-robin
    /// poll+execute, standing in for the scheduler's generate_work loop. Returns once
    /// every transfer is `Done`. A bounded step budget converts a genuine deadlock into
    /// a test failure (all transfers `Pending` with no progress) rather than a hang.
    #[cfg(test)]
    async fn drive_to_completion(transfers: &[&DownloadTransfer]) {
        let mut done = vec![false; transfers.len()];
        // Generous ceiling: each transfer needs O(parts) poll+execute steps, plus drain
        // relief steps. Far above any real count here; exceeding it means no progress.
        let max_steps = 10_000;
        for _ in 0..max_steps {
            if done.iter().all(|d| *d) {
                return;
            }
            let mut progressed = false;
            for (i, t) in transfers.iter().enumerate() {
                if done[i] {
                    continue;
                }
                match t.poll_work() {
                    PollWork::Ready { io: mut work, .. } => {
                        execute(t, &mut work).await;
                        progressed = true;
                    }
                    PollWork::Done => {
                        done[i] = true;
                        progressed = true;
                    }
                    PollWork::Spawned => {
                        progressed = true;
                    }
                    PollWork::Pending => {}
                }
            }
            if !progressed {
                panic!(
                    "no transfer made progress: all Pending with work outstanding \
                     (memory-admission deadlock regressed)"
                );
            }
        }
        panic!("drive_to_completion exceeded {max_steps} steps without completing");
    }

    /// REGRESSION (PR #154 review, landonxjames): the shared-admission deadlock for
    /// concurrent multi-part disk transfers below the drain batch must NOT wedge.
    ///
    /// Before the fix: a disk chunk's charge returned only on a drain (fires at the
    /// batch `min(SEG_SIZE=16, window)` or a full segment) or the terminal finalize. A
    /// multi-part object below a segment (2..15 parts) held ALL parts resident until
    /// terminal, which needs every part issued and therefore memory admission. Spread across
    /// concurrent transfers under tight shared admission, none could reach its part
    /// count, so none finalized, drained, or returned its carrier.
    ///
    /// The fix (`DownloadWork::DrainResident`): a transfer about to
    /// wait for memory while holding a resident run flushes it first, returning
    /// carriers for the FIFO. This test drives two 2-part transfers on a
    /// 2-part memory budget to completion.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_concurrent_multipart_disk_below_drain_batch_completes() {
        let part_size = 8 * MB;
        let object_size = 2 * part_size; // 2 parts, below the 16-part drain batch

        // Range-echoing mock: the content-range must match the requested range or
        // execute_get_range fails validation. (Fixed body works only for single-chunk.)
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_compute_response(move |req| {
            let start = req
                .range()
                .and_then(|r| r.parse::<crate::http::header::Range>().ok())
                .map(|r| match r.0 {
                    crate::http::header::ByteRange::Inclusive(s, _) => s,
                    crate::http::header::ByteRange::AllFrom(s) => s,
                    _ => 0,
                })
                .unwrap_or(0);
            let end = std::cmp::min(start + part_size, object_size) - 1;
            let chunk = vec![0u8; (end - start + 1) as usize];
            aws_smithy_mocks::MockResponse::Output(
                GetObjectOutput::builder()
                    .content_length((end - start + 1) as i64)
                    .content_range(format!("bytes {}-{}/{}", start, end, object_size))
                    .e_tag("test-etag")
                    .body(ByteStream::from(chunk))
                    .build(),
            )
        });
        let pool = crate::memory::BufferPool::builder()
            .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                2 * part_size,
            )))
            .build()
            .expect("test pool");
        let config = crate::Config::builder()
            .sdk_client(mock_client!(
                aws_sdk_s3,
                RuleMode::MatchAny,
                &[head_rule(object_size), get_obj]
            ))
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
            .memory(crate::config::MemoryConfig::Explicit(pool.clone()))
            .build()
            .expect("valid config");
        let handle = crate::client::Handle::test_handle_tokio(config);

        let (a, _ca, _da) = disk_transfer(handle.clone(), &FileSinkFactory);
        let (b, _cb, _db) = disk_transfer(handle.clone(), &FileSinkFactory);

        // Pre-fix this wedges: both retain an undrainable resident seq-0 while
        // queued for part 1. Post-fix each flushes its resident run before waiting,
        // so both complete under the 2-part memory budget.
        drive_to_completion(&[&a, &b]).await;

        assert!(!a.ctx().is_active(), "transfer A completed");
        assert!(!b.ctx().is_active(), "transfer B completed");
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            0,
            "all reservations released after both transfers complete"
        );
        assert_eq!(
            pool.metrics().waiting_requests(),
            0,
            "no memory waiters remain"
        );
    }

    /// REGRESSION (PR #154 review generalization, aajtodd): the admission deadlock is
    /// NOT specific to small objects (`total_parts < batch`). It is the general
    /// "wait while holding undrained resident parts" wedge, reachable with LARGE multipart
    /// objects that are nowhere near terminal.
    ///
    /// Two transfers, each a 20-part object (far above the 16-part drain batch, so the
    /// small-object predicate `total_parts < batch` does NOT apply). Drive each to hold
    /// 3 filled-undrained resident parts (3 < 16, so no non-terminal drain), then let a
    /// tight shared memory budget cap them mid-stream with 17 parts still remaining. Neither
    /// can issue (budget full), drain (below batch), or reach terminal (`remaining` far
    /// from done). Each is waiting on the other to release, and neither can — the exact
    /// wedge, with objects an order of magnitude larger than the drain batch.
    ///
    /// Drives both to completion under the tight memory budget: pre-fix this wedges (caught by
    /// `drive_to_completion`'s no-progress panic), post-fix the `DrainResident` relief
    /// lets both finish. Proves the fix is not the small-object special case.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_concurrent_large_multipart_partial_fills_complete() {
        let part_size = 8 * MB;
        let parts_per_object = 20u64; // WELL above the 16-part drain batch
        let object_size = parts_per_object * part_size;
        let resident_per_transfer = 3u64; // 3 < 16: never drains non-terminally

        // Range-echoing mock: each GET's content-range must match the requested range,
        // or execute_get_range's validate_content_range fails the transfer. (A fixed
        // `then_output` body works only for single-chunk objects.)
        let get_obj = mock!(aws_sdk_s3::Client::get_object).then_compute_response(move |req| {
            let start = req
                .range()
                .and_then(|r| r.parse::<crate::http::header::Range>().ok())
                .map(|r| match r.0 {
                    crate::http::header::ByteRange::Inclusive(s, _) => s,
                    crate::http::header::ByteRange::AllFrom(s) => s,
                    _ => 0,
                })
                .unwrap_or(0);
            let end = std::cmp::min(start + part_size, object_size) - 1;
            let chunk = vec![0u8; (end - start + 1) as usize];
            aws_smithy_mocks::MockResponse::Output(
                GetObjectOutput::builder()
                    .content_length((end - start + 1) as i64)
                    .content_range(format!("bytes {}-{}/{}", start, end, object_size))
                    .e_tag("test-etag")
                    .body(ByteStream::from(chunk))
                    .build(),
            )
        });
        let capacity_bytes = (2 * resident_per_transfer * part_size) as usize;
        let pool = crate::memory::BufferPool::builder()
            .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                capacity_bytes as u64,
            )))
            .build()
            .expect("test pool");
        let config = crate::Config::builder()
            .sdk_client(mock_client!(
                aws_sdk_s3,
                RuleMode::MatchAny,
                &[head_rule(object_size), get_obj]
            ))
            .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
            .memory(crate::config::MemoryConfig::Explicit(pool.clone()))
            .build()
            .expect("valid config");
        let handle = crate::client::Handle::test_handle_tokio(config);

        let (a, _ca, _da) = disk_transfer(handle.clone(), &FileSinkFactory);
        let (b, _cb, _db) = disk_transfer(handle.clone(), &FileSinkFactory);

        // Memory budget for exactly the resident parts of both transfers, nothing more.
        // Once both fill to that depth neither can reserve another part without a drain.

        // Drive each transfer to hold `resident_per_transfer` filled-undrained parts:
        // discovery fills seq 0, then (resident-1) range GETs fill seqs 1.. . Each fill's
        // in-execute Batched drain frees nothing (below batch), so all stay resident.
        async fn fill_resident(t: &DownloadTransfer, resident: u64) {
            assert_first_range_succeeds(t).await; // seq 0 filled + reserved
            for _ in 1..resident {
                let mut w = assert_ready(t.poll_work());
                execute(t, &mut w).await;
            }
        }
        fill_resident(&a, resident_per_transfer).await;
        fill_resident(&b, resident_per_transfer).await;

        assert_eq!(
            pool.metrics().admitted_bytes(),
            capacity_bytes as u64,
            "both transfers hold charged resident parts; memory budget is exactly full"
        );

        // Both are mid-stream (17 parts each remaining) with the budget full. Pre-fix
        // this wedges — neither can issue, drain (below batch), or reach terminal, and
        // each waits on the other. Post-fix each flushes its resident run before waiting,
        // so both complete under the tight budget. `drive_to_completion` panics on a
        // no-progress wedge instead of hanging.
        drive_to_completion(&[&a, &b]).await;

        assert!(!a.ctx().is_active(), "large-object transfer A completed");
        assert!(!b.ctx().is_active(), "large-object transfer B completed");
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            0,
            "all reservations released after both large multipart transfers complete"
        );
        assert_eq!(
            pool.metrics().waiting_requests(),
            0,
            "no memory waiters remain"
        );
    }

    /// The window resolved at construction follows precedence: a per-request
    /// `read_ahead` override wins; absent one, the client default applies.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_read_ahead_resolution_precedence() {
        use crate::config::ReadAhead;

        let build = |client_mode: ReadAhead, input_override: Option<ReadAhead>| {
            let get_obj = mock!(aws_sdk_s3::Client::get_object).then_output(|| {
                GetObjectOutput::builder()
                    .content_length(8 * MB as i64)
                    .content_range(format!("bytes 0-{}/{}", 8 * MB - 1, 8 * MB))
                    .e_tag("test-etag")
                    .body(ByteStream::from(vec![0u8; 8 * MB as usize]))
                    .build()
            });
            let config = crate::Config::builder()
                .sdk_client(mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj]))
                .part_size(crate::config::PartSize::Target(ByteSize::new(8 * MB)))
                .read_ahead(client_mode)
                .build()
                .expect("valid config");
            let handle = crate::client::Handle::test_handle_tokio(config);
            let input = DownloadInput::builder()
                .bucket("test-bucket")
                .key("test-key")
                .set_read_ahead(input_override)
                .build()
                .unwrap();
            let (writer, _consumer) = crate::operation::download::body::new_recv_body();
            let (ctx, _rx) = TransferContext::new(handle);
            DownloadTransfer::new(ctx, BucketType::Standard, input, writer)
        };

        // No request override: the client default resolves.
        let t = build(ReadAhead::Parts(9), None);
        assert_eq!(t.read_ahead().window(), 10, "client default applies");

        // Request override wins over the client default.
        let t = build(ReadAhead::Parts(9), Some(ReadAhead::Parts(3)));
        assert_eq!(t.read_ahead().window(), 4, "request override wins");

        // Client Auto resolves to the fixed default when not overridden.
        let t = build(ReadAhead::Auto, None);
        assert_eq!(
            t.read_ahead().window(),
            super::super::read_ahead::DEFAULT_WINDOW_PARTS
        );
    }

    /// `io_ctl().set_read_ahead` resolves the public knob to a window and applies it
    /// to the running transfer; the gate observes the new value on the next poll.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_io_ctl_set_read_ahead_resizes_window() {
        let (transfer, _consumer) = create_download_for_gate(128 * MB, 8 * MB);
        assert_first_range_succeeds(&transfer).await;

        // Parts(n) resolves to n + 1 (n speculative parts plus the demand part).
        transfer
            .io_ctl()
            .set_read_ahead(crate::config::ReadAhead::Parts(4));
        assert_eq!(transfer.read_ahead().window(), 5);

        // Parts(0) is demand paging: a window of exactly one outstanding part.
        transfer
            .io_ctl()
            .set_read_ahead(crate::config::ReadAhead::Parts(0));
        assert_eq!(transfer.read_ahead().window(), 1);

        // Auto returns to the default fixed window.
        transfer
            .io_ctl()
            .set_read_ahead(crate::config::ReadAhead::Auto);
        assert_eq!(
            transfer.read_ahead().window(),
            super::super::read_ahead::DEFAULT_WINDOW_PARTS
        );
    }

    use crate::http::header::Range;
    use aws_smithy_mocks::MockResponse;
    use aws_smithy_runtime::test_util::capture_test_logs::show_test_logs;
    use aws_smithy_runtime_api::http::{Response, StatusCode};
    use aws_smithy_types::body::SdkBody;
    use std::collections::HashMap;

    /// Failure behavior for a specific seq
    #[derive(Clone)]
    enum FailureBehavior {
        /// Always fail
        Always,
        /// Fail first N attempts, then succeed
        #[allow(dead_code)] // TODO: re-enable with retry tests
        Times(usize),
    }

    /// Builder for downloads with configurable failure injection
    struct FailureConfig {
        object_size: u64,
        part_size: u64,
        failures: HashMap<u64, FailureBehavior>,
        detail: u64,
    }

    impl FailureConfig {
        fn new(object_size: u64, part_size: u64) -> Self {
            Self {
                object_size,
                part_size,
                failures: HashMap::new(),
                detail: 0,
            }
        }

        /// Fail this seq always (retryable 500 error)
        fn fail(mut self, seq: u64) -> Self {
            self.failures.insert(seq, FailureBehavior::Always);
            self
        }

        fn detail(mut self, detail: u64) -> Self {
            self.detail = detail;
            self
        }

        fn build(self) -> DownloadTransfer {
            let object_size = self.object_size;
            let part_size = self.part_size;
            let detail = self.detail;
            let failures = Arc::new(self.failures);
            let call_counts: Arc<std::sync::Mutex<HashMap<u64, usize>>> =
                Arc::new(std::sync::Mutex::new(HashMap::new()));

            let get_obj = mock!(aws_sdk_s3::Client::get_object).then_compute_response(move |req| {
                let seq = req
                    .range()
                    .and_then(|r| r.parse::<Range>().ok())
                    .map(|r| match r.0 {
                        crate::http::header::ByteRange::Inclusive(start, _) => start / part_size,
                        crate::http::header::ByteRange::AllFrom(start) => start / part_size,
                        _ => 0,
                    })
                    .unwrap_or(0);

                // Track calls per seq
                let mut counts = call_counts.lock().unwrap();
                let call_num = *counts.entry(seq).and_modify(|c| *c += 1).or_insert(1);
                drop(counts);

                // Check failure config
                let should_fail = match failures.get(&seq) {
                    Some(FailureBehavior::Always) => true,
                    Some(FailureBehavior::Times(n)) => call_num <= *n,
                    None => false,
                };

                if should_fail {
                    MockResponse::Http(Response::new(
                        StatusCode::try_from(500).unwrap(),
                        SdkBody::from("internal error"),
                    ))
                } else {
                    let start = seq * part_size;
                    let end = std::cmp::min(start + part_size, object_size) - 1;
                    let chunk = vec![0u8; (end - start + 1) as usize];

                    MockResponse::Output(
                        GetObjectOutput::builder()
                            .content_length((end - start + 1) as i64)
                            .content_range(format!("bytes {}-{}/{}", start, end, object_size))
                            .e_tag("test-etag")
                            .body(ByteStream::from(chunk))
                            .build(),
                    )
                }
            });

            create_get_first_download_with_client_and_detail(
                mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[get_obj], |conf| {
                    conf.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
                }),
                part_size,
                detail,
                Some(object_size),
            )
        }
    }

    #[test]
    fn test_validate_content_range_success() {
        assert!(validate_content_range(
            "bytes=1024-2047",
            Some("bytes 1024-2047/4096"),
            None,
            None
        )
        .is_ok());
        assert!(
            validate_content_range("1024-2047", Some("bytes 1024-2047/4096"), None, None).is_ok()
        );
    }

    #[test]
    fn test_validate_content_range_mismatch() {
        assert!(validate_content_range(
            "bytes=1024-2047",
            Some("bytes 2048-3071/4096"),
            None,
            None
        )
        .is_err());
    }

    #[test]
    fn test_validate_content_range_missing() {
        assert!(validate_content_range("bytes=1024-2047", None, None, None).is_err());
    }

    #[test]
    fn test_validate_content_range_substring_false_positive() {
        // The substring "0-9" appears in "bytes 10-99/100", but the ranges differ.
        // A naive `.contains()` match would wrongly pass this.
        assert!(validate_content_range("bytes=0-9", Some("bytes 10-99/100"), None, None).is_err());
    }

    #[test]
    fn test_validate_content_range_exact_match_small_range() {
        assert!(validate_content_range("bytes=0-9", Some("bytes 0-9/100"), None, None).is_ok());
    }

    #[test]
    fn test_validate_content_range_unsized_total() {
        // RFC 7233 allows `bytes START-END/*` when the total is unknown.
        assert!(validate_content_range("bytes=0-9", Some("bytes 0-9/*"), None, None).is_ok());
    }

    #[test]
    fn test_validate_content_range_large_range_match() {
        assert!(
            validate_content_range("bytes=100-199", Some("bytes 100-199/500"), None, None).is_ok()
        );
    }

    #[test]
    fn test_validate_content_range_response_none() {
        assert!(validate_content_range("bytes=0-9", None, None, None).is_err());
    }

    /// A server that ignores Range may answer a request for the whole object with the
    /// complete object and no Content-Range. Only a whole-object request whose response
    /// length is the object's length is accepted.
    #[test]
    fn test_validate_content_range_complete_response_without_content_range() {
        assert!(validate_content_range("bytes=0-4", None, Some(5), Some(5)).is_ok());
        // Part of the object, even if the response length matches the request.
        assert!(validate_content_range("bytes=0-4", None, Some(5), Some(10)).is_err());
        assert!(validate_content_range("bytes=5-9", None, Some(10), Some(10)).is_err());
        // The whole object, but the response length is wrong or missing.
        assert!(validate_content_range("bytes=0-4", None, Some(4), Some(5)).is_err());
        assert!(validate_content_range("bytes=0-4", None, None, Some(5)).is_err());
        // The object length is unknown.
        assert!(validate_content_range("bytes=0-4", None, Some(5), None).is_err());
        // A Content-Range that is present must still match.
        assert!(validate_content_range("bytes=0-4", Some("bytes abc"), Some(5), Some(5)).is_err());
    }

    #[test]
    fn test_validate_content_range_garbage_response() {
        assert!(validate_content_range("bytes=0-9", Some("bytes abc"), None, None).is_err());
    }

    #[test]
    fn test_parse_byte_range_request_format() {
        assert_eq!(parse_byte_range("bytes=0-9"), Some((0, 9)));
        assert_eq!(parse_byte_range("bytes=100-199"), Some((100, 199)));
    }

    #[test]
    fn test_parse_byte_range_response_format() {
        assert_eq!(parse_byte_range("bytes 0-9/100"), Some((0, 9)));
        assert_eq!(parse_byte_range("bytes 100-199/500"), Some((100, 199)));
        assert_eq!(parse_byte_range("bytes 0-9/*"), Some((0, 9)));
    }

    #[test]
    fn test_parse_byte_range_invalid() {
        assert_eq!(parse_byte_range("bytes abc"), None);
        assert_eq!(parse_byte_range(""), None);
        assert_eq!(parse_byte_range("bytes 9-0"), None); // start > end
    }
}