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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#![cfg(target_family = "unix")]

use aws_s3_transfer::config::PartSize;
use aws_s3_transfer::types::ByteSize;
use aws_s3_transfer::{error::ErrorKind, io::walk::FsWalker, types::FailedTransferPolicy};
use aws_sdk_s3::{
    config::http::HttpResponse,
    error::DisplayErrorContext,
    operation::{
        complete_multipart_upload::CompleteMultipartUploadOutput,
        create_multipart_upload::CreateMultipartUploadOutput, put_object::PutObjectOutput,
        upload_part::UploadPartOutput,
    },
    Client,
};
use aws_smithy_mocks::{mock, mock_client, RuleMode};
use aws_smithy_runtime_api::http::StatusCode;
use aws_smithy_types::body::SdkBody;
use std::time::Duration;
use test_common::create_test_dir;
use tokio::{fs::symlink, sync::watch, time::timeout};

/// Default test timeout. Any test body that exceeds this likely reveals a
/// hang in the TM rather than a real slow operation.
const TEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Waits until two `metrics` snapshots taken 10 ms apart report the same
/// `elapsed`, and returns it. `elapsed` stops advancing only once the transfer
/// records its finish, so a transfer that never records one hangs until the
/// caller's `TEST_TIMEOUT`.
async fn wait_for_finished_elapsed(
    metrics: impl Fn() -> aws_s3_transfer::metrics::TransferMetrics,
) -> Duration {
    loop {
        let first = metrics().elapsed;
        tokio::time::sleep(Duration::from_millis(10)).await;
        if metrics().elapsed == first {
            return first;
        }
    }
}

// Create an S3 client with mock behavior configured for `PutObject`
fn mock_s3_client_for_put_object(bucket_name: String) -> Client {
    let put_object = mock!(aws_sdk_s3::Client::put_object)
        .match_requests(move |input| input.bucket() == Some(&bucket_name))
        .then_output(|| PutObjectOutput::builder().build());

    mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object])
}

// Create an S3 client with mock behavior configured for `MultipartUpload`
//
// We intentionally avoid being specific about the expected input and output for mocks,
// as long as the execution of uploading multiple objects completes successfully.
// Setting expectations that are too precise can lead to brittle tests.
fn mock_s3_client_for_multipart_upload(bucket_name: String) -> Client {
    let upload_id = "test-upload-id".to_owned();

    let create_mpu = mock!(aws_sdk_s3::Client::create_multipart_upload).then_output({
        let upload_id = upload_id.clone();
        move || {
            CreateMultipartUploadOutput::builder()
                .upload_id(upload_id.clone())
                .build()
        }
    });

    let upload_part = mock!(aws_sdk_s3::Client::upload_part)
        .match_requests({
            let upload_id = upload_id.clone();
            move |input| {
                input.upload_id.as_ref() == Some(&upload_id) && input.bucket() == Some(&bucket_name)
            }
        })
        .then_output(|| UploadPartOutput::builder().e_tag("test-etag").build());

    let complete_mpu = mock!(aws_sdk_s3::Client::complete_multipart_upload)
        .match_requests({
            let upload_id = upload_id.clone();
            move |r| r.upload_id.as_ref() == Some(&upload_id)
        })
        .then_output(|| CompleteMultipartUploadOutput::builder().build());

    mock_client!(
        aws_sdk_s3,
        RuleMode::MatchAny,
        &[create_mpu, upload_part, complete_mpu]
    )
}

#[tokio::test]
async fn test_successful_multiple_objects_upload_via_put_object() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        let files = vec![
            ("sample.jpg", 1),
            ("photos/2022/January/sample.jpg", 1),
            ("photos/2022/February/sample1.jpg", 1),
            ("photos/2022/February/sample2.jpg", 1),
            ("photos/2022/February/sample3.jpg", 1),
        ];
        let test_dir = create_test_dir(Some(recursion_root), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(5, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(5, output.metrics.network_tx);
    })
    .await
    .expect("test_successful_multiple_objects_upload_via_put_object timed out");
}

#[tokio::test]
async fn test_successful_multiple_objects_upload_via_multipart_upload() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        // should be in sync with `aws_s3_transfer::config::MIN_MULTIPART_PART_SIZE_BYTES`
        const MIN_MULTIPART_PART_SIZE_BYTES: u64 = ByteSize::mib(5).as_u64();
        let files = vec![
            ("sample.jpg", MIN_MULTIPART_PART_SIZE_BYTES as usize),
            (
                "photos/2022/January/sample.jpg",
                MIN_MULTIPART_PART_SIZE_BYTES as usize,
            ),
        ];
        let test_dir = create_test_dir(Some(recursion_root), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_multipart_upload(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .multipart_threshold(PartSize::Target(ByteSize::new(5)))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(2, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(2 * MIN_MULTIPART_PART_SIZE_BYTES, output.metrics.network_tx);
    })
    .await
    .expect("test_successful_multiple_objects_upload_via_multipart_upload timed out");
}

#[tokio::test]
async fn test_successful_multiple_objects_upload_with_symlinks() {
    timeout(TEST_TIMEOUT, async {
        let temp_dir1 = create_test_dir(Some("temp1"), vec![("sample.jpg", 1)], &[]);

        let temp_dir2 = create_test_dir(
            Some("temp2"),
            vec![
                ("sample.txt", 1),
                ("docs/2022/January/sample.txt", 1),
                ("docs/2022/February/sample1.txt", 1),
                ("docs/2022/February/sample2.txt", 1),
                ("docs/2022/February/sample3.txt", 1),
            ],
            &[],
        );

        let temp_dir3 = create_test_dir(Some("temp3"), vec![("sample3.png", 1)], &[]);

        // Crate a symbolic link from `temp1/symlink` to `temp2`
        symlink(&temp_dir2, temp_dir1.path().join("symlink"))
            .await
            .unwrap();
        // Crate a symbolic link from `temp1/symlink2` to `temp3/sample.png`
        symlink(
            temp_dir3.path().join("sample3.png"),
            temp_dir1.path().join("symlink2"),
        )
        .await
        .unwrap();

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        // Test with following symbolic links while uploading recursively
        {
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(temp_dir1.path())
                .walker(
                    FsWalker::builder()
                        .recursive(true)
                        .follow_symlinks(true)
                        .build(),
                )
                .initiate()
                .unwrap();

            let output = handle.join().await.unwrap();
            assert_eq!(7, output.objects_uploaded());
            assert!(output.failed_transfers().is_empty());
            assert_eq!(7, output.metrics.network_tx);
        }

        // Test without following symbolic links while uploading recursively
        {
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(temp_dir1.path())
                .initiate()
                .unwrap();

            let output = handle.join().await.unwrap();
            assert_eq!(1, output.objects_uploaded()); // should only include "temp1/sample.jpg"
            assert!(output.failed_transfers().is_empty());
            assert_eq!(1, output.metrics.network_tx);
        }
    })
    .await
    .expect("test_successful_multiple_objects_upload_with_symlinks timed out");
}

#[tokio::test]
async fn test_source_dir_is_symlink() {
    timeout(TEST_TIMEOUT, async {
        let temp_dir1 = create_test_dir(Some("temp1"), vec![], &[]);

        let temp_dir2 = create_test_dir(Some("temp2"), vec![("sample.txt", 1)], &[]);

        // Create a symbolic link from `temp1/symlink` to `temp2`
        let symlink_path = temp_dir1.path().join("symlink");
        symlink(&temp_dir2, &symlink_path).await.unwrap();

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        // When the source is a symbolic link to a directory and follow_symlinks is false,
        // the walker rejects the root on first iteration; the error surfaces from join()
        // as InputInvalid (a bad source root is invalid input, not an I/O failure).
        {
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(&symlink_path)
                .initiate()
                .unwrap();

            let err = handle.join().await.unwrap_err();
            assert_eq!(&ErrorKind::InputInvalid, err.kind());
        }

        // should succeed when the source is a symbolic link to a directory and the operation follows symbolic links
        {
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(symlink_path)
                .walker(FsWalker::builder().follow_symlinks(true).build())
                .initiate()
                .unwrap();

            let output = handle.join().await.unwrap();
            assert_eq!(1, output.objects_uploaded());
            assert!(output.failed_transfers().is_empty());
            assert_eq!(1, output.metrics.network_tx);
        }
    })
    .await
    .expect("test_source_dir_is_symlink timed out");
}

#[tokio::test]
async fn test_failed_upload_policy_continue() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        let files = vec![
            ("sample.jpg", 1),
            ("photos/2022/January/sample.jpg", 1),
            ("photos/2022/February/sample1.jpg", 1),
            ("photos/2022/February/sample2.jpg", 1),
            ("photos/2022/February/sample3.jpg", 1),
        ];
        // Make all files inaccessible under `photos/2022/February`
        let inaccessible_dir_relative_path = "photos/2022/February";
        let test_dir = create_test_dir(
            Some(recursion_root),
            files.clone(),
            &[inaccessible_dir_relative_path],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .failure_policy(FailedTransferPolicy::Continue)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(2, output.objects_uploaded());
        // One failure recorded for the inaccessible subdir (cannot enumerate its contents)
        assert_eq!(1, output.failed_transfers().len());
        assert!(output.failed_transfers()[0].input().is_none());
        assert_eq!(2, output.metrics.network_tx);
    })
    .await
    .expect("test_failed_upload_policy_continue timed out");
}

#[tokio::test]
async fn test_server_error_should_be_recorded_as_such_in_failed_transfers() {
    timeout(TEST_TIMEOUT, async {
        let test_dir = create_test_dir(Some("test"), vec![("sample.jpg", 1)], &[]);

        let bucket_name = "test-bucket";
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_http_response(|| {
                HttpResponse::new(StatusCode::try_from(500).unwrap(), SdkBody::empty())
            });
        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .failure_policy(FailedTransferPolicy::Continue)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(0, output.objects_uploaded());
        assert_eq!(1, output.failed_transfers().len());
        // The new state machine records source_path for failed uploads; the UploadInput
        // cannot be captured because the InputStream body is non-clonable.
        assert!(output.failed_transfers()[0].source_path().is_some());
        assert_eq!(0, output.metrics.network_tx);
    })
    .await
    .expect("test_server_error_should_be_recorded_as_such_in_failed_transfers timed out");
}

/// Fail when source is not a directory.
#[tokio::test]
async fn test_source_dir_not_valid() {
    timeout(TEST_TIMEOUT, async {
        let source = tempfile::NamedTempFile::new().unwrap();

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        // The walker detects the non-directory root on first iteration; the error
        // surfaces from join() as IOError rather than the legacy InputInvalid.
        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(source.path())
            .initiate()
            .unwrap();

        let err = handle.join().await.unwrap_err();
        assert_eq!(&ErrorKind::InputInvalid, err.kind());
    })
    .await
    .expect("test_source_dir_not_valid timed out");
}

#[tokio::test]
async fn test_error_when_custom_delimiter_appears_in_filename() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        let files = vec![
            ("sample.jpg", 1),
            ("photos/2022-January/sample.jpg", 1),
            ("photos/2022-February/sample1.jpg", 1),
            ("photos/2022-February/sample2.jpg", 1),
            ("photos/2022-February/sample3.jpg", 1),
        ];
        let test_dir = create_test_dir(Some(recursion_root), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .delimiter("-")
            .initiate()
            .unwrap();

        // Under the default Abort policy, the first key derivation failure aborts
        // the transfer. The terminal error is ChildOperationFailed, and its
        // source chain carries the key derivation error.
        let err = handle.join().await.unwrap_err();
        assert_eq!(&ErrorKind::ChildOperationFailed, err.kind());
        let child = std::error::Error::source(&err)
            .and_then(|s| s.downcast_ref::<aws_s3_transfer::error::Error>())
            .expect("the source is the failed child's error");
        assert_eq!(&ErrorKind::InputInvalid, child.kind());
        let cause = std::error::Error::source(child).expect("the child keeps its cause");
        assert!(
            cause
                .to_string()
                .contains("a custom delimiter `-` should not appear in"),
            "the child's cause is the key derivation error, got: {cause}"
        );
    })
    .await
    .expect("test_error_when_custom_delimiter_appears_in_filename timed out");
}

#[tokio::test]
async fn test_abort_on_handle_should_terminate_tasks_gracefully() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        let files = vec![
            ("sample.jpg", 1),
            ("photos/2022-January/sample.jpg", 1),
            ("photos/2022-February/sample1.jpg", 1),
            ("photos/2022-February/sample2.jpg", 1),
            ("photos/2022-February/sample3.jpg", 1),
        ];
        let test_dir = create_test_dir(Some(recursion_root), files.clone(), &[]);

        let (watch_tx, watch_rx) = watch::channel(());

        let bucket_name = "test-bucket";
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_output({
                let rx = watch_rx.clone();
                move || {
                    while !rx.has_changed().unwrap() {}
                    PutObjectOutput::builder().build()
                }
            });

        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        // Release the mock's spin wait so in-flight PutObjects can return.
        watch_tx.send(()).unwrap();

        // abort() should complete (cancel + wait_for_idle) without hanging.
        handle.abort().await;
    })
    .await
    .expect("test_abort_on_handle_should_terminate_tasks_gracefully timed out");
}

#[tokio::test]
async fn test_failed_child_operation_should_cause_ongoing_requests_to_be_cancelled() {
    timeout(TEST_TIMEOUT, async {
        let recursion_root = "test";
        let files = vec![
            ("sample.jpg", 1),
            ("photos/2022-January/sample.jpg", 1),
            ("photos/2022-February/sample1.jpg", 1),
            ("photos/2022-February/sample2.jpg", 1),
            ("photos/2022-February/sample3.jpg", 1),
        ];
        let test_dir = create_test_dir(Some(recursion_root), files.clone(), &[]);

        let bucket_name = "test-bucket";

        // Fail every PutObject attempt so SDK retries exhaust and each child
        // upload's join() surfaces an error. Under the default Abort policy, the
        // first failure aborts the parent transfer, which cancels all ongoing
        // siblings. `handle.join()` returns the triggering error.
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_http_response(|| {
                HttpResponse::new(StatusCode::try_from(500).unwrap(), SdkBody::empty())
            });

        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let err = handle.join().await.unwrap_err();
        assert_eq!(&ErrorKind::ChildOperationFailed, err.kind());
    })
    .await
    .expect("test_failed_child_operation_should_cause_ongoing_requests_to_be_cancelled timed out");
}

// ref: RUST-1202
/// Under the Abort policy, the aggregate error's source is the error of the
/// child upload that triggered the abort, so the error chain names the failed
/// S3 operation and its error code.
#[tokio::test]
async fn test_aborted_upload_objects_error_source_is_failed_child_error() {
    use aws_s3_transfer::error::Error;

    timeout(TEST_TIMEOUT, async {
        let test_dir = create_test_dir(
            Some("test"),
            vec![("a.txt", 1), ("denied.txt", 1), ("b.txt", 1)],
            &[],
        );

        let denied = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(|input| input.key() == Some("denied.txt"))
            .then_http_response(|| {
                HttpResponse::new(
                    StatusCode::try_from(403).unwrap(),
                    SdkBody::from("<Error><Code>AccessDenied</Code></Error>"),
                )
            });
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .then_output(|| PutObjectOutput::builder().build());
        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[denied, put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let err = sut
            .upload_objects()
            .bucket("test-bucket")
            .source(test_dir.path())
            .failure_policy(FailedTransferPolicy::Abort)
            .initiate()
            .unwrap()
            .join()
            .await
            .unwrap_err();

        assert_eq!(&ErrorKind::ChildOperationFailed, err.kind());
        let first = err
            .failed_uploads()
            .and_then(|f| f.first())
            .expect("the aggregate carries the failed uploads");
        assert_eq!(
            Some("denied.txt"),
            first
                .source_path()
                .and_then(|p| p.file_name())
                .and_then(|n| n.to_str())
        );

        let source = std::error::Error::source(&err)
            .and_then(|s| s.downcast_ref::<Error>())
            .expect("the source is the failed child's error");
        assert!(
            std::ptr::eq(source, first.error()),
            "the source is the first failed upload's error"
        );
        assert_eq!(Some("PutObject"), source.operation_name());
        assert_eq!(Some("AccessDenied"), source.code());

        let context = format!("{}", DisplayErrorContext(&err));
        assert!(
            context.contains("PutObject") && context.contains("AccessDenied"),
            "the error context names the child's operation and code, got: {context}"
        );
    })
    .await
    .expect("test_aborted_upload_objects_error_source_is_failed_child_error timed out");
}

#[tokio::test]
async fn test_drop_upload_objects_handle() {
    timeout(TEST_TIMEOUT, async {
        let test_dir = create_test_dir(
            Some("test"),
            vec![
                ("sample.jpg", 1),
                ("photos/2022-January/sample.jpg", 1),
                ("photos/2022-February/sample1.jpg", 1),
                ("photos/2022-February/sample2.jpg", 1),
                ("photos/2022-February/sample3.jpg", 1),
            ],
            &[],
        );

        let (watch_tx, watch_rx) = watch::channel(());

        let bucket_name = "test-bucket";
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_output({
                move || {
                    let _ = watch_tx.send(());
                    PutObjectOutput::builder().build()
                }
            });
        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        // Wait until at least one PutObject has been invoked so drop happens
        // against an in-flight transfer, not immediately after spawning.
        let rx = watch_rx.clone();
        while !rx.has_changed().unwrap() {
            tokio::time::sleep(Duration::from_millis(50)).await;
        }

        // Give spawned tasks a moment to progress.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Dropping must not panic and must cancel the transfer cleanly.
        drop(handle);
    })
    .await
    .expect("test_drop_upload_objects_handle timed out");
}

/// Metrics correctness on a successful multi-object upload.
///
/// After a fully successful upload of files with known sizes:
/// - `objects_uploaded` matches the number of source files
/// - `network_tx` equals the sum of source file sizes
/// - `disk_read` equals the sum of source file sizes
/// - `elapsed` stops advancing once the transfer finishes, and the output reports
///   that final value
#[tokio::test]
async fn test_metrics_correctness_on_success() {
    timeout(TEST_TIMEOUT, async {
        let files = vec![
            ("a.bin", 7),
            ("b.bin", 13),
            ("nested/c.bin", 19),
            ("nested/deep/d.bin", 23),
        ];
        let total_bytes: u64 = files.iter().map(|(_, s)| *s as u64).sum();
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let elapsed = wait_for_finished_elapsed(|| handle.metrics()).await;
        let output = handle.join().await.unwrap();
        assert_eq!(4, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(
            total_bytes, output.metrics.network_tx,
            "network_tx should equal sum of source file sizes"
        );
        assert_eq!(
            total_bytes, output.metrics.disk_read,
            "disk_read should equal sum of source file sizes"
        );
        assert_eq!(output.metrics.elapsed, elapsed);
    })
    .await
    .expect("test_metrics_correctness_on_success timed out");
}

/// Serial execution correctness with `max_concurrent_uploads(1)`.
///
/// Forces the state machine through the serial-execution regime: only one
/// child spawned at a time, reaped before the next is spawned. All files
/// must still upload and metrics must still aggregate correctly.
#[tokio::test]
async fn test_max_concurrent_uploads_one_serial_execution() {
    timeout(TEST_TIMEOUT, async {
        let files: Vec<(String, usize)> = (0..10).map(|i| (format!("f{i}.bin"), 3)).collect();
        let files_ref: Vec<(&str, usize)> = files.iter().map(|(p, s)| (p.as_str(), *s)).collect();
        let test_dir = create_test_dir(Some("test"), files_ref, &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .max_concurrent_uploads(1)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(10, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(30, output.metrics.network_tx);
        assert_eq!(30, output.metrics.disk_read);
    })
    .await
    .expect("test_max_concurrent_uploads_one_serial_execution timed out");
}

/// Deep tree exercises subtree claiming beyond `MAX_PARALLEL_WALKS`.
///
/// Builds a tree wider than the hardcoded 16-walker cap so the state
/// machine's `claim_subtrees` path is exercised: one walker splits off
/// sub-walkers up to the cap. Every file must still be uploaded exactly
/// once, with no lost entries.
#[tokio::test]
async fn test_deep_tree_subtree_claiming() {
    timeout(TEST_TIMEOUT, async {
        // 20 sibling subdirectories under the root, each with one file.
        // Combined with the root, that's 20 directories to walk, exceeding
        // the 16-walker cap so subtree claiming is forced to queue.
        let files: Vec<(String, usize)> = (0..20)
            .map(|i| (format!("sub_{i:02}/file.bin"), 5))
            .collect();
        let files_ref: Vec<(&str, usize)> = files.iter().map(|(p, s)| (p.as_str(), *s)).collect();
        let test_dir = create_test_dir(Some("test"), files_ref, &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(
            20,
            output.objects_uploaded(),
            "all 20 files in sibling subdirs must upload"
        );
        assert!(output.failed_transfers().is_empty());
        assert_eq!(100, output.metrics.network_tx);
    })
    .await
    .expect("test_deep_tree_subtree_claiming timed out");
}

/// Custom walker filter limits the set of uploaded files.
///
/// Exercises the walker-first API surface: a filter closure is attached to
/// the `FsWalker`, and only files the filter accepts should be uploaded.
#[tokio::test]
async fn test_walker_filter_restricts_uploads() {
    timeout(TEST_TIMEOUT, async {
        let files = vec![
            ("keep.txt", 4),
            ("skip.log", 4),
            ("nested/keep.txt", 4),
            ("nested/skip.log", 4),
        ];
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(
                FsWalker::builder()
                    .recursive(true)
                    .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "txt"))
                    .build(),
            )
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(
            2,
            output.objects_uploaded(),
            "only .txt files should upload"
        );
        assert!(output.failed_transfers().is_empty());
        assert_eq!(8, output.metrics.network_tx);
    })
    .await
    .expect("test_walker_filter_restricts_uploads timed out");
}

/// Empty source directory terminates cleanly with zero metrics.
///
/// Regression target for the `reaping_in_flight` race: when the walker
/// yields no entries and no children are ever spawned, `check_terminal`
/// must still fire and the handle must settle with an empty output.
#[tokio::test]
async fn test_empty_source_directory() {
    timeout(TEST_TIMEOUT, async {
        let test_dir = create_test_dir(Some("test"), vec![], &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let elapsed = wait_for_finished_elapsed(|| handle.metrics()).await;
        let output = handle.join().await.unwrap();
        assert_eq!(0, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(0, output.metrics.network_tx);
        assert_eq!(0, output.metrics.disk_read);
        assert_eq!(
            output.metrics.elapsed, elapsed,
            "a zero-work transfer must record its finish"
        );
    })
    .await
    .expect("test_empty_source_directory timed out");
}

/// Interleaved per-child success and failure under `Continue` policy.
///
/// One specific key always returns 500 (persistent failure); the others
/// succeed. The transfer must complete (not abort), and the output must
/// record:
/// - successful uploads with `objects_uploaded`
/// - the failed upload with a populated `source_path`
/// - metrics reflecting only the on-wire bytes actually sent
#[tokio::test]
async fn test_interleaved_success_failure_continue() {
    timeout(TEST_TIMEOUT, async {
        let files = vec![
            ("a.bin", 4),
            ("b.bin", 4),
            ("doomed.bin", 4),
            ("c.bin", 4),
            ("d.bin", 4),
        ];
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let fail_match = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| {
                input.bucket() == Some(bucket_name)
                    && input.key().is_some_and(|k| k.ends_with("doomed.bin"))
            })
            .then_http_response(|| {
                HttpResponse::new(StatusCode::try_from(500).unwrap(), SdkBody::empty())
            });
        let succeed_match = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_output(|| PutObjectOutput::builder().build());

        let s3_client = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[fail_match, succeed_match]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3_client.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .failure_policy(FailedTransferPolicy::Continue)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(4, output.objects_uploaded());
        assert_eq!(1, output.failed_transfers().len());
        let failed = &output.failed_transfers()[0];
        assert!(
            failed.source_path().is_some(),
            "failed upload must carry source_path"
        );
        assert!(
            failed
                .source_path()
                .unwrap()
                .to_string_lossy()
                .ends_with("doomed.bin"),
            "failed source_path should point at the failing file"
        );
    })
    .await
    .expect("test_interleaved_success_failure_continue timed out");
}

/// Dropping the handle while the walk is still in progress must not
/// panic and must tear down cleanly.
///
/// Creates a larger tree than the previous drop test and drops the handle
/// without any synchronization, so the drop can race with walker dispatch
/// and child spawning.
#[tokio::test]
async fn test_drop_during_walk_in_progress() {
    timeout(TEST_TIMEOUT, async {
        let files: Vec<(String, usize)> =
            (0..50).map(|i| (format!("dir_{i:02}/f.bin"), 2)).collect();
        let files_ref: Vec<(&str, usize)> = files.iter().map(|(p, s)| (p.as_str(), *s)).collect();
        let test_dir = create_test_dir(Some("test"), files_ref, &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        // Drop immediately — walker is almost certainly still producing
        // entries, and some children may be mid-flight.
        drop(handle);

        // Give tasks a moment to settle to ensure Drop did not deadlock.
        tokio::time::sleep(Duration::from_millis(50)).await;
    })
    .await
    .expect("test_drop_during_walk_in_progress timed out");
}

/// Multi-file multipart uploads aggregate `network_tx` and `disk_read`
/// correctly at the parent level.
///
/// Uses the multipart path exclusively (which instruments `disk_read` via
/// `part_reader`) to verify the parent aggregates both counters across
/// multiple multipart children.
#[tokio::test]
async fn test_multipart_metrics_aggregate_across_children() {
    timeout(TEST_TIMEOUT, async {
        const MIN_MULTIPART: u64 = ByteSize::mib(5).as_u64();
        let files = vec![
            ("a.bin", MIN_MULTIPART as usize),
            ("b.bin", MIN_MULTIPART as usize),
            ("nested/c.bin", MIN_MULTIPART as usize),
        ];
        let expected_total: u64 = MIN_MULTIPART * 3;
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_multipart_upload(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .multipart_threshold(PartSize::Target(ByteSize::new(5)))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(3, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
        assert_eq!(
            expected_total, output.metrics.network_tx,
            "network_tx should sum across all multipart children"
        );
        assert_eq!(
            expected_total, output.metrics.disk_read,
            "disk_read should sum across all multipart children (part_reader instruments it)"
        );
    })
    .await
    .expect("test_multipart_metrics_aggregate_across_children timed out");
}

/// Handle `status()` returns a terminal variant after join.
#[tokio::test]
async fn test_status_transitions_to_terminal() {
    timeout(TEST_TIMEOUT, async {
        let test_dir = create_test_dir(Some("test"), vec![("a.bin", 1)], &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        // Status at this point may be Running or (for a fast completion on
        // 1-byte files) already terminal; don't assert on pre-join state.
        let output = handle.join().await.unwrap();
        assert_eq!(1, output.objects_uploaded());
        // Output being Ok implies the transfer reached a non-error terminal
        // state. No separate status accessor after join since the handle is
        // consumed.
    })
    .await
    .expect("test_status_transitions_to_terminal timed out");
}

/// Hidden files (dotfiles) are uploaded by default.
///
/// The default walker does not filter dotfiles. A custom filter is the
/// opt-in path for users who want to exclude them.
#[tokio::test]
async fn test_hidden_files_uploaded_by_default() {
    timeout(TEST_TIMEOUT, async {
        let files = vec![
            (".hidden.txt", 3),
            ("visible.txt", 3),
            (".dotdir/inner.txt", 3),
        ];
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(
            3,
            output.objects_uploaded(),
            "all files including dotfiles and files in dotdirs should upload"
        );
        assert!(output.failed_transfers().is_empty());
    })
    .await
    .expect("test_hidden_files_uploaded_by_default timed out");
}

/// Multiple `upload_objects` calls on the same `Client` must each
/// complete independently. Verifies no state leaks between iterations
/// (thread-locals, ready_set descriptors, counter residue).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_multiple_iterations_on_same_client_do_not_hang() {
    timeout(Duration::from_secs(60), async {
        const FILE_COUNT: usize = 2000;
        const ITERATIONS: usize = 3;
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("f/{i:04}.bin"), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        for iter in 0..ITERATIONS {
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(test_dir.path())
                .walker(FsWalker::builder().recursive(true).build())
                .key_prefix(format!("iter{iter}/"))
                .initiate()
                .unwrap();
            let output = handle.join().await.unwrap();
            assert_eq!(
                FILE_COUNT as u64,
                output.objects_uploaded(),
                "iteration {iter}: all files should upload"
            );
            assert!(
                output.failed_transfers().is_empty(),
                "iteration {iter}: no failures expected"
            );
        }
    })
    .await
    .expect("test_multiple_iterations_on_same_client_do_not_hang timed out");
}

/// Regression test for a hang where a re-entrant scheduler path left work
/// items in the submission queue undispatched.
///
/// The scenario: parent `poll_work` inside `spawn_children` called
/// `Upload::orchestrate_child`, which called `scheduler.enqueue_transfer`,
/// which called `scheduler.generate_work` — all while holding the parent's
/// state lock. Worker threads firing child-completion wakes would then
/// block on the parent state lock, each holding a pending count on the
/// shared submission queue. The queue's pending counter never dropped to
/// zero so flushes were skipped. The fix spans three layers (see
/// `GenerateWorkGuard` in scheduler, `SUBMISSION_DEPTH` in submission, and
/// the claim/orchestrate/merge phases in `poll_work`). This test asserts
/// that a burst of concurrent child completions completes through all of
/// them.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_concurrent_child_completion_terminates_cleanly() {
    timeout(Duration::from_secs(30), async {
        // 300 small files, all succeeding. 300 is comfortably above the
        // default pipeline depth (100) so spawn_children will iterate
        // multiple times and the scheduler will process many child
        // completions concurrently.
        const FILE_COUNT: usize = 300;
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("f/{i:04}.bin"), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(FILE_COUNT as u64, output.objects_uploaded());
        assert!(output.failed_transfers().is_empty());
    })
    .await
    .expect("test_concurrent_child_completion_terminates_cleanly timed out");
}

/// Same shape as `test_concurrent_child_completion_terminates_cleanly`
/// but under `FailedTransferPolicy::Continue` with every child failing.
/// Exercises the failure path through the 3-phase spawn restructure and
/// verifies `children_reserved` is released correctly on the error side
/// of `merge_spawned`.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_continue_policy_records_all_failures_under_concurrent_orchestration() {
    timeout(Duration::from_secs(30), async {
        const FILE_COUNT: usize = 200;
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("f/{i:04}.bin"), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";

        // Every PutObject returns a 503 server error. Under Continue
        // policy these accumulate in `failed_transfers`.
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_http_response(|| {
                HttpResponse::new(StatusCode::try_from(503).unwrap(), SdkBody::from(""))
            });

        let s3 = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[&put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                s3.config().to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .failure_policy(FailedTransferPolicy::Continue)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(0, output.objects_uploaded());
        assert_eq!(FILE_COUNT, output.failed_transfers().len());
    })
    .await
    .expect("test_continue_policy_records_all_failures_under_concurrent_orchestration timed out");
}

/// Verify `max_concurrent_uploads` is respected across the claim/orchestrate/merge
/// split even when many children complete concurrently. Counts the maximum
/// in-flight PutObjects observed through the mock and asserts it never
/// exceeds `max_concurrent_uploads`.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_max_concurrent_uploads_respected_during_concurrent_orchestration() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    timeout(Duration::from_secs(30), async {
        const FILE_COUNT: usize = 100;
        const MAX_CONCURRENT: usize = 8;
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("{i:04}.bin"), 16))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let in_flight = Arc::new(AtomicUsize::new(0));
        let max_observed = Arc::new(AtomicUsize::new(0));
        let in_flight_cb = Arc::clone(&in_flight);
        let max_observed_cb = Arc::clone(&max_observed);

        let bucket_name = "test-bucket";
        let put_object = mock!(aws_sdk_s3::Client::put_object)
            .match_requests(move |input| input.bucket() == Some(bucket_name))
            .then_output(move || {
                let current = in_flight_cb.fetch_add(1, Ordering::AcqRel) + 1;
                max_observed_cb.fetch_max(current, Ordering::AcqRel);
                // Yielding is not available inside a blocking `then_output`
                // closure, so fake concurrency by sleeping briefly to widen
                // the window where many children can be in-flight at once.
                std::thread::sleep(Duration::from_millis(2));
                in_flight_cb.fetch_sub(1, Ordering::AcqRel);
                PutObjectOutput::builder().build()
            });

        let s3 = mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[&put_object]);
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(s3.config().to_builder()))
            .build()
.expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .max_concurrent_uploads(MAX_CONCURRENT)
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(FILE_COUNT as u64, output.objects_uploaded());
        let observed = max_observed.load(Ordering::Acquire);
        assert!(
            observed <= MAX_CONCURRENT,
            "max concurrent PutObjects ({observed}) exceeded max_concurrent_uploads ({MAX_CONCURRENT}); \
             children_reserved must prevent over-spawning during lock-released orchestration"
        );
    })
    .await
    .expect("test_max_concurrent_uploads_respected_during_concurrent_orchestration timed out");
}

/// Abort policy with mid-burst latency must terminate cleanly without
/// leaking the counter protocol. The mock succeeds for the first
/// `SUCCESS_COUNT` calls then 503's; with synchronous per-call latency
/// of `LATENCY`, by the time the first 503 lands the parent already has
/// many successful children in `state.children` (and possibly more
/// reservations in flight). Hitting `abort()` from
/// `execute_join_children` while the protocol is non-trivially
/// populated exercises the lock-released orchestration window plus the
/// merge-spawned reservation-release path.
///
/// Asserts: `join()` returns `Err`, the error's source is the failed
/// PutObject that caused the abort, and the test completes within its timeout (no hang
/// on stale `children_reserved` or `reaping_in_flight`).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_abort_policy_terminates_cleanly_during_concurrent_orchestration() {
    timeout(Duration::from_secs(30), async {
        const FILE_COUNT: usize = 100;
        const SUCCESS_COUNT: usize = 30;
        const LATENCY: Duration = Duration::from_millis(15);

        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("f/{i:04}.bin"), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object_succeeds_then_fails(
                    bucket_name.to_owned(),
                    SUCCESS_COUNT,
                    LATENCY,
                )
                .config()
                .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .failure_policy(FailedTransferPolicy::Abort)
            .initiate()
            .unwrap();

        let result = handle.join().await;
        let err = result.expect_err("Abort policy must surface an error");
        assert!(
            matches!(
                err.kind(),
                aws_s3_transfer::error::ErrorKind::ChildOperationFailed
            ),
            "expected ChildOperationFailed, got: {:?}",
            err.kind(),
        );
        let source = std::error::Error::source(&err)
            .and_then(|s| s.downcast_ref::<aws_s3_transfer::error::Error>())
            .expect("the error's source is the failed child upload's error");
        assert_eq!(
            Some("PutObject"),
            source.operation_name(),
            "expected the failed PutObject as the abort cause, got: {source:?}",
        );
    })
    .await
    .expect("test_abort_policy_terminates_cleanly_during_concurrent_orchestration timed out");
}

/// Dropping the handle while child uploads are mid-flight must cascade
/// cancellation through the scheduler without deadlocking on the state
/// lock and without hanging on counters that the orphaned in-flight
/// work would otherwise have decremented. With per-call latency of
/// `LATENCY`, the burst saturates the pipeline and the drop fires
/// while children occupy `state.children`, `children_reserved`, and
/// (statistically) `reaping_in_flight` simultaneously.
///
/// Asserts: drop returns within 50 ms (no deadlock), and within a 5 s
/// settle window every child `UploadHandle::status()` reaches a
/// terminal state (cascade reached the children).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_drop_during_active_uploads_cancels_without_hang() {
    timeout(Duration::from_secs(30), async {
        const FILE_COUNT: usize = 200;
        const LATENCY: Duration = Duration::from_millis(20);

        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("f/{i:04}.bin"), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object_with_latency(bucket_name.to_owned(), LATENCY)
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        // Let several children dispatch and complete so the protocol
        // is non-trivially populated when the drop fires. 50 ms covers
        // ~2 LATENCY rounds, enough to seed reservations + reaping.
        tokio::time::sleep(Duration::from_millis(50)).await;

        let drop_start = std::time::Instant::now();
        drop(handle);
        let drop_elapsed = drop_start.elapsed();
        assert!(
            drop_elapsed < Duration::from_millis(50),
            "drop took {drop_elapsed:?}; expected < 50ms, indicates a deadlock"
        );

        // Settle window for the cascade to complete. If the cascade
        // is broken the timeout above (30 s) will fire instead.
        tokio::time::sleep(Duration::from_secs(2)).await;
    })
    .await
    .expect("test_drop_during_active_uploads_cancels_without_hang timed out");
}

/// Multi-iteration upload_objects stress test exercising the state machine's
/// re-entrancy guards.
///
/// Runs three iterations of a 10 000-file upload back-to-back on a single
/// client. Each iteration uses a fresh key prefix so nothing is shared
/// between runs except the scheduler, its thread-local re-entry guards
/// (`IN_GENERATE_WORK`, `SUBMISSION_DEPTH`), and the submission queue.
///
/// The purpose is to catch re-entrancy defects that only manifest when
/// scheduler state persists across transfer boundaries — for example a
/// guard that is cleared on the happy path but not on an early return,
/// or a thread-local that accumulates across iterations. Instant-response
/// mocks keep the test isolated to the TM layer (no network, no hyper, no
/// HTTP) so any stall is attributable to scheduler or state-machine
/// behaviour.
///
/// Run with: `cargo test ... --release -- --ignored --nocapture`.
#[ignore = "stress repro, run with --ignored"]
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn test_stress_multi_iter_reproduce_ec2_hang() {
    timeout(Duration::from_secs(240), async {
        const FILE_COUNT: usize = 10_000;
        const ITERATIONS: usize = 3;
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("d{:03}/{i:05}.bin", i / 100), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(
                mock_s3_client_for_put_object(bucket_name.to_owned())
                    .config()
                    .to_builder(),
            ))
            .build()
            .expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        for iter in 0..ITERATIONS {
            let start = std::time::Instant::now();
            let handle = sut
                .upload_objects()
                .bucket(bucket_name)
                .source(test_dir.path())
                .walker(FsWalker::builder().recursive(true).build())
                .key_prefix(format!("iter{iter}/"))
                .initiate()
                .unwrap();
            let output = handle.join().await.unwrap();
            let elapsed = start.elapsed();
            eprintln!(
                "iter {iter} done in {elapsed:?}: uploaded={} failed={}",
                output.objects_uploaded(),
                output.failed_transfers().len()
            );
            assert_eq!(
                FILE_COUNT as u64,
                output.objects_uploaded(),
                "iteration {iter}: all files should upload"
            );
            assert!(
                output.failed_transfers().is_empty(),
                "iteration {iter}: no failures expected"
            );
        }
    })
    .await
    .expect("test_stress_multi_iter_reproduce_ec2_hang timed out");
}

/// Mock S3 `PutObject` that introduces a small, evenly-distributed delay
/// before returning success.
///
/// Mock `PutObject` that responds successfully after a real-time delay
/// of `latency`.
///
/// Uses `std::thread::sleep` rather than `tokio::time::sleep` because
/// `then_compute_output` takes a sync closure. In our test setup the
/// SDK pipeline executes on the transfer manager's managed thread pool
/// (sized to CPU count), not the tokio multi-thread runtime that drives
/// the test. Blocking a managed thread for the duration of a "request"
/// approximates the real SDK path well enough to widen the concurrent
/// in-flight window without starving the test's tokio runtime.
///
/// # Runtime constraint
///
/// Only valid when the transfer manager uses owned managed execution
/// (the default). Under `TokioMultiThreadRuntime` the SDK pipeline
/// runs on tokio worker threads; blocking them with `thread::sleep`
/// starves the runtime and deadlocks the test.
fn mock_s3_client_for_put_object_with_latency(bucket_name: String, latency: Duration) -> Client {
    let put_object = mock!(aws_sdk_s3::Client::put_object)
        .match_requests(move |input| input.bucket() == Some(&bucket_name))
        .then_compute_output(move |_input| {
            std::thread::sleep(latency);
            PutObjectOutput::builder().build()
        });

    mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object])
}

/// Mock `PutObject` that succeeds for the first `success_count` calls,
/// then returns HTTP 503 for every subsequent call. Each call sleeps
/// for `latency` before responding.
///
/// Lets a test pin the timing of a state transition: the `success_count + 1`
/// th call is guaranteed to be the first failure observed, so the parent
/// state machine reaches a known mix of in-flight and pre-failure children.
/// Used to drive the abort path with deterministic mid-burst timing
/// rather than racing instant-response mocks.
///
/// Like `mock_s3_client_for_put_object_with_latency`, the synchronous
/// sleep blocks a managed thread (where the SDK pipeline runs), not the
/// tokio runtime driving the test.
///
/// # Runtime constraint
///
/// Only valid when the transfer manager uses owned managed execution
/// (the default). See `mock_s3_client_for_put_object_with_latency`.
fn mock_s3_client_for_put_object_succeeds_then_fails(
    bucket_name: String,
    success_count: usize,
    latency: Duration,
) -> Client {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    let counter = Arc::new(AtomicUsize::new(0));
    let put_object = mock!(aws_sdk_s3::Client::put_object)
        .match_requests(move |input| input.bucket() == Some(&bucket_name))
        .then_http_response(move || {
            std::thread::sleep(latency);
            let n = counter.fetch_add(1, Ordering::AcqRel);
            if n < success_count {
                let mut resp =
                    HttpResponse::new(StatusCode::try_from(200).unwrap(), SdkBody::from(""));
                resp.headers_mut()
                    .insert("etag", "\"d41d8cd98f00b204e9800998ecf8427e\"");
                resp
            } else {
                HttpResponse::new(StatusCode::try_from(503).unwrap(), SdkBody::from(""))
            }
        });

    mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[put_object])
}

/// Stress test for single-poll exclusivity on a composite transfer's
/// descriptor under concurrent child completions.
///
/// **What this verifies.** The scheduler guarantees that at most one
/// thread is inside `poll_work(desc)` for a given descriptor at a time.
/// This test exercises the code paths that uphold that invariant under a
/// realistic pressure pattern for composite transfers (`upload_objects`
/// in particular): many child uploads completing within a narrow time
/// window each fire `on_completion` on their dispatching managed thread,
/// which calls `scheduler.generate_work()` synchronously on that thread.
/// Without the single-poll guarantee, several of those threads can enter
/// the composite's `poll_work` concurrently, contend on its state mutex,
/// and — since they are running synchronous scheduler code on managed
/// thread tokio runtimes — starve those runtimes of the async task
/// polling they need to drive the remaining in-flight work. The system
/// then has no path back to forward progress.
///
/// **Test shape.** 10 000 small files (32 bytes each, enough to exercise
/// one PutObject per file without making the test dataset expensive) are
/// uploaded through a mock S3 client that returns successfully after a
/// ~10 ms synchronous sleep. The sleep is what allows dispatches to
/// saturate target concurrency (~128) with in-flight work; the first
/// wave of responses then completes in a tight burst that stresses the
/// contention window. The assertion is simply that the upload completes
/// within the test timeout — failure to uphold the invariant manifests
/// as an indefinite stall.
///
/// **Why `#[ignore]`.** ~2 min happy-path runtime keeps it out of
/// routine CI. Run explicitly as part of scheduler-regression
/// validation:
///
/// ```text
/// cargo test -p aws-s3-transfer --release --test upload_objects_test \
///     -- --ignored --nocapture test_stress_parent_lock_contention
/// ```
#[ignore = "stress repro (~2 min), run with --ignored"]
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn test_stress_parent_lock_contention() {
    timeout(Duration::from_secs(180), async {
        const FILE_COUNT: usize = 10_000;
        const PUT_LATENCY: Duration = Duration::from_millis(10);

        // 32 bytes per file: dataset cost is trivial while every file
        // still produces one PutObject. The contention pattern we care
        // about scales with completion count, not per-object size.
        let files: Vec<(String, usize)> = (0..FILE_COUNT)
            .map(|i| (format!("d{:03}/{i:05}.bin", i / 100), 32))
            .collect();
        let test_dir = create_test_dir(
            Some("test"),
            files.iter().map(|(k, s)| (k.as_str(), *s)).collect(),
            &[],
        );

        let bucket_name = "test-bucket";
        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(mock_s3_client_for_put_object_with_latency(
                bucket_name.to_owned(),
                PUT_LATENCY,
            ).config().to_builder()))
            .build()
.expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let start = std::time::Instant::now();
        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();
        let output = handle.join().await.unwrap();
        let elapsed = start.elapsed();
        eprintln!(
            "upload done in {elapsed:?}: uploaded={} failed={}",
            output.objects_uploaded(),
            output.failed_transfers().len()
        );
        assert_eq!(
            FILE_COUNT as u64,
            output.objects_uploaded(),
            "all files should upload — a stall here indicates the scheduler is not draining in-flight work, which usually means single-poll exclusivity has broken",
        );
        assert!(
            output.failed_transfers().is_empty(),
            "no failures expected under happy-path mock",
        );
    })
    .await
    .expect("test_stress_parent_lock_contention timed out — single-poll exclusivity on the composite descriptor is likely broken");
}

/// Every child multipart upload spawned by `upload_objects` must send
/// `MpuObjectSize` on CompleteMultipartUpload, so S3 can reject a request
/// that assembled a wrong-sized object (dropped or duplicated part).
/// Required by SEP step 7.
///
/// The mock matches CompleteMPU only when `mpu_object_size` equals the child's
/// content length. With the field absent or wrong on any child, no rule matches
/// that request and the child fails — the join below then surfaces the
/// failure. Passing under `objects_uploaded == files.len()` is what pins the
/// field's presence on every child.
#[tokio::test]
async fn test_upload_objects_children_send_mpu_object_size() {
    timeout(TEST_TIMEOUT, async {
        // Three files of distinct sizes, all above the multipart threshold, so
        // a naive "always send the same value" implementation would only pass
        // one child at a time.
        let one_mib = ByteSize::mib(1).as_u64();
        let files = vec![
            ("a.bin", (5 * one_mib) as usize),
            ("b.bin", (6 * one_mib) as usize),
            ("nested/c.bin", (7 * one_mib) as usize),
        ];
        let test_dir = create_test_dir(Some("test"), files.clone(), &[]);

        let bucket_name = "test-bucket";
        let upload_id = "test-upload-id".to_owned();

        let create_mpu = mock!(aws_sdk_s3::Client::create_multipart_upload).then_output({
            let upload_id = upload_id.clone();
            move || {
                CreateMultipartUploadOutput::builder()
                    .upload_id(upload_id.clone())
                    .build()
            }
        });

        let upload_part = mock!(aws_sdk_s3::Client::upload_part)
            .then_output(|| UploadPartOutput::builder().e_tag("test-etag").build());

        // Match CompleteMPU only when MpuObjectSize is one of the known file
        // sizes. The mock is size-set-aware rather than per-key because
        // upload_objects dispatches children concurrently and there is no
        // ordering guarantee against a specific key.
        let expected_sizes: Vec<i64> = files
            .iter()
            .map(|(_, size)| *size as i64)
            .collect();
        let complete_mpu = mock!(aws_sdk_s3::Client::complete_multipart_upload)
            .match_requests(move |req| {
                req.mpu_object_size()
                    .is_some_and(|n| expected_sizes.contains(&n))
            })
            .then_output(|| CompleteMultipartUploadOutput::builder().build());

        let client = mock_client!(
            aws_sdk_s3,
            RuleMode::MatchAny,
            &[create_mpu, upload_part, complete_mpu]
        );

        let config = aws_s3_transfer::Config::builder()
            .s3_config(test_common::s3_config_with_test_http(client.config().to_builder()))
            .multipart_threshold(PartSize::Target(ByteSize::new(5)))
            .build()
.expect("valid config");
        let sut = aws_s3_transfer::Client::new(config);

        let handle = sut
            .upload_objects()
            .bucket(bucket_name)
            .source(test_dir.path())
            .walker(FsWalker::builder().recursive(true).build())
            .initiate()
            .unwrap();

        let output = handle.join().await.unwrap();
        assert_eq!(
            3,
            output.objects_uploaded(),
            "every child must send MpuObjectSize = its content length; a child whose CompleteMPU request omits the field will not match the mock and will fail",
        );
        assert!(
            output.failed_transfers().is_empty(),
            "no child should fail: {:?}",
            output.failed_transfers(),
        );
    })
    .await
    .expect("test_upload_objects_children_send_mpu_object_size timed out");
}