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

//! Transfer types that define what a transfer is and what it produces.

mod composite;
mod pending;

use crate::config::user_agent::OperationFeatures;
use crate::error;
use crate::scheduler::concurrency::ErrorKind;
use std::any::Any;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Wake, Waker};

pub(crate) use composite::{CompositePendingReason, CompositeTransferSummary};
use pending::TransferPendingState;
pub(crate) use pending::{
    emit_pending_details, PendingCategory, PendingCause, TransferPendingStats,
};

/// Edge-triggered wake flag for transfer state machines.
///
/// Scoped to a sub-module so the underlying atomic is sourced from the
/// `runtime/sync` compat layer (loom under `cfg(s3_tm_loom)`, std otherwise)
/// without forcing the rest of this file's atomics onto the same path.
///
/// See [`TransferContext::set_pending`] for the wake primitive protocol —
/// the discipline the poller and mutator must follow to avoid lost wakes.
pub(crate) mod wake_flag {
    use crate::runtime::sync::sync::atomic::{AtomicBool, Ordering};

    pub(crate) struct WakeFlag {
        pending: AtomicBool,
    }

    impl WakeFlag {
        pub(crate) fn new() -> Self {
            Self {
                pending: AtomicBool::new(false),
            }
        }

        /// Set the pending flag.
        pub(crate) fn set_pending(&self) {
            self.pending.store(true, Ordering::Release);
        }

        /// Atomically clear the flag and return whether it was set.
        pub(crate) fn take_pending(&self) -> bool {
            self.pending.swap(false, Ordering::AcqRel)
        }
    }
}

/// A transfer operation that the scheduler polls for work and the runtime executes.
///
/// Each transfer (upload, download) is a state machine that produces IO requests
/// on demand via `poll_work()` and executes them via `execute()`. The scheduler
/// calls `poll_work()` when capacity is available; the runtime calls `execute()`
/// on whatever thread or executor it manages.
///
/// # Contracts
///
/// Implementations must uphold:
/// - **Failed lifecycle**: record the error before returning `WorkOutcome::Failed`.
///   Then either end the transfer and signal termination, or keep it active
///   with a wake path so `poll_work` drives it to an end (an upload aborts
///   its multipart upload first).
/// - **Pending/wake obligation**: every `PollWork::Pending` must first call
///   `ctx.set_pending(cause)` and have a future wake path. See
///   [`TransferContext`] for the wake primitive protocol.
/// - **Panic safety**: `execute` panics are caught by the runtime's
///   `catch_unwind` wrapper and converted to a terminal transition. `poll_work`
///   panics are caught by the scheduler inside `generate_work`, which
///   force-terminates the panicking transfer (cascading to children).
///   Implementations SHOULD NOT rely on panic recovery — a caught panic still
///   corrupts the transfer's internal state and forces termination.
///
/// # Per-method expectations
///
/// ## `poll_work` — synchronous, short, bounded
/// - No `.await`, no blocking I/O, no unbounded loops.
/// - Cost is O(1) per call with a bounded critical section on state. Long
///   `poll_work` calls pin the caller's runtime and starve its other async tasks.
/// - At most one thread is inside `poll_work` for a given transfer at a time
///   (scheduler-enforced). Per-transfer state mutexes are therefore
///   effectively uncontended in steady state.
/// - Composite transfers whose `poll_work` recursively calls
///   `scheduler.enqueue_transfer` to spawn children must bound the per-call
///   fan-out: cost becomes `O(batch × enqueue_cost)` and a single unbounded
///   call can starve the rest of the scheduler.
///
/// ## `execute` — the async surface
/// - The only place `.await` is permitted. All blocking or long-running work
///   belongs here.
/// - State locks MUST NOT be held across `.await`. Acquire the lock, mutate,
///   drop it, then await.
/// - May call `scheduler.wake(id)` (via `ctx.try_wake()`) mid-execution to
///   re-queue the transfer if intra-execute state changes unblock work.
/// - The concurrency slot is held for the duration of this future; the
///   scheduler only decrements its dispatched counter after `execute` returns.
/// - Cancelling the transfer drops this future at its next `.await`. State
///   visible to other work or to the handle must be consistent at every
///   `.await` point.
///
/// ## `on_terminal` — external termination hook
/// - Called from outside the normal lifecycle (panic, cancellation, drop) to
///   let the transfer release held resources and notify waiters.
/// - Must be short and must not block.
pub(crate) trait Transfer: Send + Sync + std::fmt::Debug {
    /// The transfer's shared context (id, handle, status).
    fn ctx(&self) -> &TransferContext;

    /// Poll for the next IO request. Returns `Ready` with work, `Pending` if
    /// blocked, or `Done` when all work has been generated.
    ///
    /// See the trait-level "Per-method expectations" for the cost and threading
    /// contracts this call must respect.
    fn poll_work(&self) -> PollWork;

    /// Execute an IO request. Called by the runtime, not the scheduler.
    ///
    /// The only async surface on a transfer. State locks must not be held
    /// across `.await` points.
    fn execute<'a>(
        &'a self,
        work: &'a mut IoRequest,
    ) -> Pin<Box<dyn Future<Output = WorkOutcome> + Send + 'a>>;

    /// Called when the transfer is forced into a terminal state from outside
    /// (e.g. worker panic, external cancellation). Allows the transfer to
    /// clean up resources and notify waiters that would otherwise block
    /// indefinitely.
    ///
    /// Must be short and non-blocking.
    fn on_terminal(&self) {}
}

pub(crate) type BoxTransfer = Box<dyn Transfer>;

/// Opaque work data carried by work items. Each state machine defines its own type.
/// The scheduler never inspects this; it ferries it across the scheduling boundary
/// for the transfer to reclaim via `IoRequest::data_mut::<T>()`.
pub(crate) trait WorkData: Any + Send + std::fmt::Debug {
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl<T: Any + Send + std::fmt::Debug> WorkData for T {
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Unique identifier for a transfer, with optional parent for hierarchy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct TransferId {
    pub(crate) id: u64,
    pub(crate) parent: Option<u64>,
}

impl std::fmt::Display for TransferId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.parent {
            Some(parent) => write!(f, "{}-{}", self.id, parent),
            None => write!(f, "{}", self.id),
        }
    }
}

/// A unit of I/O to be scheduled and executed by the runtime.
#[derive(Debug)]
pub(crate) struct IoRequest {
    pub(crate) data: Option<Box<dyn WorkData>>,
}

impl IoRequest {
    /// Downcast data to a concrete type. Panics if wrong type or None.
    pub(crate) fn data_mut<T: 'static>(&mut self) -> &mut T {
        (**self.data.as_mut().expect("work item has no data"))
            .as_any_mut()
            .downcast_mut::<T>()
            .expect("work data type mismatch")
    }

    /// Take the data as a concrete type, leaving the request without data.
    /// For work whose payload `execute` consumes. Panics if wrong type or None.
    pub(crate) fn take_data<T: 'static>(&mut self) -> T {
        let data: Box<dyn Any> = self.data.take().expect("work item has no data");
        *data.downcast::<T>().expect("work data type mismatch")
    }
}

/// Result of polling a transfer for work.
#[derive(Debug)]
pub(crate) enum PollWork {
    /// Work is available to execute.
    ///
    /// `spawned` records whether this same poll ALSO spawned a child (a
    /// composite that reaped terminal children and refilled in one turn). When
    /// true, the scheduler dispatches `io` as usual (one dispatch ticket, full
    /// `work_generated`) AND additionally charges one spawn's reduced vruntime
    /// ([`work_generated_spawn`]) -- WITHOUT an extra dispatch ticket, since the
    /// spawned child accounts for itself when later polled (the `Spawned`
    /// contract). It is a bool, not a count: single-ticket spawning means a poll
    /// spawns at most one child. Non-composite transfers always set it false;
    /// use [`PollWork::ready`] for that common case.
    ///
    /// Fusing reap and spawn into one poll lets a composite retire a terminal
    /// child and spawn its replacement in the same turn instead of alternating
    /// turns, so a continuous completion stream cannot starve refill by
    /// monopolizing the parent's poll turns with reaping.
    ///
    /// [`work_generated_spawn`]: crate::scheduler::descriptor::TransferDescriptor::work_generated_spawn
    Ready { io: IoRequest, spawned: bool },
    /// The transfer enqueued one child transfer into the scheduler this poll. It
    /// produced no dispatchable `IoRequest` and is not blocked: re-poll while
    /// capacity remains (next poll may spawn again, block, or complete). Distinct
    /// from `Ready` (which carries a work item and consumes a dispatch ticket) --
    /// `Spawned` dispatches nothing and does not count against the concurrency
    /// target; the spawned child accounts for itself when it is later polled. The
    /// scheduler charges spawn vruntime (the reduced [`work_generated_spawn`]
    /// cost) so a composite parent stays scheduling-competitive with its
    /// children.
    ///
    /// [`work_generated_spawn`]: crate::scheduler::descriptor::TransferDescriptor::work_generated_spawn
    Spawned,
    /// Transfer is blocked waiting for in-flight work to complete.
    /// Scheduler should not poll again until `wake(transfer_id)` is called.
    Pending,
    /// Transfer has completed all work.
    Done,
}

impl PollWork {
    /// Construct a `Ready` that dispatched work but did not spawn a child --
    /// the common case for non-composite transfers and for composite polls that
    /// only reaped. Equivalent to `Ready { io, spawned: false }`.
    pub(crate) fn ready(io: IoRequest) -> Self {
        PollWork::Ready { io, spawned: false }
    }
}

/// How a work item's execution ended. Each variant states what the transfer guarantees in
/// returning it.
pub(crate) enum WorkOutcome {
    /// Work completed successfully.
    Success { data: Option<Box<dyn WorkData>> },
    /// The work ended without completing an I/O operation or reporting a failure, and the
    /// transfer continues. Unlike every other outcome, it is not a completion for the concurrency
    /// controller.
    ///
    /// The transfer has reconciled the work exactly once. A continuation it kept retains the
    /// work's progress and a future wake path; otherwise the operation was retracted or retired.
    Yielded,
    /// The work failed, and the transfer recorded the error.
    ///
    /// The transfer has ended, or stays active with a wake path to its end; see the Failed
    /// lifecycle contract on [`Transfer`]. `classification` is the error's kind, if it has one.
    Failed { classification: Option<ErrorKind> },
    /// The work was skipped, or stood down without an error of its own, because the transfer is
    /// ending or has ended.
    Cancelled,
}

impl std::fmt::Debug for WorkOutcome {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorkOutcome::Success { data } => f
                .debug_struct("Success")
                .field("has_data", &data.is_some())
                .finish(),
            WorkOutcome::Yielded => write!(f, "Yielded"),
            WorkOutcome::Failed { classification } => f
                .debug_struct("Failed")
                .field("classification", classification)
                .finish(),
            WorkOutcome::Cancelled => write!(f, "Cancelled"),
        }
    }
}

static NEXT_TRANSFER_ID: AtomicU64 = AtomicU64::new(1);

pub(crate) fn next_transfer_id() -> TransferId {
    TransferId {
        id: NEXT_TRANSFER_ID.fetch_add(1, Ordering::Relaxed),
        parent: None,
    }
}

// Type aliases for state machine completion signal (one-to-one, state machine → handle)
pub(crate) type StateMachineTerminalSender = tokio::sync::oneshot::Sender<()>;
pub(crate) type StateMachineTerminalReceiver = tokio::sync::oneshot::Receiver<()>;

/// Transfer lifecycle status.
///
/// ## State Machine
///
/// ```text
///              ┌──────────┐
///  (enqueued)──►  Active  │
///              └────┬─────┘
///                   │
///      ┌────────────┼────────────┐
///      │            │            │
///      ▼            ▼            ▼
/// ┌──────────┐ ┌──────────┐ ┌───────────┐
/// │Completed │ │  Failed  │ │ Cancelled │
/// └──────────┘ └──────────┘ └───────────┘
///
/// Terminal states: Completed, Failed, Cancelled
/// ```
///
/// ## Transitions
///
/// - `Active → Completed`: All work finished successfully, output available
/// - `Active → Failed`: A work item failed, error stored in context
/// - `Active → Cancelled`: User requested cancellation or handle dropped
///
/// ## First-Write-Wins Semantics
///
/// Only one transition from `Active` succeeds. Concurrent failures, cancellations,
/// or completion attempts race - the first one wins, others are no-ops.
///
/// ## Terminal State Signaling
///
/// After transitioning to a terminal state, call `signal_terminal()` to notify
/// waiters (e.g., `join()`). This signals "state machine has reached terminal
/// state" - in-flight work may still be completing/draining.
///
/// ## Data Availability
///
/// | Status    | Error Available | Output Available |
/// |-----------|-----------------|------------------|
/// | Active    | No              | No               |
/// | Completed | No              | Yes              |
/// | Failed    | Yes (take once) | No               |
/// | Cancelled | No              | No               |
#[derive(Clone)]
pub(crate) struct StateMachineStatus(Arc<AtomicU8>);

// Status constants
const STATUS_ACTIVE: u8 = 0;
const STATUS_COMPLETED: u8 = 1;
const STATUS_FAILED: u8 = 2;
const STATUS_CANCELLED: u8 = 3;

impl StateMachineStatus {
    /// Create a new status in the Active state
    #[inline]
    pub(crate) fn new() -> Self {
        Self(Arc::new(AtomicU8::new(STATUS_ACTIVE)))
    }

    /// Transition to Completed. Returns true if this call made the transition.
    #[inline]
    pub(crate) fn set_completed(&self) -> bool {
        self.0
            .compare_exchange(
                STATUS_ACTIVE,
                STATUS_COMPLETED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    /// Transition to Failed. Returns true if this call made the transition.
    #[inline]
    pub(crate) fn set_failed(&self) -> bool {
        self.0
            .compare_exchange(
                STATUS_ACTIVE,
                STATUS_FAILED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    /// Transition to Cancelled. Returns true if this call made the transition.
    #[inline]
    pub(crate) fn set_cancelled(&self) -> bool {
        self.0
            .compare_exchange(
                STATUS_ACTIVE,
                STATUS_CANCELLED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    #[inline]
    pub(crate) fn is_active(&self) -> bool {
        self.0.load(Ordering::Acquire) == STATUS_ACTIVE
    }

    #[inline]
    pub(crate) fn is_completed(&self) -> bool {
        self.0.load(Ordering::Acquire) == STATUS_COMPLETED
    }

    #[inline]
    pub(crate) fn is_failed(&self) -> bool {
        self.0.load(Ordering::Acquire) == STATUS_FAILED
    }

    #[inline]
    pub(crate) fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire) == STATUS_CANCELLED
    }

    fn as_str(&self) -> &'static str {
        match self.0.load(Ordering::Acquire) {
            STATUS_ACTIVE => "Active",
            STATUS_COMPLETED => "Completed",
            STATUS_FAILED => "Failed",
            STATUS_CANCELLED => "Cancelled",
            _ => "Unknown",
        }
    }
}

impl fmt::Display for StateMachineStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl fmt::Debug for StateMachineStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("StateMachineStatus")
            .field(&self.as_str())
            .finish()
    }
}

/// Per-transfer cumulative metrics.
pub(crate) struct MetricsState {
    network_tx: AtomicU64,
    network_rx: AtomicU64,
    disk_read: AtomicU64,
    disk_write: AtomicU64,
    total_bytes: std::sync::OnceLock<u64>,
    started_at: std::time::Instant,
    finished_at: std::sync::OnceLock<std::time::Instant>,
    terminal_reported: AtomicBool,
    request_metrics: crate::metrics::RequestMetricsState,
}

impl MetricsState {
    pub(crate) fn new() -> Self {
        Self {
            network_tx: AtomicU64::new(0),
            network_rx: AtomicU64::new(0),
            disk_read: AtomicU64::new(0),
            disk_write: AtomicU64::new(0),
            total_bytes: std::sync::OnceLock::new(),
            started_at: std::time::Instant::now(),
            finished_at: std::sync::OnceLock::new(),
            terminal_reported: AtomicBool::new(false),
            request_metrics: crate::metrics::RequestMetricsState::default(),
        }
    }

    /// Record an IO sample (per-transfer cumulative counters only).
    pub(crate) fn record_io(&self, sample: &crate::metrics::IoSample) {
        self.network_tx
            .fetch_add(sample.network_tx, Ordering::Relaxed);
        self.network_rx
            .fetch_add(sample.network_rx, Ordering::Relaxed);
        self.disk_read
            .fetch_add(sample.disk_read, Ordering::Relaxed);
        self.disk_write
            .fetch_add(sample.disk_write, Ordering::Relaxed);
    }

    /// Set the expected total payload bytes. No-op if already set.
    pub(crate) fn set_total_bytes(&self, n: u64) {
        let _ = self.total_bytes.set(n);
    }

    /// Mark the transfer as finished. No-op if already set.
    pub(crate) fn set_finished(&self) {
        let _ = self.finished_at.set(std::time::Instant::now());
    }

    /// Claims the single terminal tracing record for this transfer.
    ///
    /// Normal completion, failure, cancellation, and scheduler-owned cleanup
    /// may converge on terminal reporting. Only the first caller emits.
    pub(crate) fn claim_terminal_report(&self) -> bool {
        !self.terminal_reported.swap(true, Ordering::AcqRel)
    }

    /// Merge one completed service-request measurement.
    pub(crate) fn record_request(&self, metrics: &crate::metrics::RequestMetrics) {
        self.request_metrics.record(metrics);
    }

    /// Return the cumulative request measurement for this transfer.
    pub(crate) fn request_metrics(&self) -> crate::metrics::RequestMetrics {
        self.request_metrics.snapshot()
    }

    /// Snapshot current metrics into the public type.
    pub(crate) fn snapshot(&self) -> crate::metrics::TransferMetrics {
        crate::metrics::TransferMetrics {
            network_tx: self.network_tx.load(Ordering::Relaxed),
            network_rx: self.network_rx.load(Ordering::Relaxed),
            disk_read: self.disk_read.load(Ordering::Relaxed),
            disk_write: self.disk_write.load(Ordering::Relaxed),
            total_bytes: self.total_bytes.get().copied(),
            elapsed: self.elapsed(),
        }
    }

    /// Returns the time from the transfer's start to its recorded finish, or
    /// to now if no finish is recorded.
    fn elapsed(&self) -> std::time::Duration {
        match self.finished_at.get() {
            Some(finished_at) => finished_at.saturating_duration_since(self.started_at),
            None => self.started_at.elapsed(),
        }
    }
}

impl std::fmt::Debug for MetricsState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MetricsState")
            .field("network_tx", &self.network_tx.load(Ordering::Relaxed))
            .field("network_rx", &self.network_rx.load(Ordering::Relaxed))
            .field("disk_read", &self.disk_read.load(Ordering::Relaxed))
            .field("disk_write", &self.disk_write.load(Ordering::Relaxed))
            .field("request_metrics", &self.request_metrics())
            .finish()
    }
}

/// Terminal status reported once in a transfer's terminal summary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TerminalOutcome {
    /// The transfer completed successfully.
    Completed,
    /// The transfer failed.
    Failed,
    /// The transfer was cancelled.
    Cancelled,
}

impl TerminalOutcome {
    /// Projects a status onto its terminal outcome, or `None` while active.
    pub(crate) fn from_status(status: crate::types::TransferStatus) -> Option<Self> {
        use crate::types::TransferStatus;
        match status {
            TransferStatus::Completed => Some(Self::Completed),
            TransferStatus::Failed => Some(Self::Failed),
            TransferStatus::Cancelled => Some(Self::Cancelled),
            TransferStatus::Active => None,
        }
    }

    /// Stable value of the summary's `outcome` field.
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }
}

/// Common lifecycle management for transfer state machines.
///
/// Handles status tracking, error storage, completion signaling, and scheduler
/// wake coordination. Each transfer type (upload, download, etc.) owns a
/// `TransferContext` along with its operation-specific state.
///
/// Cheap to clone - all fields are behind `Arc`.
#[derive(Clone)]
pub(crate) struct TransferContext {
    /// Unique identifier for this transfer
    pub(crate) id: TransferId,
    /// Access to client handle (scheduler, S3 client, config)
    pub(crate) handle: Arc<crate::client::Handle>,
    /// Transfer lifecycle status
    status: StateMachineStatus,
    /// Error storage (only used when status == Failed)
    error: Arc<Mutex<Option<Box<error::Error>>>>,
    /// Completion signal sender - signals "state machine reached terminal state"
    completion_tx: Arc<Mutex<Option<StateMachineTerminalSender>>>,
    /// Set when `poll_work` returns `Pending`, cleared by a wake or resumed poll.
    wake_flag: Arc<wake_flag::WakeFlag>,
    /// Optional scheduler-visible pending interval accounting.
    pending_state: Option<Arc<TransferPendingState>>,
    /// Per-transfer metrics backing store
    pub(crate) metrics: Arc<MetricsState>,
    /// User agent features of the operation this transfer belongs to
    features: OperationFeatures,
}

/// In-progress measurement for one logical transfer-manager request.
///
/// The guard publishes exactly once when finished or dropped. Drop publication
/// keeps early returns and cancellation paths from losing a request after it
/// started. A ranged discovery may carry the guard with its response body so
/// headers and validated body collection remain one logical request.
///
/// The published elapsed time is the sum of the intervals during which the
/// measurement was running. A measurement starts running and accrues nothing
/// while paused.
///
/// Time is read from [`tokio::time::Instant`], which follows the tokio test
/// clock when it is paused and the system monotonic clock otherwise.
#[derive(Debug)]
pub(crate) struct RequestMeasurement {
    ctx: TransferContext,
    /// Elapsed time accrued by completed running intervals.
    accrued: std::time::Duration,
    /// Start of the current running interval; `None` while paused.
    running_since: Option<tokio::time::Instant>,
    metrics: crate::metrics::RequestMetrics,
    published: bool,
}

impl RequestMeasurement {
    fn new(ctx: TransferContext) -> Self {
        Self {
            ctx,
            accrued: std::time::Duration::ZERO,
            running_since: Some(tokio::time::Instant::now()),
            metrics: crate::metrics::RequestMetrics::default(),
            published: false,
        }
    }

    /// Return the request aggregate updated by the retry loop.
    pub(crate) fn metrics_mut(&mut self) -> &mut crate::metrics::RequestMetrics {
        &mut self.metrics
    }

    /// Stop accruing elapsed time while the request's work is not in progress,
    /// e.g. while its response body waits for memory before being read.
    ///
    /// No-op when already paused.
    pub(crate) fn pause(&mut self) {
        if let Some(since) = self.running_since.take() {
            self.accrued += since.elapsed();
        }
    }

    /// Resume accruing elapsed time.
    ///
    /// No-op when already running.
    pub(crate) fn resume(&mut self) {
        if self.running_since.is_none() {
            self.running_since = Some(tokio::time::Instant::now());
        }
    }

    /// Elapsed time accrued so far, including the current running interval.
    fn elapsed(&self) -> std::time::Duration {
        self.accrued
            + self
                .running_since
                .map_or(std::time::Duration::ZERO, |s| s.elapsed())
    }

    /// Complete and publish this logical request.
    pub(crate) fn finish(mut self) -> crate::metrics::RequestMetrics {
        self.publish();
        self.metrics
    }

    fn publish(&mut self) {
        if self.published {
            return;
        }
        self.metrics.record_request(self.elapsed());
        self.ctx.record_request_metrics(&self.metrics);
        self.published = true;
    }
}

impl Drop for RequestMeasurement {
    fn drop(&mut self) {
        self.publish();
    }
}

/// Direction-specific attribution for one logical request measurement.
///
/// The common measurement records transfer totals. Implementations add the
/// same result to the request-kind aggregate owned by one transfer direction.
pub(crate) trait RequestMetricsAttribution: Clone {
    /// Direction-specific request classification.
    type Kind: Copy + std::fmt::Debug;

    /// Records one finished request under its direction-specific kind.
    fn record_request_metrics(&self, kind: Self::Kind, metrics: &crate::metrics::RequestMetrics);
}

/// Request measurement published to common and direction-specific aggregates.
///
/// The guard publishes exactly once when explicitly finished or dropped.
pub(crate) struct AttributedRequestMeasurement<A: RequestMetricsAttribution> {
    measurement: Option<RequestMeasurement>,
    attribution: A,
    kind: A::Kind,
}

impl<A: RequestMetricsAttribution> AttributedRequestMeasurement<A> {
    /// Starts a logical request associated with one direction-specific kind.
    pub(crate) fn new(ctx: &TransferContext, attribution: A, kind: A::Kind) -> Self {
        Self {
            measurement: Some(ctx.start_request_metrics()),
            attribution,
            kind,
        }
    }

    /// Returns the request metrics updated by the retry loop.
    pub(crate) fn metrics_mut(&mut self) -> &mut crate::metrics::RequestMetrics {
        self.measurement
            .as_mut()
            .expect("request measurement already finished")
            .metrics_mut()
    }

    /// Stop accruing elapsed time while the request's work is not in progress,
    /// e.g. while its response body waits for memory before being read.
    ///
    /// No-op when already paused.
    pub(crate) fn pause(&mut self) {
        self.measurement
            .as_mut()
            .expect("request measurement already finished")
            .pause();
    }

    /// Resume accruing elapsed time.
    ///
    /// No-op when already running.
    pub(crate) fn resume(&mut self) {
        self.measurement
            .as_mut()
            .expect("request measurement already finished")
            .resume();
    }

    /// Publishes the request measurement to both aggregate scopes.
    pub(crate) fn finish(mut self) -> crate::metrics::RequestMetrics {
        self.publish()
    }

    fn publish(&mut self) -> crate::metrics::RequestMetrics {
        let measurement = self
            .measurement
            .take()
            .expect("request measurement already finished");
        let metrics = measurement.finish();
        self.attribution.record_request_metrics(self.kind, &metrics);
        metrics
    }
}

impl<A: RequestMetricsAttribution> std::fmt::Debug for AttributedRequestMeasurement<A> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("AttributedRequestMeasurement")
            .field("kind", &self.kind)
            .field("finished", &self.measurement.is_none())
            .finish()
    }
}

impl<A: RequestMetricsAttribution> Drop for AttributedRequestMeasurement<A> {
    fn drop(&mut self) {
        if self.measurement.is_some() {
            let _ = self.publish();
        }
    }
}

/// Task wake adapter for futures polled from a transfer's synchronous state machine.
///
/// This deliberately enters the scheduler directly instead of using
/// [`TransferContext::try_wake`]. The scheduler's descriptor claim records a wake
/// that races the active `poll_work` call, so the future can register this waker
/// before `poll_work` returns `Pending` without relying on the edge-triggered
/// [`wake_flag::WakeFlag`].
struct SchedulerWake {
    scheduler: crate::scheduler::Scheduler,
    id: TransferId,
}

impl Wake for SchedulerWake {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.scheduler.wake(self.id);
    }
}

impl fmt::Display for TransferContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Transfer(id={}, status={})", self.id.id, self.status)
    }
}

impl fmt::Debug for TransferContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TransferContext")
            .field("id", &self.id)
            .field("status", &self.status)
            .finish_non_exhaustive()
    }
}

impl TransferContext {
    /// Create a new transfer context.
    /// Returns the context and a receiver for terminal state notification.
    pub(crate) fn new(handle: Arc<crate::client::Handle>) -> (Self, StateMachineTerminalReceiver) {
        Self::new_inner(handle, next_transfer_id())
    }

    /// Returns a context + receiver for a child transfer linked to `parent_id`.
    ///
    /// Child transfers share the scheduler with their parent. `signal_terminal`
    /// on the child wakes the parent so the parent state machine can reap it.
    /// `scheduler.cancel_transfer(parent_id)` cascades to children via the
    /// parent linkage.
    pub(crate) fn new_child(
        handle: Arc<crate::client::Handle>,
        parent_id: u64,
    ) -> (Self, StateMachineTerminalReceiver) {
        let mut id = next_transfer_id();
        id.parent = Some(parent_id);
        Self::new_inner(handle, id)
    }

    fn new_inner(
        handle: Arc<crate::client::Handle>,
        id: TransferId,
    ) -> (Self, StateMachineTerminalReceiver) {
        let (completion_tx, completion_rx) = tokio::sync::oneshot::channel();
        let diagnostics = handle.config.diagnostics().transfer();
        let pending_state = diagnostics
            .enable_summaries()
            .then(|| Arc::new(TransferPendingState::new(diagnostics.events_enabled())));
        let ctx = Self {
            id,
            metrics: Arc::new(MetricsState::new()),
            handle,
            status: StateMachineStatus::new(),
            error: Arc::new(Mutex::new(None)),
            completion_tx: Arc::new(Mutex::new(Some(completion_tx))),
            wake_flag: Arc::new(wake_flag::WakeFlag::new()),
            pending_state,
            features: OperationFeatures::default(),
        };
        (ctx, completion_rx)
    }

    /// Marks every request this transfer issues with `features`.
    pub(crate) fn with_features(mut self, features: OperationFeatures) -> Self {
        self.features = features;
        self
    }

    /// [`Handle::bucket_partition_override`](crate::client::Handle::bucket_partition_override)
    /// carrying this transfer's user agent features.
    pub(crate) fn bucket_partition_override(
        &self,
        bucket: Option<&str>,
    ) -> aws_sdk_s3::config::Builder {
        self.features
            .apply(self.handle.bucket_partition_override(bucket))
    }

    /// [`Handle::download_get_override`](crate::client::Handle::download_get_override)
    /// carrying this transfer's user agent features.
    pub(crate) fn download_get_override(
        &self,
        bucket: Option<&str>,
    ) -> aws_sdk_s3::config::Builder {
        self.features
            .apply(self.handle.download_get_override(bucket))
    }

    /// [`Handle::upload_override`](crate::client::Handle::upload_override) carrying this
    /// transfer's user agent features.
    pub(crate) fn upload_override(&self, bucket: Option<&str>) -> aws_sdk_s3::config::Builder {
        self.features.apply(self.handle.upload_override(bucket))
    }

    /// Create a new transfer context with a specific ID (for testing).
    /// Returns the context and a receiver for terminal state notification.
    #[cfg(test)]
    pub(crate) fn with_id(
        id: TransferId,
        handle: Arc<crate::client::Handle>,
    ) -> (Self, StateMachineTerminalReceiver) {
        Self::new_inner(handle, id)
    }

    /// Record that `poll_work` is about to return `Pending`.
    ///
    /// # Wake primitive protocol
    ///
    /// The wake primitive is edge-triggered: a wake only fires if the
    /// pending flag is set at the moment the mutator calls `try_wake`. Lost-
    /// wake avoidance is a cooperation between two sides.
    ///
    /// ## The race this protocol prevents
    ///
    /// Without a shared lock, the poller and mutator can interleave:
    ///
    /// ```text
    /// Poller:                              Mutator:
    ///   check condition -> blocked
    ///                                        mutate state (now unblocking)
    ///                                        try_wake -> sees pending=false
    ///                                                 -> no-op
    ///   set_pending(true)
    ///   return Pending
    /// ```
    ///
    /// The state is unblocked, the poller is pending, and nothing will
    /// wake it. The transfer is stuck.
    ///
    /// ## How the lock prevents this
    ///
    /// Both the poller's condition check + `set_pending` and the mutator's
    /// state mutation happen under the same lock (the transfer's state
    /// mutex). This serializes them:
    ///
    /// - If the mutator acquires the lock first: it mutates state and
    ///   releases. The poller then acquires the lock, observes the new
    ///   state, and returns `Ready` (never calls `set_pending`).
    ///
    /// - If the poller acquires the lock first: it checks the condition
    ///   (still blocked), calls `set_pending`, and releases. The mutator
    ///   then acquires the lock, mutates, releases, and calls `try_wake`
    ///   which observes pending=true and fires the wake.
    ///
    /// The mutator's discipline is `lock → mutate → unlock → try_wake`.
    /// Calling `try_wake` after releasing the lock lets the woken poller
    /// acquire the lock immediately. `try_wake` is unconditionally cheap
    /// (a single atomic swap when no wake is pending).
    ///
    /// Spurious wakes (mutator fires when no poll was actually pending)
    /// are harmless — `wake` on a descriptor not in pending state is a
    /// no-op.
    #[inline]
    pub(crate) fn set_pending(&self, cause: impl Into<PendingCause>) {
        let cause = cause.into();
        self.wake_flag.set_pending();
        if let Some(pending) = &self.pending_state {
            pending.record_pending(self.id, cause);
        }
        tracing::trace!(
            target: crate::telemetry::TARGET_SCHEDULING,
            tid = %self.id,
            category = cause.category.as_str(),
            reason = cause.reason,
            "ctx.set_pending",
        );
    }

    /// Wake the scheduler if this transfer was marked `Pending`.
    ///
    /// Call after any state mutation that might unblock a pending poll,
    /// following the mutator pattern `lock → mutate → unlock → try_wake`.
    /// Idempotent: spurious calls cost only an atomic swap. See
    /// [`Self::set_pending`] for the full wake primitive protocol.
    #[inline]
    pub(crate) fn try_wake(&self) {
        if self.wake_flag.take_pending() {
            tracing::trace!(
                target: crate::telemetry::TARGET_SCHEDULING,
                tid = %self.id,
                "ctx.try_wake.fired",
            );
            self.wake();
        } else {
            tracing::trace!(
                target: crate::telemetry::TARGET_SCHEDULING,
                tid = %self.id,
                "ctx.try_wake.skipped",
            );
        }
    }

    /// Unconditionally notify the scheduler that this transfer should be polled.
    ///
    /// Futures registered from `poll_work` use this path because their wake may
    /// race before or after the transfer publishes `Pending`. The descriptor's
    /// wake-requested protocol retains either ordering.
    #[inline]
    pub(crate) fn wake(&self) {
        self.handle.scheduler.wake(self.id);
    }

    /// Returns a task waker that requeues this transfer in the scheduler.
    ///
    /// Use this for a `Future` polled inside `poll_work`. Its wake is level-like
    /// at the scheduler boundary: a wake concurrent with the current poll is
    /// retained by the descriptor's release-and-recheck protocol. Ordinary
    /// state mutations should continue to use [`Self::set_pending`] and
    /// [`Self::try_wake`] under their shared state lock.
    pub(crate) fn waker(&self) -> Waker {
        Waker::from(Arc::new(SchedulerWake {
            scheduler: self.handle.scheduler.clone(),
            id: self.id,
        }))
    }

    /// Reconcile the previous pending interval before the scheduler polls again.
    ///
    /// Clearing the edge-triggered flag here also handles registered-future
    /// wakes, which enter through [`Self::waker`] rather than [`Self::try_wake`].
    pub(crate) fn begin_poll(&self) {
        self.wake_flag.take_pending();
        if let Some(pending) = &self.pending_state {
            pending.record_poll_started(self.id);
        }
    }

    /// Record the first scheduler wake observed for the current pending interval.
    pub(crate) fn record_wake(&self) {
        if let Some(pending) = &self.pending_state {
            pending.record_wake(self.id);
        }
    }

    /// Return optional scheduler-visible pending statistics.
    pub(crate) fn pending_stats(&self) -> Option<TransferPendingStats> {
        self.pending_state
            .as_ref()
            .map(|pending| pending.snapshot())
    }

    /// The S3 client to use for SDK operations
    pub(crate) fn s3_client(&self) -> &aws_sdk_s3::Client {
        &self.handle.s3_client
    }

    /// Mark transfer as failed and store the error.
    /// First-write-wins - returns true if this call set the status.
    ///
    /// Setting the status alone is not observable to the owning handle: a
    /// terminal transition must be signalled via [`signal_terminal`] (directly,
    /// or once in-flight work drains).
    ///
    /// [`signal_terminal`]: Self::signal_terminal
    pub(crate) fn set_failed(&self, err: impl Into<error::Error>) -> bool {
        if self.status.set_failed() {
            *self.error.lock().unwrap() = Some(Box::new(err.into()));
            true
        } else {
            false
        }
    }

    /// Mark transfer as completed.
    /// First-write-wins - returns true if this call set the status.
    #[inline]
    pub(crate) fn set_completed(&self) -> bool {
        self.status.set_completed()
    }

    /// Mark transfer as cancelled.
    /// First-write-wins - returns true if this call set the status.
    #[inline]
    pub(crate) fn set_cancelled(&self) -> bool {
        self.status.set_cancelled()
    }

    /// Take the error if transfer failed. Returns None if not failed or already taken.
    pub(crate) fn take_error(&self) -> Option<error::Error> {
        if self.status.is_failed() {
            self.error.lock().unwrap().take().map(|e| *e)
        } else {
            None
        }
    }

    /// Replaces the stored error with `f` applied to it, under the lock
    /// [`take_error`](Self::take_error) takes it under.
    ///
    /// No effect when no error is stored: the transfer has not failed, or its
    /// error was already taken. The status is unchanged.
    pub(crate) fn amend_error(&self, f: impl FnOnce(error::Error) -> error::Error) {
        let mut stored = self.error.lock().unwrap();
        *stored = stored.take().map(|err| Box::new(f(*err)));
    }

    /// Peek at the error kind if transfer failed. Returns None if not failed or already taken.
    pub(crate) fn error_kind(&self) -> Option<error::ErrorKind> {
        if self.status.is_failed() {
            self.error
                .lock()
                .unwrap()
                .as_ref()
                .map(|e| e.kind().clone())
        } else {
            None
        }
    }

    /// Check if transfer has failed
    #[inline]
    pub(crate) fn is_failed(&self) -> bool {
        self.status.is_failed()
    }

    /// Check if transfer was cancelled
    #[inline]
    pub(crate) fn is_cancelled(&self) -> bool {
        self.status.is_cancelled()
    }

    /// Check if transfer is still active (not completed, failed, or cancelled)
    #[inline]
    pub(crate) fn is_active(&self) -> bool {
        self.status.is_active()
    }

    /// Check if transfer completed successfully
    #[inline]
    pub(crate) fn is_completed(&self) -> bool {
        self.status.is_completed()
    }

    /// Signal that the transfer has reached a terminal state.
    ///
    /// Call this after `set_completed()`/`set_failed()`/`set_cancelled()`. Wakes
    /// any waiters (`join()`) and the parent transfer (so it can reap this child).
    ///
    /// Setting a terminal status is not enough on its own. A transfer that has
    /// gone terminal but returns idle to the scheduler WITHOUT signalling can be
    /// removed by the scheduler with its completion channel never fired — a
    /// permanent hang of the owning handle, not merely a delay. Every terminal
    /// transition must therefore reach exactly one `signal_terminal`. It is safe
    /// to call while in-flight work is still draining.
    pub(crate) fn signal_terminal(&self) {
        self.finalize_terminal_metrics();
        if let Some(tx) = self.completion_tx.lock().unwrap().take() {
            let _ = tx.send(());
        }
        // Wake the parent transfer (if any) so it can reap this child.
        if let Some(parent_id) = self.id.parent {
            self.handle.scheduler.wake(TransferId {
                id: parent_id,
                parent: None,
            });
        }
    }

    /// Closes common timing intervals before a terminal diagnostic is emitted.
    ///
    /// This operation is idempotent. State machines may call it before
    /// [`Self::signal_terminal`] so their terminal summary observes the same
    /// finished timestamp and pending interval that the owning handle will see.
    pub(crate) fn finalize_terminal_metrics(&self) {
        if let Some(pending) = &self.pending_state {
            pending.record_terminal(self.id);
        }
        self.wake_flag.take_pending();
        self.metrics.set_finished();
    }

    /// Record an IO sample to per-transfer metrics and per-client telemetry.
    pub(crate) fn record_io(&self, sample: &crate::metrics::IoSample) {
        self.metrics.record_io(sample);
        self.handle.telemetry.io_counters.record(sample);
    }

    /// Record one request in the transfer aggregate.
    pub(crate) fn record_request_metrics(&self, metrics: &crate::metrics::RequestMetrics) {
        self.metrics.record_request(metrics);
    }

    /// Start measuring one logical service request.
    pub(crate) fn start_request_metrics(&self) -> RequestMeasurement {
        RequestMeasurement::new(self.clone())
    }

    /// Set the expected total payload bytes for this transfer.
    pub(crate) fn set_total_bytes(&self, n: u64) {
        self.metrics.set_total_bytes(n);
    }

    /// Get current transfer status as a public enum.
    pub(crate) fn transfer_status(&self) -> crate::types::TransferStatus {
        use crate::types::TransferStatus;
        if self.status.is_cancelled() {
            TransferStatus::Cancelled
        } else if self.is_failed() {
            TransferStatus::Failed
        } else if !self.is_active() {
            TransferStatus::Completed
        } else {
            TransferStatus::Active
        }
    }

    /// Claims the single terminal tracing record for this transfer.
    pub(crate) fn claim_terminal_report(&self) -> bool {
        self.metrics.claim_terminal_report()
    }

    /// Snapshot current transfer metrics.
    pub(crate) fn metrics(&self) -> crate::metrics::TransferMetrics {
        self.metrics.snapshot()
    }

    /// Get scheduling controls for this transfer.
    pub(crate) fn scheduling(&self) -> SchedulingCtl<'_> {
        SchedulingCtl { ctx: self }
    }
}

/// Scheduling controls for a transfer.
///
/// Adjusts how this transfer is scheduled relative to other transfers.
/// Obtained from the `scheduling` method of a transfer handle.
#[derive(Debug)]
pub struct SchedulingCtl<'a> {
    ctx: &'a TransferContext,
}

impl SchedulingCtl<'_> {
    /// Sets the priority of this transfer.
    ///
    /// Concurrent transfers receive work in proportion to their priorities.
    /// The default is 128; 255 is the highest. `0` is treated as `1`. Applies
    /// to work scheduled after the call.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(client: &aws_s3_transfer::Client) -> Result<(), aws_s3_transfer::error::Error> {
    /// let handle = client
    ///     .download()
    ///     .bucket("my-bucket")
    ///     .key("my-key")
    ///     .initiate()?;
    ///
    /// // Start as a low-priority background transfer.
    /// handle.scheduling().set_priority(64);
    ///
    /// // The data is now needed sooner; raise the priority.
    /// handle.scheduling().set_priority(255);
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_priority(&self, priority: u8) {
        self.ctx
            .handle
            .scheduler
            .set_priority(self.ctx.id, priority);
    }
}

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

    /// A snapshot's `elapsed` advances while no finish is recorded and stops at
    /// the recorded finish. The 5 ms sleeps exceed any monotonic clock step, so
    /// a snapshot that kept advancing after `set_finished` fails the equality.
    #[test]
    fn metrics_elapsed_stops_at_recorded_finish() {
        let metrics = MetricsState::new();
        let before = metrics.snapshot().elapsed;
        std::thread::sleep(std::time::Duration::from_millis(5));
        let active = metrics.snapshot().elapsed;
        assert!(
            active > before,
            "elapsed must advance while the transfer is active"
        );

        metrics.set_finished();
        let finished = metrics.snapshot().elapsed;
        assert!(finished >= active);
        std::thread::sleep(std::time::Duration::from_millis(5));
        assert_eq!(
            metrics.snapshot().elapsed,
            finished,
            "elapsed must stop advancing at the recorded finish"
        );
    }

    mod state_machine_status {
        use super::*;

        #[test]
        fn starts_active() {
            let s = StateMachineStatus::new();
            assert!(s.is_active());
            assert!(!s.is_failed());
            assert!(!s.is_cancelled());
        }

        #[test]
        fn set_completed_from_active() {
            let s = StateMachineStatus::new();
            assert!(s.set_completed());
            assert!(!s.is_active());
            assert!(!s.is_failed());
            assert!(!s.is_cancelled());
        }

        #[test]
        fn set_failed_from_active() {
            let s = StateMachineStatus::new();
            assert!(s.set_failed());
            assert!(!s.is_active());
            assert!(s.is_failed());
        }

        #[test]
        fn set_cancelled_from_active() {
            let s = StateMachineStatus::new();
            assert!(s.set_cancelled());
            assert!(!s.is_active());
            assert!(s.is_cancelled());
        }

        #[test]
        fn only_first_transition_wins() {
            let s = StateMachineStatus::new();
            assert!(s.set_failed());
            // second transition fails — already terminal
            assert!(!s.set_completed());
            assert!(!s.set_cancelled());
            assert!(s.is_failed());
        }

        #[test]
        fn completed_blocks_other_transitions() {
            let s = StateMachineStatus::new();
            assert!(s.set_completed());
            assert!(!s.set_failed());
            assert!(!s.set_cancelled());
        }

        #[test]
        fn display() {
            let s = StateMachineStatus::new();
            assert_eq!(s.to_string(), "Active");
            s.set_failed();
            assert_eq!(s.to_string(), "Failed");
        }
    }

    mod transfer_status {
        use crate::types::TransferStatus;

        #[test]
        fn is_terminal() {
            assert!(!TransferStatus::Active.is_terminal());
            assert!(TransferStatus::Completed.is_terminal());
            assert!(TransferStatus::Failed.is_terminal());
            assert!(TransferStatus::Cancelled.is_terminal());
        }
    }

    mod transfer_context_status_and_metrics {
        use super::*;
        use std::sync::Arc;

        fn test_handle() -> Arc<crate::client::Handle> {
            let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
            let config = crate::Config::builder()
                .sdk_client(s3_client)
                .build()
                .expect("valid config");
            crate::client::Handle::new_for_test(config, 4)
        }

        fn test_handle_with_diagnostics(detail: u64) -> Arc<crate::client::Handle> {
            let s3_client = aws_smithy_mocks::mock_client!(aws_sdk_s3, []);
            let config = crate::Config::builder()
                .sdk_client(s3_client)
                .diagnostics_for_test(crate::config::MemoryDiagnosticsConfig::default(), detail)
                .build()
                .expect("valid config");
            crate::client::Handle::new_for_test(config, 4)
        }

        #[derive(Clone, Default)]
        struct TestRequestAttribution {
            records: Arc<Mutex<Vec<(u8, crate::metrics::RequestMetrics)>>>,
        }

        impl RequestMetricsAttribution for TestRequestAttribution {
            type Kind = u8;

            fn record_request_metrics(
                &self,
                kind: Self::Kind,
                metrics: &crate::metrics::RequestMetrics,
            ) {
                self.records.lock().unwrap().push((kind, *metrics));
            }
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn status_transitions() {
            let handle = test_handle();

            // Completed
            let (ctx, _rx) = TransferContext::new(handle.clone());
            assert_eq!(ctx.transfer_status(), crate::types::TransferStatus::Active);
            ctx.set_completed();
            ctx.signal_terminal();
            assert_eq!(
                ctx.transfer_status(),
                crate::types::TransferStatus::Completed
            );

            // Failed
            let (ctx, _rx) = TransferContext::new(handle.clone());
            ctx.set_failed(crate::error::Error::new(
                crate::error::ErrorKind::InputInvalid,
                "test",
            ));
            ctx.signal_terminal();
            assert_eq!(ctx.transfer_status(), crate::types::TransferStatus::Failed);

            // Cancelled
            let (ctx, _rx) = TransferContext::new(handle);
            ctx.set_cancelled();
            ctx.signal_terminal();
            assert_eq!(
                ctx.transfer_status(),
                crate::types::TransferStatus::Cancelled
            );
        }

        /// `amend_error` rewrites a stored error in place, and does nothing
        /// before a failure is stored or after the error is taken.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn amend_error_rewrites_only_a_stored_error() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            let with_id = |err: crate::error::Error| err.with_upload_id("id".to_owned());

            ctx.amend_error(with_id);
            assert!(ctx.is_active());
            assert!(ctx.take_error().is_none());

            ctx.set_failed(crate::error::Error::new(
                crate::error::ErrorKind::RuntimeError,
                "test",
            ));
            ctx.amend_error(with_id);
            let err = ctx.take_error().expect("the failure is stored");
            assert_eq!(err.kind(), &crate::error::ErrorKind::RuntimeError);
            assert_eq!(err.upload_id(), Some("id"));

            ctx.amend_error(|_| panic!("a taken error must not be amended"));
            assert!(ctx.take_error().is_none());
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn stats_initial_values() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            let stats = ctx.metrics();
            assert_eq!(stats.network_tx, 0);
            assert_eq!(stats.network_rx, 0);
            assert_eq!(stats.disk_read, 0);
            assert_eq!(stats.disk_write, 0);
            assert_eq!(stats.total_bytes, None);
            assert!(stats.elapsed.as_secs() < 1);
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn stats_record_io() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            ctx.record_io(&crate::metrics::IoSample {
                network_tx: 100,
                network_rx: 200,
                disk_read: 300,
                disk_write: 400,
            });
            ctx.record_io(&crate::metrics::IoSample {
                network_tx: 10,
                network_rx: 20,
                disk_read: 30,
                disk_write: 40,
            });
            let stats = ctx.metrics();
            assert_eq!(stats.network_tx, 110);
            assert_eq!(stats.network_rx, 220);
            assert_eq!(stats.disk_read, 330);
            assert_eq!(stats.disk_write, 440);
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn request_metrics_merge_into_transfer_aggregate() {
            let handle = test_handle();
            assert!(!handle.config.diagnostics().transfer().enable_summaries());
            let (ctx, _rx) = TransferContext::new(handle);
            let req_metrics = crate::metrics::RequestMetrics {
                requests: 1,
                elapsed: std::time::Duration::from_millis(15),
                max_elapsed: std::time::Duration::from_millis(15),
                retry_reissues: 2,
                throttle_reissues: 3,
                hedge_reissues: 1,
                retry_exhaustions: 1,
                backoff_duration: std::time::Duration::from_millis(9),
            };

            ctx.record_request_metrics(&req_metrics);

            assert_eq!(ctx.metrics.request_metrics(), req_metrics);
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn request_measurement_publishes_once_on_finish_or_drop() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);

            ctx.start_request_metrics().finish();
            drop(ctx.start_request_metrics());

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

        #[cfg_attr(miri, ignore)]
        #[tokio::test(start_paused = true)]
        async fn request_measurement_excludes_paused_time() {
            use std::time::Duration;
            let (ctx, _rx) = TransferContext::new(test_handle());

            let mut measurement = ctx.start_request_metrics();
            tokio::time::advance(Duration::from_secs(1)).await;
            measurement.pause();
            tokio::time::advance(Duration::from_secs(10)).await;
            measurement.resume();
            tokio::time::advance(Duration::from_secs(2)).await;
            let metrics = measurement.finish();

            assert_eq!(metrics.elapsed, Duration::from_secs(3));
            assert_eq!(metrics.max_elapsed, Duration::from_secs(3));
            assert_eq!(
                ctx.metrics.request_metrics().elapsed,
                Duration::from_secs(3)
            );
        }

        #[cfg_attr(miri, ignore)]
        #[tokio::test(start_paused = true)]
        async fn request_measurement_repeated_pause_and_resume_are_noops() {
            use std::time::Duration;
            let (ctx, _rx) = TransferContext::new(test_handle());

            let mut measurement = ctx.start_request_metrics();
            tokio::time::advance(Duration::from_secs(1)).await;
            measurement.pause();
            tokio::time::advance(Duration::from_secs(5)).await;
            // A second pause must not accrue the paused interval.
            measurement.pause();
            tokio::time::advance(Duration::from_secs(5)).await;
            measurement.resume();
            tokio::time::advance(Duration::from_secs(1)).await;
            // A second resume must not restart the running interval.
            measurement.resume();
            tokio::time::advance(Duration::from_secs(1)).await;

            assert_eq!(measurement.finish().elapsed, Duration::from_secs(3));
        }

        #[cfg_attr(miri, ignore)]
        #[tokio::test(start_paused = true)]
        async fn request_measurement_published_while_paused_counts_active_time() {
            use std::time::Duration;
            let (ctx, _rx) = TransferContext::new(test_handle());

            let mut finished = ctx.start_request_metrics();
            tokio::time::advance(Duration::from_secs(2)).await;
            finished.pause();
            tokio::time::advance(Duration::from_secs(10)).await;
            assert_eq!(finished.finish().elapsed, Duration::from_secs(2));

            let mut dropped = ctx.start_request_metrics();
            tokio::time::advance(Duration::from_secs(3)).await;
            dropped.pause();
            tokio::time::advance(Duration::from_secs(10)).await;
            drop(dropped);

            let total = ctx.metrics.request_metrics();
            assert_eq!(total.requests, 2);
            assert_eq!(total.elapsed, Duration::from_secs(5));
            assert_eq!(total.max_elapsed, Duration::from_secs(3));
        }

        #[cfg_attr(miri, ignore)]
        #[tokio::test(start_paused = true)]
        async fn attributed_request_measurement_forwards_pause_and_resume() {
            use std::time::Duration;
            let (ctx, _rx) = TransferContext::new(test_handle());
            let attribution = TestRequestAttribution::default();

            let mut measurement = AttributedRequestMeasurement::new(&ctx, attribution.clone(), 1);
            tokio::time::advance(Duration::from_secs(1)).await;
            measurement.pause();
            tokio::time::advance(Duration::from_secs(10)).await;
            measurement.resume();
            tokio::time::advance(Duration::from_secs(1)).await;
            drop(measurement);

            let records = attribution.records.lock().unwrap();
            assert_eq!(records.len(), 1);
            assert_eq!(records[0].1.elapsed, Duration::from_secs(2));
            assert_eq!(
                ctx.metrics.request_metrics().elapsed,
                Duration::from_secs(2)
            );
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn attributed_request_measurement_publishes_to_both_aggregates() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            let attribution = TestRequestAttribution::default();

            let mut finished = AttributedRequestMeasurement::new(&ctx, attribution.clone(), 7);
            finished
                .metrics_mut()
                .record_retry_reissue(std::time::Duration::from_millis(3));
            let finished_metrics = finished.finish();

            drop(AttributedRequestMeasurement::new(
                &ctx,
                attribution.clone(),
                9,
            ));

            let records = attribution.records.lock().unwrap();
            assert_eq!(records.len(), 2);
            assert_eq!(records[0], (7, finished_metrics));
            assert_eq!(records[1].0, 9);
            assert_eq!(records[1].1.requests, 1);
            assert_eq!(ctx.metrics.request_metrics().requests, 2);
            assert_eq!(ctx.metrics.request_metrics().retry_reissues, 1);
        }

        // Builds a client handle: dropping the scheduler's ready set is not miri-clean.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn disabled_diagnostics_do_not_allocate_pending_stats() {
            let (ctx, _rx) = TransferContext::new(test_handle());
            ctx.set_pending(PendingCause::new(PendingCategory::Memory, "test"));
            ctx.record_wake();
            ctx.begin_poll();

            assert_eq!(ctx.pending_stats(), None);
        }

        // Builds a client handle: dropping the scheduler's ready set is not miri-clean.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn pending_cause_is_accounted_across_wake_and_next_poll() {
            let (ctx, _rx) = TransferContext::new(test_handle_with_diagnostics(1));
            ctx.set_pending(PendingCause::new(PendingCategory::Memory, "test"));
            ctx.record_wake();
            ctx.record_wake();
            ctx.begin_poll();

            let stats = ctx.pending_stats().expect("summary diagnostics enabled");
            let memory = stats.category(PendingCategory::Memory);
            assert_eq!(memory.count, 1);
            assert_eq!(stats.terminal_cause, None);
        }

        // Builds a client handle: dropping the scheduler's ready set is not miri-clean.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn terminal_signal_closes_pending_interval_once() {
            let (ctx, _rx) = TransferContext::new(test_handle_with_diagnostics(1));
            let cause = PendingCause::in_flight_work("test");
            ctx.set_pending(cause);
            ctx.set_cancelled();
            ctx.signal_terminal();
            ctx.signal_terminal();

            let stats = ctx.pending_stats().expect("summary diagnostics enabled");
            assert_eq!(stats.terminal_cause, Some(cause));
            assert_eq!(stats.category(PendingCategory::InFlightWork).count, 1);
        }

        // Builds a client handle: dropping the scheduler's ready set is not miri-clean.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn terminal_report_can_be_claimed_once() {
            let (ctx, _rx) = TransferContext::new(test_handle());

            assert!(ctx.claim_terminal_report());
            assert!(!ctx.claim_terminal_report());
        }

        /// A new context's `elapsed` advances; after `signal_terminal` it does
        /// not. The first check fails a context that records its finish at
        /// creation, the second one that never records it. The 5 ms sleeps
        /// exceed any monotonic clock step.
        #[cfg_attr(miri, ignore)]
        #[test]
        fn signal_terminal_stops_elapsed() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            let before = ctx.metrics().elapsed;
            std::thread::sleep(std::time::Duration::from_millis(5));
            assert!(
                ctx.metrics().elapsed > before,
                "elapsed must advance before the transfer finishes"
            );
            ctx.set_completed();
            ctx.signal_terminal();
            let finished = ctx.metrics().elapsed;
            std::thread::sleep(std::time::Duration::from_millis(5));
            assert_eq!(
                ctx.metrics().elapsed,
                finished,
                "signal_terminal must record the finish"
            );
        }

        #[cfg_attr(miri, ignore)]
        #[test]
        fn set_total_bytes() {
            let handle = test_handle();
            let (ctx, _rx) = TransferContext::new(handle);
            assert_eq!(ctx.metrics().total_bytes, None);
            ctx.set_total_bytes(42);
            assert_eq!(ctx.metrics().total_bytes, Some(42));
        }
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use super::wake_flag::WakeFlag;
    use loom::sync::atomic::{AtomicBool, Ordering};
    use loom::sync::{Arc, Mutex};
    use loom::thread;

    /// Harness wrapping the real `WakeFlag` with a simulated gated
    /// resource (a `Mutex<u32>` where 0 = blocked and non-zero = unblocked).
    struct Harness {
        flag: WakeFlag,
        state: Mutex<u32>,
        wake_fired: AtomicBool,
    }

    impl Harness {
        fn new() -> Self {
            Self {
                flag: WakeFlag::new(),
                state: Mutex::new(0),
                wake_fired: AtomicBool::new(false),
            }
        }

        /// Deliver a wake iff the flag was pending. Mirrors the production
        /// `TransferContext::try_wake` pattern without dragging the full
        /// scheduler into the test.
        fn try_wake(&self) {
            if self.flag.take_pending() {
                self.wake_fired.store(true, Ordering::Release);
            }
        }
    }

    /// If the mutator runs after the poller set the pending flag, the
    /// poller's later return of `PollWork::Pending` must be matched by a
    /// delivered wake. Verifies the poller+mutator disciplines prevent
    /// the lost-wake state.
    #[test]
    fn set_pending_then_try_wake_no_lost_wake() {
        loom::model(|| {
            let harness = Arc::new(Harness::new());

            let h2 = harness.clone();
            let poller = thread::spawn(move || {
                // Poller discipline: inside the critical section, set
                // pending first, then check the gating condition.
                let guard = h2.state.lock().unwrap();
                h2.flag.set_pending();
                let blocked = *guard == 0;
                drop(guard);
                // Returns true if the poller would have returned Pending.
                blocked
            });

            let h3 = harness.clone();
            let mutator = thread::spawn(move || {
                // Mutator discipline: lock, mutate, unlock, try_wake.
                {
                    let mut guard = h3.state.lock().unwrap();
                    *guard = 1;
                }
                h3.try_wake();
            });

            let poller_returned_pending = poller.join().unwrap();
            mutator.join().unwrap();

            let mutated = *harness.state.lock().unwrap() == 1;
            let wake_fired = harness.wake_fired.load(Ordering::Acquire);

            // If the poller committed to Pending and the mutator unblocked
            // the state, a wake must have been delivered. Otherwise the
            // poller is stuck forever.
            if poller_returned_pending && mutated {
                assert!(
                    wake_fired,
                    "lost wake: poller returned Pending, state was mutated, but wake did not fire"
                );
            }
        });
    }
}