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

use crate::config::{ConcurrencyMode, MemoryConfig, PartSize};
#[cfg(not(target_family = "wasm"))]
use crate::runtime::ManagedExecution;
use crate::scheduler::{ConcurrencyController, FixedConcurrency, Scheduler};
use crate::telemetry::Telemetry;
use crate::types::ByteSize;
use crate::Config;
use std::sync::Arc;
use std::time::Duration;

use crate::memory::BufferPool;
use crate::runtime::sizing::{self, ResourcePlan, Signals};
use crate::runtime::ExecutionRuntime;

/// Transfer manager client for Amazon Simple Storage Service.
#[derive(Debug, Clone)]
pub struct Client {
    pub(crate) handle: Arc<Handle>,
}

/// Shared state backing every transfer operation: configuration, the S3 client,
/// the scheduler, the execution runtime, the concurrency controller, telemetry,
/// and the shared payload-memory pool.
#[derive(Debug)]
pub(crate) struct Handle {
    pub(crate) config: crate::Config,
    pub(crate) s3_client: aws_sdk_s3::Client,
    pub(crate) scheduler: Scheduler,
    pub(crate) runtime: Arc<dyn ExecutionRuntime>,
    pub(crate) controller: Arc<dyn ConcurrencyController>,
    pub(crate) telemetry: Arc<Telemetry>,
    pub(crate) buffer_pool: BufferPool,
    /// Resource plan resolved when the client was constructed.
    pub(crate) plan: ResourcePlan,
    /// Per-bucket retry token bucket, cached so all operations and retries to a
    /// given bucket share one live token bucket. The SDK does not share a bucket
    /// across custom retry partitions, and a partition built per operation would
    /// start full every time, defeating the shared throttle budget and its refill.
    /// Unbounded: a client targets few distinct buckets, and entries are cheap
    /// (Arc-shared bucket + name). Invariant: an entry that operations may still be
    /// retrying against must not be dropped — replacing a live draining bucket with
    /// a fresh full one reintroduces the per-operation-fresh-bucket bug.
    retry_partitions: std::sync::Mutex<
        std::collections::HashMap<String, aws_sdk_s3::config::retry::RetryPartition>,
    >,
}

impl Handle {
    /// Reports newly registered scheduler work to client-owned subsystems.
    ///
    /// The callback runs while the scheduler holds its registry write lock.
    /// Keeping the adaptation here lets the scheduler publish lifecycle events
    /// without depending on the policy each client subsystem applies to them.
    pub(crate) fn scheduler_work_registered(&self) {
        self.buffer_pool.record_managed_activity();
    }

    /// Reports that the scheduler has no registered or dispatched work.
    ///
    /// The scheduler holds its registry read lock through this callback, so a
    /// concurrent registration either precedes this event or invalidates it
    /// through [`Self::scheduler_work_registered`].
    pub(crate) fn scheduler_became_idle(&self) {
        self.buffer_pool.record_global_idle();
    }

    /// Get the concrete minimum upload size in bytes to use to determine whether multipart uploads
    /// are enabled for a given request.
    pub(crate) fn mpu_threshold_bytes(&self) -> u64 {
        match self.config.multipart_threshold() {
            PartSize::Auto => ByteSize::mib(16).as_u64(),
            PartSize::Target(explicit) => explicit.as_u64(),
        }
    }

    /// Part size for uploads and downloads.
    pub(crate) fn part_size_bytes(&self) -> u64 {
        self.plan.part_size
    }

    /// Whether the user pinned an explicit part size (vs leaving it `Auto`).
    /// When `Auto`, the transfer manager owns part sizing and may override it
    /// (e.g. align download ranges to an object's stored part size for
    /// validation); an explicit size is respected as set.
    pub(crate) fn user_set_part_size(&self) -> bool {
        matches!(self.config.part_size(), PartSize::Target(_))
    }

    /// Per-operation config override that keys the retry token bucket by bucket.
    ///
    /// Returns an empty override when no bucket is set, which merges as a no-op.
    /// The partition is cached so all operations to the same bucket share one
    /// live token bucket (and its refill): under a total outage the sustained
    /// retry rate to S3 is `REFILL_RATE / throttling_retry_cost` (approx 2
    /// retries/sec per bucket), independent of concurrency.
    pub(crate) fn bucket_partition_override(
        &self,
        bucket: Option<&str>,
    ) -> aws_sdk_s3::config::Builder {
        let builder = aws_sdk_s3::config::Builder::default();
        match bucket {
            Some(b) => {
                let partition = {
                    let mut map = self.retry_partitions.lock().expect("lock poisoned");
                    map.entry(b.to_owned())
                        .or_insert_with(|| crate::retry::bucket_retry_partition(b))
                        .clone()
                };
                builder.retry_partition(partition)
            }
            None => builder,
        }
    }

    /// Per-operation config override for a transfer body (download GET or upload):
    /// bucket retry partition plus the tightened stalled-stream grace.
    fn transfer_override(&self, bucket: Option<&str>) -> aws_sdk_s3::config::Builder {
        self.bucket_partition_override(bucket)
            .stalled_stream_protection(crate::retry::tightened_ssp())
    }

    /// Per-operation config override for a download GET: bucket retry partition
    /// plus the tightened stalled-stream grace on the response body. Intentionally
    /// identical to [`upload_override`](Self::upload_override) (both delegate to
    /// `transfer_override`); the two names document the call site's direction.
    pub(crate) fn download_get_override(
        &self,
        bucket: Option<&str>,
    ) -> aws_sdk_s3::config::Builder {
        self.transfer_override(bucket)
    }

    /// Per-operation config override for an upload (UploadPart / PutObject):
    /// bucket retry partition plus the tightened stalled-stream grace on the
    /// request body. Intentionally identical to
    /// [`download_get_override`](Self::download_get_override); the two names
    /// document the call site's direction.
    pub(crate) fn upload_override(&self, bucket: Option<&str>) -> aws_sdk_s3::config::Builder {
        self.transfer_override(bucket)
    }

    /// Create a Handle for testing on the ambient tokio runtime with a fixed
    /// concurrency target. The ergonomic common case; tests that need a custom
    /// runtime or a controller they drive directly use
    /// [`new_for_test_with_runtime`](Self::new_for_test_with_runtime).
    #[cfg(test)]
    pub(crate) fn new_for_test(config: crate::Config, concurrency: usize) -> Arc<Self> {
        Self::new_for_test_with_runtime(
            config,
            Arc::new(crate::scheduler::FixedConcurrency::new(concurrency)),
            |weak| Arc::new(crate::runtime::TokioMultiThreadRuntime::new(weak)),
        )
    }

    /// Test handle using the ambient tokio runtime (no OS threads spawned).
    ///
    /// Use for: state machine logic, poll_work/execute correctness, mock SDK
    /// interactions. Fast and deterministic.
    ///
    /// Does NOT exercise: managed thread dispatch, per-thread HTTP clients,
    /// cross-runtime wake semantics.
    #[cfg(test)]
    pub(crate) fn test_handle_tokio(config: crate::Config) -> Arc<Self> {
        Self::new_for_test(config, 128)
    }

    /// Test handle with up to four managed threads from detected topology.
    ///
    /// Use for: end-to-end dispatch/wake correctness, verifying behavior
    /// under real thread scheduling. Catches bugs like missing `set_pending`
    /// that only manifest when work is dispatched across thread boundaries.
    ///
    /// The outer test can use `#[tokio::test]` (single-thread) — managed
    /// threads own their own runtimes independently.
    #[cfg(test)]
    pub(crate) fn test_handle_managed(config: crate::Config) -> Arc<Self> {
        Self::new_for_test_with_runtime(
            config,
            Arc::new(crate::scheduler::FixedConcurrency::new(128)),
            |weak| Arc::new(crate::runtime::ManagedExecution::for_test(weak, 4)),
        )
    }

    /// Create a Handle for testing with a custom concurrency controller and
    /// runtime factory. The controller is an axis because some tests drive its
    /// target directly (e.g. an adjustable controller); most pass a
    /// [`FixedConcurrency`](crate::scheduler::FixedConcurrency).
    #[cfg(test)]
    pub(crate) fn new_for_test_with_runtime(
        mut config: crate::Config,
        controller: Arc<dyn ConcurrencyController>,
        runtime_factory: impl FnOnce(std::sync::Weak<Handle>) -> Arc<dyn ExecutionRuntime>,
    ) -> Arc<Self> {
        // Most client tests exercise scheduling rather than memory admission.
        // Keep their automatic pool large enough not to become an incidental
        // gate. 8 GiB fits in a 64-bit `usize`; on 32-bit the conversion
        // saturates to `usize::MAX`.
        const DEFAULT_TEST_MEMORY_BUDGET_BYTES: usize = {
            let bytes = ByteSize::gib(8).as_u64();
            if bytes > usize::MAX as u64 {
                usize::MAX
            } else {
                bytes as usize
            }
        };

        let memory_diagnostics = config.diagnostics().memory();
        let buffer_pool = match config.memory() {
            MemoryConfig::Auto => BufferPool::from_capacity(
                crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
                    DEFAULT_TEST_MEMORY_BUDGET_BYTES as u64,
                )),
                None,
                memory_diagnostics,
            )
            .expect("test buffer-pool configuration must be valid"),
            MemoryConfig::Explicit(pool) => pool.clone(),
        };
        // Sized against this handle's own pool, so results do not depend on
        // host memory.
        let plan = sizing::resolve(Signals {
            throughput_gbps: config.throughput_target_gbps(),
            instance_type: None,
            vcpus: 1,
            ram_bytes: None,
            connection_cap: crate::runtime::platform::ConnectionCap::from_descriptor_limit(None),
            explicit_concurrency: Some(controller.target()),
            explicit_part_size: match config.part_size() {
                PartSize::Target(n) => Some(n.as_u64()),
                PartSize::Auto => None,
            },
            ceiling_override_bytes: Some(
                usize::try_from(buffer_pool.metrics().capacity_bytes()).unwrap_or(usize::MAX),
            ),
        });
        Arc::new_cyclic(|weak| {
            let scheduler = Scheduler::new(weak.clone());
            let runtime = runtime_factory(weak.clone());
            let s3_client = match config.take_s3_client_source() {
                crate::config::S3ClientSource::Provided(client) => client,
                crate::config::S3ClientSource::FromConfig(s3_config) => {
                    aws_sdk_s3::Client::from_conf(s3_config.config)
                }
            };
            Self {
                config,
                s3_client,
                scheduler,
                runtime,
                controller,
                telemetry: Arc::new(Telemetry::new(std::time::Duration::from_millis(500))),
                buffer_pool,
                plan,
                retry_partitions: std::sync::Mutex::new(std::collections::HashMap::new()),
            }
        })
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        self.runtime.shutdown();
    }
}

impl Client {
    /// Returns a non-owning observer of managed-runtime shutdown completion.
    ///
    /// Returns `Some` for automatically created and adopted managed runtimes,
    /// and `None` for caller-owned Tokio execution. Retaining the observer does
    /// not keep this client or its runtime owner alive. Waiting does not request
    /// shutdown: release client clones and transfer ownership first.
    pub fn shutdown_completion(&self) -> Option<crate::ShutdownCompletion> {
        self.handle.runtime.shutdown_completion()
    }

    /// Creates a new client from a transfer manager config.
    ///
    /// # Panics
    ///
    /// Panics when a component the configuration selects cannot be constructed:
    ///
    /// - With the automatic memory configuration, the buffer pool cannot be
    ///   sized for this machine: the OS page size is unavailable or produces an
    ///   unsupported pool layout, or the detected memory is too small to hold
    ///   one buffer. An explicitly configured [`BufferPool`] reports these
    ///   conditions as errors from [`BufferPoolBuilder::build`] instead.
    /// - With managed execution, the managed runtime cannot be started, for
    ///   example because topology discovery fails or a managed thread cannot be
    ///   created or initialized.
    /// - With managed execution and no HTTP client configured on the S3
    ///   configuration, the default HTTP transport cannot be constructed.
    ///
    /// [`BufferPoolBuilder::build`]: crate::memory::BufferPoolBuilder::build
    pub fn new(mut config: Config) -> Client {
        // Machine facts for auto-sizing: use the loader-detected profile if the
        // config came through `ConfigLoader::load`, else detect locally (DMI +
        // vCPU + RAM — cheap pseudo-file reads, no network). Detected once and
        // shared by both the concurrency seed and the buffer pool.
        let profile = config
            .machine_profile()
            .cloned()
            .unwrap_or_else(crate::runtime::platform::MachineProfile::detect_local);

        let client_features = crate::config::user_agent::client_features(&config, &profile);

        let connection_cap = crate::runtime::platform::ConnectionCap::detect();
        let explicit_pool_ceiling = match config.memory() {
            MemoryConfig::Explicit(pool) => {
                Some(usize::try_from(pool.metrics().capacity_bytes()).unwrap_or(usize::MAX))
            }
            MemoryConfig::Auto => None,
        };
        let plan = sizing::resolve(Signals {
            throughput_gbps: config.throughput_target_gbps(),
            instance_type: profile.instance_type.as_deref(),
            vcpus: profile.vcpus,
            ram_bytes: profile.ram_bytes,
            connection_cap,
            explicit_concurrency: match config.concurrency() {
                ConcurrencyMode::Explicit(n) => Some(*n),
                ConcurrencyMode::Auto | ConcurrencyMode::TargetThroughput(_) => None,
            },
            explicit_part_size: match config.part_size() {
                PartSize::Target(n) => Some(n.as_u64()),
                PartSize::Auto => None,
            },
            ceiling_override_bytes: explicit_pool_ceiling,
        });

        let (controller, telemetry): (Arc<dyn ConcurrencyController>, _) = (
            Arc::new(FixedConcurrency::new(plan.concurrency)),
            Arc::new(Telemetry::new(Duration::from_millis(500))),
        );

        // 2. Build Handle with Arc::new_cyclic so scheduler and runtime
        //    can hold Weak<Handle> without creating a reference cycle.
        let memory_diagnostics = config.diagnostics().memory();
        let buffer_pool = match config.memory() {
            MemoryConfig::Auto => BufferPool::from_capacity(
                crate::config::MemoryBudgetConfig::Limit(ByteSize::new(plan.ceiling_bytes as u64)),
                profile.ram_bytes,
                memory_diagnostics,
            )
            .expect("memory configuration must resolve to supported pool geometry"),
            MemoryConfig::Explicit(pool) => pool.clone(),
        };
        // Runtime HTTP is built only when it will be installed on an S3 client
        // this transfer manager constructs.
        let runtime_http = config.runtime_http(plan.connection_cap);
        log_resource_sizing(&plan, &profile, &connection_cap, runtime_http.is_some());
        // wasm targets have no managed execution; see `Managed`.
        #[cfg(not(target_family = "wasm"))]
        let managed = match config.managed_config_mut() {
            Some(managed) => {
                let owner = managed
                    .build()
                    .expect("failed to construct transfer manager execution");
                let components = crate::runtime::prepare_components(&owner, runtime_http)
                    .expect("failed to construct transfer manager HTTP transport");
                Some((owner, components))
            }
            None => None,
        };
        let handle = Arc::new_cyclic(|weak_handle| {
            let scheduler = Scheduler::new(weak_handle.clone());
            #[cfg(not(target_family = "wasm"))]
            let runtime: Arc<dyn ExecutionRuntime> = match managed {
                Some((owner, components)) => Arc::new(ManagedExecution::new(
                    weak_handle.clone(),
                    owner,
                    components,
                )),
                None => Arc::new(crate::runtime::TokioMultiThreadRuntime::new(
                    weak_handle.clone(),
                )),
            };
            #[cfg(target_family = "wasm")]
            let runtime: Arc<dyn ExecutionRuntime> = Arc::new(
                crate::runtime::TokioMultiThreadRuntime::new(weak_handle.clone()),
            );

            let s3_client = match config.take_s3_client_source() {
                crate::config::S3ClientSource::Provided(client) => {
                    crate::config::user_agent::install_on_client(client, client_features)
                }
                crate::config::S3ClientSource::FromConfig(s3_config) => {
                    let mut builder = s3_config.config.to_builder();
                    if let Some(http_client) = runtime.components().http_client() {
                        builder = builder.http_client(http_client.clone());
                    }
                    crate::config::user_agent::install(&mut builder, client_features);
                    aws_sdk_s3::Client::from_conf(builder.build())
                }
            };

            Handle {
                config,
                s3_client,
                scheduler,
                runtime,
                controller,
                telemetry,
                buffer_pool,
                plan,
                retry_partitions: std::sync::Mutex::new(std::collections::HashMap::new()),
            }
        });
        Client { handle }
    }

    /// Returns the client's configuration
    pub fn config(&self) -> &Config {
        &self.handle.config
    }

    /// Returns point-in-time operational metrics for this client.
    pub fn metrics(&self) -> crate::metrics::ClientMetrics {
        crate::metrics::ClientMetrics::new(self.handle.buffer_pool.metrics())
    }

    /// Upload a single object to S3.
    ///
    /// Constructs a fluent builder for the
    /// [`Upload`](crate::operation::upload::builders::UploadFluentBuilder) operation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::error::Error;
    /// use std::path::Path;
    /// use aws_s3_transfer::io::InputStream;
    ///
    /// async fn upload_file(
    ///     client: &aws_s3_transfer::Client,
    ///     path: impl AsRef<Path>
    /// ) -> Result<(), Box<dyn Error>> {
    ///     let stream = InputStream::from_path(path)?;
    ///     let handle = client.upload()
    ///         .bucket("my-bucket")
    ///         .key("my-key")
    ///         .body(stream)
    ///         .initiate()?;
    ///
    ///     // initiate() will return before the transfer is complete.
    ///     // Call the `join()` method on the returned handle to drive the transfer to completion.
    ///     // The handle also reports status and metrics, adjusts scheduling, and aborts the transfer.
    ///     let response = handle.join().await?;
    ///     // ... do something with response
    ///     Ok(())
    /// }
    ///
    /// ```
    pub fn upload(&self) -> crate::operation::upload::builders::UploadFluentBuilder {
        crate::operation::upload::builders::UploadFluentBuilder::new(self.handle.clone())
    }

    /// Download a single object from S3.
    ///
    /// A single logical request may be split into many concurrent ranged `GetObject` requests
    /// to improve throughput.
    ///
    /// Constructs a fluent builder for the
    /// [`Download`](crate::operation::download::builders::DownloadFluentBuilder) operation.
    ///
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::error::Error;
    ///
    /// async fn get_object(client: &aws_s3_transfer::Client) -> Result<(), Box<dyn Error>> {
    ///
    ///     let handle = client
    ///         .download()
    ///         .bucket("my-bucket")
    ///         .key("my-key")
    ///         .initiate()?;
    ///
    ///     // initiate() will return before the transfer is complete.
    ///     // Call the `join()` method on the returned handle to drive the transfer to completion.
    ///     // The handle also exposes the object metadata and body, reports status and metrics,
    ///     // adjusts scheduling and read-ahead, and aborts the transfer.
    ///     let response = handle.join().await?;
    ///     // ... do something with response
    ///     Ok(())
    /// }
    /// ```
    pub fn download(&self) -> crate::operation::download::builders::DownloadFluentBuilder {
        crate::operation::download::builders::DownloadFluentBuilder::new(self.handle.clone())
    }

    /// Download multiple objects from an Amazon S3 bucket to a local directory
    ///
    /// Each object is written at its full key under the destination directory.
    /// The walker's prefix selects the objects and does not shorten their
    /// paths. See [`DownloadObjectsInput`](crate::operation::download_objects::DownloadObjectsInput)
    /// for how keys map to paths.
    ///
    /// Each object is written to a temporary file beside its destination path
    /// and renamed into place when that object's download succeeds, replacing
    /// any file already at that path. A successful `join` means the operating
    /// system accepted every byte of each downloaded object and completed each
    /// rename. The transfer manager does not call `sync_data` or `sync_all` on
    /// the files, or synchronize any directory, including the directories it
    /// creates, so success does not promise persistence across a system crash
    /// or power loss.
    ///
    /// Constructs a fluent builder for the
    /// [`DownloadObjects`](crate::operation::download_objects::builders::DownloadObjectsFluentBuilder) operation.
    ///
    /// # Examples
    /// ```no_run
    /// use std::path::PathBuf;
    /// use aws_s3_transfer::error::Error;
    /// use aws_s3_transfer::io::walk::S3Walker;
    ///
    /// async fn download_photos(
    ///     client: &aws_s3_transfer::Client,
    ///     dest: PathBuf
    /// ) -> Result<(), Error> {
    ///
    ///     let handle = client
    ///         .download_objects()
    ///         .bucket("my-bucket")
    ///         .walker(S3Walker::builder().prefix("photos/").build())
    ///         .destination(dest)
    ///         .initiate()?;
    ///
    ///     // wait for transfer to complete
    ///     handle.join().await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// ```
    pub fn download_objects(
        &self,
    ) -> crate::operation::download_objects::builders::DownloadObjectsFluentBuilder {
        crate::operation::download_objects::builders::DownloadObjectsFluentBuilder::new(
            self.handle.clone(),
        )
    }

    /// Upload multiple objects from a local directory to an Amazon S3 bucket
    ///
    /// Constructs a fluent builder for the
    /// [`UploadObjects`](crate::operation::upload_objects::builders::UploadObjectsFluentBuilder) operation.
    ///
    /// The default walk is not recursive: it uploads the regular files directly
    /// inside the source directory and skips subdirectories. To upload a
    /// directory tree, supply a walker built with
    /// [`FsWalker::builder().recursive(true)`](crate::io::walk::FsWalkerBuilder::recursive),
    /// as in the example below.
    ///
    /// Examples
    /// ```no_run
    /// use std::path::Path;
    /// use aws_s3_transfer::error::Error;
    /// use aws_s3_transfer::io::walk::FsWalker;
    ///
    /// async fn upload_directory(
    ///     client: &aws_s3_transfer::Client,
    ///     source: &Path,
    /// ) -> Result<(), Error> {
    ///
    ///     let handle = client
    ///         .upload_objects()
    ///         .source(source)
    ///         .bucket("my-bucket")
    ///         .walker(FsWalker::builder().recursive(true).build())
    ///         .initiate()?;
    ///
    ///     // wait for transfer to complete
    ///     handle.join().await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// ```
    pub fn upload_objects(
        &self,
    ) -> crate::operation::upload_objects::builders::UploadObjectsFluentBuilder {
        crate::operation::upload_objects::builders::UploadObjectsFluentBuilder::new(
            self.handle.clone(),
        )
    }
}

/// Logs the resolved sizing at `INFO`, a `WARN` when the part size exceeds the
/// memory ceiling, and a `WARN` when the descriptor limit holds connections per
/// host below the concurrency target.
///
/// `connection_cap_installed` is whether the cap is applied to a transport this
/// client builds.
fn log_resource_sizing(
    plan: &ResourcePlan,
    profile: &crate::runtime::platform::MachineProfile,
    cap: &crate::runtime::platform::ConnectionCap,
    connection_cap_installed: bool,
) {
    let soft = cap.descriptors.map(|limit| limit.soft);
    let hard = cap.descriptors.and_then(|limit| limit.hard);
    tracing::info!(
        target: crate::telemetry::TARGET_CONCURRENCY,
        concurrency_target = plan.concurrency,
        source = plan.concurrency_source.as_str(),
        throughput_gbps = ?plan.throughput_gbps,
        instance_type = ?profile.instance_type,
        vcpus = profile.vcpus,
        memory_ceiling_bytes = plan.ceiling_bytes,
        memory_detected = plan.memory_detected,
        part_size_bytes = plan.part_size,
        max_connections_per_host = plan.connection_cap,
        connection_cap_installed,
        soft_descriptor_limit = ?soft,
        hard_descriptor_limit = ?hard,
        "resolved resource sizing",
    );

    if plan.part_exceeds_ceiling {
        tracing::warn!(
            target: crate::telemetry::TARGET_CONCURRENCY,
            part_size_bytes = plan.part_size,
            memory_ceiling_bytes = plan.ceiling_bytes,
            "part size exceeds the payload-memory ceiling, so transfers that use it fail; raise \
             the memory ceiling or lower the part size",
        );
    }

    if cap.limited_by_descriptors() && plan.concurrency > plan.connection_cap {
        if connection_cap_installed {
            tracing::warn!(
                target: crate::telemetry::TARGET_CONCURRENCY,
                max_connections_per_host = plan.connection_cap,
                concurrency_target = plan.concurrency,
                soft_descriptor_limit = ?soft,
                hard_descriptor_limit = ?hard,
                "the soft file-descriptor limit (RLIMIT_NOFILE) caps connections per host below \
                 the concurrency target; requests beyond the cap wait for a connection. Raise the \
                 soft limit to allow more connections",
            );
        } else {
            tracing::warn!(
                target: crate::telemetry::TARGET_CONCURRENCY,
                max_connections_per_host = plan.connection_cap,
                concurrency_target = plan.concurrency,
                soft_descriptor_limit = ?soft,
                hard_descriptor_limit = ?hard,
                "the soft file-descriptor limit (RLIMIT_NOFILE) allows fewer connections per host \
                 than the concurrency target; the supplied HTTP client is not capped by the \
                 transfer manager and may fail to open connections past the limit. Raise the soft \
                 limit or lower the concurrency target",
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::RuntimeConfig;
    use aws_smithy_runtime_api::client::http::SharedHttpClient;

    fn test_config() -> crate::Config {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config")
    }

    fn runtime_http_client(client: &Client) -> Option<&SharedHttpClient> {
        client.handle.runtime.components().http_client()
    }

    /// A configured transport that polls file bodies on a plain thread,
    /// retries the first PUT, and lets the test hold an active transfer.
    #[derive(Debug)]
    struct ThreadHttp {
        started: Arc<tokio::sync::Semaphore>,
        release: Arc<tokio::sync::Semaphore>,
        bodies: Arc<std::sync::Mutex<Vec<Vec<u8>>>>,
        execution: Option<aws_smithy_execution::ManagedRuntimeHandle>,
        dispatches: Arc<std::sync::Mutex<Vec<aws_smithy_execution::RuntimePartitionId>>>,
    }

    impl aws_smithy_runtime_api::client::http::HttpConnector for ThreadHttp {
        fn call(
            &self,
            request: aws_smithy_runtime_api::client::orchestrator::HttpRequest,
        ) -> aws_smithy_runtime_api::client::http::HttpConnectorFuture {
            use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
            use aws_smithy_types::body::SdkBody;
            use http_body_1x::Body;
            use std::pin::Pin;

            assert_eq!(request.method(), "PUT");
            if let Some(execution) = &self.execution {
                let partition = execution
                    .current_partition()
                    .expect("transfer must execute on the adopted runtime");
                self.dispatches.lock().unwrap().push(partition.id());
            }
            let started = self.started.clone();
            let release = self.release.clone();
            let bodies = self.bodies.clone();
            let (completed, result) = tokio::sync::oneshot::channel();
            std::thread::spawn(move || {
                assert!(tokio::runtime::Handle::try_current().is_err());
                let response = crate::runtime::test_util::block_on(async move {
                    let first = bodies.lock().unwrap().is_empty();
                    if first {
                        started.add_permits(1);
                        release.acquire().await.unwrap().forget();
                    }
                    let mut body = request.into_body();
                    let mut bytes = Vec::new();
                    while let Some(frame) =
                        futures_util::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await
                    {
                        if let Ok(data) = frame.unwrap().into_data() {
                            bytes.extend_from_slice(&data);
                        }
                    }
                    bodies.lock().unwrap().push(bytes);
                    HttpResponse::try_from(
                        ::http::Response::builder()
                            .status(if first { 500 } else { 200 })
                            .header("etag", "\"test-etag\"")
                            .body(SdkBody::empty())
                            .unwrap(),
                    )
                    .unwrap()
                });
                let _ = completed.send(response);
            });
            aws_smithy_runtime_api::client::http::HttpConnectorFuture::new(async move {
                Ok(result.await.unwrap())
            })
        }
    }

    // Real SDK requests, body replay, and owner retention are exercised together:
    // the configured HTTP implementation polls outside managed execution.
    #[cfg_attr(miri, ignore)]
    #[test]
    fn configured_sdk_http_uploads_files_and_retains_active_execution() {
        use aws_sdk_s3::config::{Credentials, Region, SharedCredentialsProvider};
        use aws_smithy_runtime_api::client::http::{http_client_fn, SharedHttpConnector};
        use std::io::Write;

        let caller = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let mut file = tempfile::NamedTempFile::new().unwrap();
        let payload = vec![0x5a; 128 * 1024];
        file.write_all(&payload).unwrap();
        let mut checksum = aws_smithy_checksums::ChecksumAlgorithm::Crc32.into_impl();
        checksum.update(&payload);
        let checksum = checksum.header_value().to_str().unwrap().to_owned();

        let adopted: Option<(
            RuntimeConfig,
            bool,
            Option<aws_smithy_execution::ManagedRuntimeHandle>,
        )> = {
            #[cfg(feature = "__unstable_ext")]
            {
                let owner = aws_smithy_execution::ManagedRuntime::builder()
                    .topology(
                        aws_smithy_execution::topology::Topology::detect()
                            .unwrap()
                            .with_max_placements(1),
                    )
                    .thread_name_prefix("adopted-upload")
                    .pin_threads(false)
                    .build()
                    .unwrap();
                let execution = owner.handle();
                Some((
                    RuntimeConfig::managed(crate::unstable::managed(owner)),
                    true,
                    Some(execution),
                ))
            }
            #[cfg(not(feature = "__unstable_ext"))]
            {
                None
            }
        };
        for (runtime, managed, adopted) in [
            (RuntimeConfig::default(), true, None),
            (RuntimeConfig::multi_thread_tokio(), false, None),
        ]
        .into_iter()
        .chain(adopted)
        {
            caller.block_on(async {
                let started = Arc::new(tokio::sync::Semaphore::new(0));
                let release = Arc::new(tokio::sync::Semaphore::new(0));
                let bodies = Arc::new(std::sync::Mutex::new(Vec::new()));
                let dispatches = Arc::new(std::sync::Mutex::new(Vec::new()));
                let owner_watch = adopted
                    .as_ref()
                    .map(|execution| execution.partitions()[0].spawn(std::future::pending::<()>()));
                let connector = SharedHttpConnector::new(ThreadHttp {
                    started: started.clone(),
                    release: release.clone(),
                    bodies: bodies.clone(),
                    execution: adopted.clone(),
                    dispatches: dispatches.clone(),
                });
                let sdk = aws_types::SdkConfig::builder()
                    .http_client(http_client_fn(move |_, _| connector.clone()))
                    .region(Region::new("us-west-2"))
                    .credentials_provider(SharedCredentialsProvider::new(Credentials::new(
                        "test", "test", None, None, "test",
                    )))
                    .behavior_version(aws_config::BehaviorVersion::latest())
                    .build();
                let client = Client::new(
                    crate::Config::builder()
                        .s3_config(&sdk)
                        .runtime_config(runtime)
                        .build()
                        .expect("valid config"),
                );
                let components = client.handle.runtime.components();
                assert!(
                    components.http_client().is_none(),
                    "unused managed HTTP must not be built"
                );
                assert_eq!(components.direct_io(), managed);
                assert!(
                    !components.direct_body_io(),
                    "configured HTTP controls its polling thread"
                );

                let completion = client.shutdown_completion();
                assert_eq!(completion.is_some(), managed);
                let weak = Arc::downgrade(&client.handle);
                let upload = client
                    .upload()
                    .bucket("test-bucket")
                    .key("file")
                    .checksum_strategy(
                        crate::types::ChecksumStrategy::full_object(crate::types::checksum::Crc32)
                            .with_expected_value(&checksum),
                    )
                    .body(crate::io::InputStream::from_path(file.path()).unwrap())
                    .initiate()
                    .unwrap();
                tokio::time::timeout(Duration::from_secs(5), started.acquire())
                    .await
                    .unwrap()
                    .unwrap()
                    .forget();
                drop(client);
                assert!(
                    weak.upgrade().is_some(),
                    "active transfer retains execution owner"
                );
                release.add_permits(1);
                let output = tokio::time::timeout(Duration::from_secs(10), upload.join())
                    .await
                    .unwrap()
                    .unwrap();
                assert!(
                    output.upload_id().is_none(),
                    "exercise single-PUT file body"
                );
                {
                    let captured = bodies.lock().unwrap();
                    assert_eq!(captured.len(), 2, "SDK retries the first PUT");
                    assert!(
                        captured.iter().all(|body| body == &payload),
                        "both attempts replay the file"
                    );
                }
                if let Some(execution) = &adopted {
                    let observed = dispatches.lock().unwrap();
                    assert_eq!(observed.len(), 2);
                    assert!(observed.iter().all(|id| id.runtime_id() == execution.id()));
                }
                tokio::time::timeout(Duration::from_secs(5), async {
                    // Terminal notification can precede the last work item's
                    // retirement.
                    while weak.upgrade().is_some() {
                        tokio::task::yield_now().await;
                    }
                })
                .await
                .unwrap_or_else(|_| {
                    panic!("finished transfer retains execution (managed={managed})")
                });
                if let Some(completion) = completion {
                    tokio::time::timeout(Duration::from_secs(5), completion.wait())
                        .await
                        .unwrap()
                        .unwrap();
                }
                if let Some(watch) = owner_watch {
                    let error = tokio::time::timeout(Duration::from_secs(5), watch)
                        .await
                        .unwrap()
                        .unwrap_err();
                    assert!(
                        error.is_cancelled(),
                        "retained handles must not retain ownership"
                    );
                }
            });
        }
    }

    #[cfg(all(feature = "__unstable_ext", not(miri)))]
    #[tokio::test]
    async fn adopted_runtime_without_configured_http_uses_the_managed_preset() {
        let owner = aws_smithy_execution::ManagedRuntime::builder()
            .topology(
                aws_smithy_execution::topology::Topology::detect()
                    .unwrap()
                    .with_max_placements(1),
            )
            .pin_threads(false)
            .build()
            .unwrap();
        let execution = owner.handle();
        let watch = execution.partitions()[0].spawn(std::future::pending::<()>());
        let mut s3 = mock_s3_config().config.to_builder();
        s3.set_http_client(None);
        let client = Client::new(
            crate::Config::builder()
                .s3_config(crate::config::S3ClientConfig::from_sdk_builder(s3))
                .runtime_config(RuntimeConfig::managed(crate::unstable::managed(owner)))
                .build()
                .expect("valid config"),
        );
        assert!(client
            .handle
            .config
            .runtime_config()
            .managed_config()
            .is_some());
        let components = client.handle.runtime.components();
        assert!(components.http_client().is_some());
        assert!(components.direct_io());
        assert!(components.direct_body_io());
        assert_eq!(
            execution.partitions()[0].spawn(async { 42 }).await.unwrap(),
            42,
        );
        drop(client);
        assert!(tokio::time::timeout(Duration::from_secs(5), watch)
            .await
            .unwrap()
            .unwrap_err()
            .is_cancelled());
    }

    #[cfg(all(
        feature = "__unstable_ext",
        not(miri),
        any(
            target_os = "android",
            target_os = "fuchsia",
            target_os = "illumos",
            target_os = "ios",
            target_os = "linux",
            target_os = "macos",
            target_os = "solaris",
            target_os = "tvos",
            target_os = "visionos",
            target_os = "watchos",
        )
    ))]
    #[tokio::test]
    async fn transport_construction_failure_drops_the_adopted_owner() {
        let owner = aws_smithy_execution::ManagedRuntime::builder()
            .topology(
                aws_smithy_execution::topology::Topology::detect()
                    .unwrap()
                    .with_max_placements(1),
            )
            .pin_threads(false)
            .build()
            .unwrap();
        let execution = owner.handle();
        let watch = execution.partitions()[0].spawn(std::future::pending::<()>());
        let mut s3 = mock_s3_config().config.to_builder();
        s3.set_http_client(None);
        let mut config = crate::Config::builder()
            .s3_config(crate::config::S3ClientConfig::from_sdk_builder(s3))
            .runtime_config(RuntimeConfig::managed(crate::unstable::managed(owner)))
            .build()
            .expect("valid config");
        // A NUL byte cannot be passed to the OS as an interface name, so building
        // the transport fails after the runtime owner has been adopted.
        config.network_interfaces = vec!["bad\0interface".to_owned()];
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Client::new(config)));
        assert!(result.is_err());
        assert!(tokio::time::timeout(Duration::from_secs(5), watch)
            .await
            .unwrap()
            .unwrap_err()
            .is_cancelled());
    }

    #[cfg_attr(miri, ignore)]
    #[test]
    fn shared_tokio_without_configured_http_uses_sdk_defaults() {
        let mut s3 = mock_s3_config().config.to_builder();
        s3.set_http_client(None);
        let client = Client::new(
            crate::Config::builder()
                .s3_config(crate::config::S3ClientConfig::from_sdk_builder(s3))
                .runtime_config(RuntimeConfig::multi_thread_tokio())
                .build()
                .expect("valid config"),
        );
        let components = client.handle.runtime.components();
        assert!(components.http_client().is_none());
        assert!(!components.direct_io());
        assert!(!components.direct_body_io());
    }

    fn mock_s3_config() -> crate::config::S3ClientConfig {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        crate::config::S3ClientConfig::from_sdk_builder(s3_client.config().to_builder())
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn managed_runtime_builds_http_for_s3_config() {
        let mut builder = mock_s3_config().config.to_builder();
        builder.set_http_client(None);
        let client = Client::new(
            crate::Config::builder()
                .s3_config(crate::config::S3ClientConfig::from_sdk_builder(builder))
                .build()
                .expect("valid config"),
        );
        assert!(runtime_http_client(&client).is_some());
        assert!(client.handle.runtime.components().direct_io());
        assert!(client.handle.runtime.components().direct_body_io());
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn managed_runtime_skips_http_for_provided_client() {
        let client = Client::new(test_config());
        assert!(runtime_http_client(&client).is_none());
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn managed_runtime_preserves_configured_http() {
        let config = crate::Config::builder()
            .s3_config(mock_s3_config())
            .build()
            .expect("valid config");
        let client = Client::new(config);
        assert!(runtime_http_client(&client).is_none());
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn handle_drop_shuts_down_runtime() {
        let handle = Handle::new_for_test(test_config(), 2);
        let weak = Arc::downgrade(&handle);
        drop(handle);
        assert!(weak.upgrade().is_none(), "Handle should be fully dropped");
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn client_clone_shares_handle() {
        let client = Client::new(test_config());
        let client2 = client.clone();
        assert!(Arc::ptr_eq(&client.handle, &client2.handle));
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_client_uses_the_explicit_buffer_pool() {
        let pool = BufferPool::from_capacity(
            crate::config::MemoryBudgetConfig::Limit(ByteSize::mib(16)),
            None,
            crate::config::MemoryDiagnosticsConfig::default(),
        )
        .unwrap();
        let carrier_size = pool.carrier_size();
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .memory(MemoryConfig::Explicit(pool.clone()))
            .build()
            .expect("valid config");

        let client = Client::new(config);
        let reservation = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("explicit pool reservation");

        let client_metrics = client.metrics();
        let memory = client_metrics.memory();
        assert_eq!(memory.active_planned_demand_bytes(), carrier_size as u64);
        assert_eq!(memory.capacity_bytes(), pool.metrics().capacity_bytes());
        drop(reservation);
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_client_automatic_pool_starts_unprepared() {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .machine_profile(Some(crate::runtime::platform::MachineProfile {
                instance_type: None,
                vcpus: 4,
                ram_bytes: Some(ByteSize::mib(512).as_usize()),
            }))
            .build()
            .expect("valid config");
        let client = Client::new(config);
        let client_metrics = client.metrics();
        let memory = client_metrics.memory();

        assert!(memory.capacity_bytes() > 0);
        assert_eq!(memory.admitted_bytes(), 0);
        assert_eq!(memory.prepared_capacity_bytes(), 0);
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn test_handle_test_constructor_preserves_an_explicit_pool() {
        let pool = BufferPool::from_capacity(
            crate::config::MemoryBudgetConfig::Limit(ByteSize::mib(16)),
            None,
            crate::config::MemoryDiagnosticsConfig::default(),
        )
        .unwrap();
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .memory(MemoryConfig::Explicit(pool.clone()))
            .build()
            .expect("valid config");

        let handle = Handle::new_for_test(config, 2);
        let reservation = pool
            .try_reserve(pool.carrier_size())
            .unwrap()
            .expect("explicit pool reservation");

        assert_eq!(
            handle.buffer_pool.metrics().active_planned_demand_bytes(),
            pool.carrier_size() as u64
        );
        drop(reservation);
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn last_client_drop_releases_handle() {
        let client = Client::new(test_config());
        let weak = Arc::downgrade(&client.handle);
        let client2 = client.clone();
        drop(client);
        assert!(
            weak.upgrade().is_some(),
            "Handle alive while client2 exists"
        );
        drop(client2);
        assert!(weak.upgrade().is_none(), "Handle dropped after last client");
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn handle_drop_invalidates_weak_references() {
        let handle = Handle::new_for_test(test_config(), 2);
        let weak = Arc::downgrade(&handle);
        drop(handle);
        assert!(
            weak.upgrade().is_none(),
            "Weak should be invalid after Handle drop"
        );
    }

    // --- concurrency resolution wiring ---

    use crate::config::ConcurrencyMode;
    use crate::runtime::platform::{self, MachineProfile};

    /// A profile with the given instance type and vCPU count, and no detected
    /// memory, so the ceiling is the no-detection fallback.
    fn profile(instance_type: Option<&str>, vcpus: usize) -> MachineProfile {
        MachineProfile {
            instance_type: instance_type.map(str::to_string),
            vcpus,
            ram_bytes: None,
        }
    }

    fn config_with(mode: ConcurrencyMode, profile: Option<MachineProfile>) -> crate::Config {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        crate::config::Config::builder()
            .sdk_client(s3_client)
            .concurrency(mode)
            .machine_profile(profile)
            .build()
            .expect("valid config")
    }

    // FIXME: crossbeam-epoch is incompatible with miri
    #[cfg_attr(miri, ignore)]
    #[test]
    fn client_new_wires_resolved_target_into_controller() {
        // The resolved target is the controller's target. Expected values come
        // from the pass because the descriptor cap depends on RLIMIT_NOFILE.
        let p = profile(Some("c8gn.16xlarge"), 64);
        let expected = sizing::resolve(Signals {
            throughput_gbps: None,
            instance_type: p.instance_type.as_deref(),
            vcpus: p.vcpus,
            ram_bytes: p.ram_bytes,
            connection_cap: platform::ConnectionCap::detect(),
            explicit_concurrency: None,
            explicit_part_size: None,
            ceiling_override_bytes: None,
        });

        let client = Client::new(config_with(ConcurrencyMode::Auto, Some(p)));

        assert_eq!(client.handle.controller.target(), expected.concurrency);
        assert_eq!(client.handle.part_size_bytes(), expected.part_size);
    }

    // FIXME: crossbeam-epoch is incompatible with miri
    #[cfg_attr(miri, ignore)]
    #[test]
    fn client_new_sizes_an_automatic_pool_from_the_resolved_ceiling() {
        // `MemoryConfig::Auto` uses the resolved ceiling.
        let p = profile(None, 4);
        let config = crate::config::Config::builder()
            .sdk_client(aws_smithy_mocks::mock_client!(aws_sdk_s3, []))
            .machine_profile(Some(p))
            .build()
            .expect("valid config");

        let client = Client::new(config);
        let configured = client.handle.buffer_pool.metrics().capacity_bytes();

        // Carrier rounding can only round the ceiling down, never above it.
        assert!(configured <= client.handle.plan.ceiling_bytes as u64);
        assert!(configured > 0);
    }

    // FIXME: crossbeam-epoch is incompatible with miri
    #[cfg_attr(miri, ignore)]
    #[test]
    fn configured_throughput_drives_the_resolved_target() {
        // A throughput target sets the controller's target.
        let client = Client::new(config_with(
            ConcurrencyMode::TargetThroughput(
                crate::config::TargetThroughput::gbps(100.0).unwrap(),
            ),
            Some(profile(None, 4)),
        ));

        // Expected value from the pass, which seeds the target from 100 Gbps.
        let expected = sizing::resolve(Signals {
            throughput_gbps: Some(100.0),
            instance_type: None,
            vcpus: 4,
            ram_bytes: None,
            connection_cap: platform::ConnectionCap::detect(),
            explicit_concurrency: None,
            explicit_part_size: None,
            ceiling_override_bytes: None,
        });
        assert_eq!(client.handle.controller.target(), expected.concurrency);
        assert_eq!(client.handle.plan.throughput_gbps, Some(100.0));
    }

    // FIXME: crossbeam-epoch is incompatible with miri
    #[cfg_attr(miri, ignore)]
    #[test]
    fn client_new_bypass_path_detects_locally() {
        // Without a profile on the config, Client::new detects locally. Off EC2
        // no instance type is detected, so the target is resolved from the
        // local vCPU count and memory, which the expected plan reads the same
        // way.
        let expected = sizing::resolve(Signals {
            throughput_gbps: None,
            instance_type: None,
            vcpus: platform::local_vcpus(),
            ram_bytes: platform::available_ram(),
            connection_cap: platform::ConnectionCap::detect(),
            explicit_concurrency: None,
            explicit_part_size: None,
            ceiling_override_bytes: None,
        });
        let client = Client::new(config_with(ConcurrencyMode::Auto, None));
        assert_eq!(client.handle.controller.target(), expected.concurrency);
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn retry_partition_is_cached_per_bucket() {
        // The retry partition (and its refilling token bucket) must be built once
        // per bucket and reused, not rebuilt per operation — a fresh partition
        // would carry a fresh full bucket, defeating the shared budget and refill.
        // The map is the observable of that reuse: repeated calls for one bucket
        // add exactly one entry, and distinct buckets each add their own. A
        // build-fresh-per-call regression never populates the map (stays empty).
        let handle = Handle::new_for_test(test_config(), 2);

        // Same bucket, three calls: one cache entry, populated once.
        for _ in 0..3 {
            let _ = handle.bucket_partition_override(Some("bucket-a"));
        }
        assert_eq!(
            handle.retry_partitions.lock().unwrap().len(),
            1,
            "repeated calls for one bucket must reuse a single cached partition"
        );

        // A second bucket adds its own entry; `None` adds nothing.
        let _ = handle.bucket_partition_override(Some("bucket-b"));
        let _ = handle.bucket_partition_override(None);
        let map = handle.retry_partitions.lock().unwrap();
        assert_eq!(map.len(), 2, "each distinct bucket caches one partition");
        assert!(map.contains_key("bucket-a") && map.contains_key("bucket-b"));
    }

    // --- runtime mode selection ---

    #[test]
    fn config_default_runtime_is_managed() {
        let config = config_with(ConcurrencyMode::Auto, None);
        assert!(config.runtime_config().managed_config().is_some());
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[test]
    fn client_new_with_managed_runtime() {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .runtime_config(RuntimeConfig::default())
            .build()
            .expect("valid config");
        let _client = Client::new(config);
    }

    // FIXME: crossbeam-epoch is incompatible with miri (https://github.com/crossbeam-rs/crossbeam/issues/1181)
    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread")]
    async fn client_new_with_multi_thread_tokio_runtime() {
        let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .runtime_config(RuntimeConfig::multi_thread_tokio())
            .build()
            .expect("valid config");
        let _client = Client::new(config);
    }
}