asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
//! Retry combinator with exponential backoff.
//!
//! The retry combinator wraps a fallible operation with configurable retry logic
//! including exponential backoff, jitter, and attempt limits.
//!
//! # Design Philosophy
//!
//! Retries must be:
//! 1. **Cancel-aware**: Respect incoming cancellation between attempts
//! 2. **Budget-aware**: Total retry budget bounds all attempts combined
//! 3. **Deterministic**: Same seed → same jitter in lab runtime
//! 4. **Configurable**: Policy captures retry strategy
//!
//! # Cancellation Handling
//!
//! - Check cancellation status before each attempt
//! - Check cancellation during sleep
//! - If cancelled: do NOT start another attempt, return Cancelled immediately
//! - Any in-flight attempt continues to checkpoint (cannot force-stop)
//!
//! # Budget Integration
//!
//! Total budget for retry operation:
//! ```text
//! retry_budget = Σ(attempt_budget[i] + sleep_budget[i])
//!              = max_attempts * per_attempt_budget + Σ(delays)
//! ```

use crate::cx::Cx;
use crate::time::Sleep;
use crate::types::cancel::CancelReason;
use crate::types::outcome::PanicPayload;
use crate::types::{Outcome, Time};
use crate::util::det_rng::DetRng;
use core::fmt;
use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

/// Policy for retry behavior.
///
/// Configures how retries are performed, including backoff strategy,
/// jitter, and limits.
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    /// Maximum number of attempts (including the first attempt).
    /// Must be at least 1.
    pub max_attempts: u32,
    /// Initial delay before the first retry (after first failure).
    pub initial_delay: Duration,
    /// Maximum delay between retries (caps exponential growth).
    pub max_delay: Duration,
    /// Multiplier for exponential backoff (typically 2.0).
    pub multiplier: f64,
    /// Jitter factor [0.0, 1.0] - random factor added to delay.
    /// A value of 0.1 means up to 10% jitter is added.
    pub jitter: f64,
}

impl RetryPolicy {
    /// Creates a new retry policy with default settings.
    ///
    /// Defaults:
    /// - 3 attempts
    /// - 100ms initial delay
    /// - 30s max delay
    /// - 2.0 multiplier
    /// - 0.1 jitter (10%)
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_attempts: 3,
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            multiplier: 2.0,
            jitter: 0.1,
        }
    }

    /// Creates a policy with the specified number of attempts.
    #[inline]
    #[must_use]
    pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = max_attempts.max(1);
        self
    }

    /// Sets the initial delay for the first retry.
    #[inline]
    #[must_use]
    pub fn with_initial_delay(mut self, delay: Duration) -> Self {
        self.initial_delay = delay;
        self
    }

    /// Sets the maximum delay cap.
    #[inline]
    #[must_use]
    pub fn with_max_delay(mut self, delay: Duration) -> Self {
        self.max_delay = delay;
        self
    }

    /// Sets the backoff multiplier.
    #[inline]
    #[must_use]
    pub fn with_multiplier(mut self, multiplier: f64) -> Self {
        self.multiplier = multiplier.max(1.0);
        self
    }

    /// Sets the jitter factor (0.0 to 1.0).
    #[inline]
    #[must_use]
    pub fn with_jitter(mut self, jitter: f64) -> Self {
        self.jitter = jitter.clamp(0.0, 1.0);
        self
    }

    /// Creates a policy with no jitter (fully deterministic delays).
    #[inline]
    #[must_use]
    pub fn no_jitter(mut self) -> Self {
        self.jitter = 0.0;
        self
    }

    /// Creates a policy with fixed delays (no exponential backoff).
    #[inline]
    #[must_use]
    pub fn fixed_delay(delay: Duration, max_attempts: u32) -> Self {
        Self {
            max_attempts: max_attempts.max(1),
            initial_delay: delay,
            max_delay: delay,
            multiplier: 1.0,
            jitter: 0.0,
        }
    }

    /// Creates a policy for immediate retries (no delay).
    #[inline]
    #[must_use]
    pub fn immediate(max_attempts: u32) -> Self {
        Self {
            max_attempts: max_attempts.max(1),
            initial_delay: Duration::ZERO,
            max_delay: Duration::ZERO,
            multiplier: 1.0,
            jitter: 0.0,
        }
    }

    /// Validates the policy returns Ok if valid, or an error message.
    pub fn validate(&self) -> Result<(), &'static str> {
        if self.max_attempts == 0 {
            return Err("max_attempts must be at least 1");
        }
        if self.multiplier < 1.0 {
            return Err("multiplier must be at least 1.0");
        }
        if !(0.0..=1.0).contains(&self.jitter) {
            return Err("jitter must be between 0.0 and 1.0");
        }
        Ok(())
    }
}

impl Default for RetryPolicy {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Calculates the delay for a given attempt number.
///
/// The delay follows exponential backoff with optional jitter:
/// ```text
/// base_delay = initial_delay * multiplier^(attempt - 1)
/// capped_delay = min(base_delay, max_delay)
/// final_delay = capped_delay * (1 + jitter_factor)
/// ```
///
/// # Arguments
/// * `policy` - The retry policy
/// * `attempt` - The attempt number (1-indexed, so attempt 1 = first retry)
/// * `rng` - Deterministic RNG for jitter (optional)
///
/// # Returns
/// The delay duration for this attempt.
#[must_use]
#[allow(
    clippy::cast_possible_wrap,  // exponent is bounded by practical max_attempts values
    clippy::cast_precision_loss, // acceptable for duration calculations in millisecond-second range
    clippy::cast_sign_loss,      // final_nanos is always positive after min() capping
)]
pub fn calculate_delay(policy: &RetryPolicy, attempt: u32, rng: Option<&mut DetRng>) -> Duration {
    if attempt == 0 {
        return Duration::ZERO;
    }

    // Calculate base delay with exponential backoff
    let exponent = attempt.saturating_sub(1);

    // Safely compute multiplier^exponent, avoiding overflow and non-finite results
    let multiplier_factor = if exponent == 0 {
        1.0
    } else if exponent > 60 || policy.multiplier <= 0.0 || !policy.multiplier.is_finite() {
        // Avoid extremely large exponents or invalid multipliers
        f64::INFINITY
    } else {
        // Limit exponent to reasonable range for powi()
        let safe_exponent = exponent.min(60) as i32;
        let factor = policy.multiplier.powi(safe_exponent);
        if !factor.is_finite() {
            f64::INFINITY
        } else {
            factor
        }
    };

    // Safely convert initial_delay to f64, preserving precision for reasonable values
    let initial_nanos_f64 = if policy.initial_delay.as_nanos() <= (1u64 << 53) as u128 {
        policy.initial_delay.as_nanos() as f64
    } else {
        // Use seconds conversion for very large durations to preserve precision
        policy.initial_delay.as_secs_f64() * 1_000_000_000.0
    };

    let base_nanos = if multiplier_factor.is_infinite() {
        f64::INFINITY
    } else {
        initial_nanos_f64 * multiplier_factor
    };

    // Cap at max_delay
    let max_nanos = policy.max_delay.as_nanos() as f64;
    let capped_nanos = base_nanos.min(max_nanos);

    // Apply jitter if enabled and RNG provided
    let final_nanos = if policy.jitter > 0.0 && capped_nanos.is_finite() {
        rng.map_or(capped_nanos, |rng| {
            // Generate deterministic jitter factor in [0, jitter] with precision-safe division
            let rand_val = rng.next_u64();
            // Use high-precision division avoiding direct u64::MAX cast
            let normalized = if rand_val == u64::MAX {
                1.0
            } else {
                rand_val as f64 / (u64::MAX as f64)
            };
            let jitter_factor = normalized * policy.jitter;

            let result = capped_nanos * (1.0 + jitter_factor);
            if result.is_finite() {
                result
            } else {
                capped_nanos
            }
        })
    } else {
        capped_nanos
    };

    Duration::from_nanos(clamp_nanos_f64(final_nanos))
}

#[allow(
    clippy::cast_precision_loss, // clamp boundary requires f64 comparison
    clippy::cast_sign_loss,      // negative/NaN handled above before cast
)]
fn clamp_nanos_f64(nanos: f64) -> u64 {
    if !nanos.is_finite() || nanos <= 0.0 {
        return 0;
    }
    if nanos >= u64::MAX as f64 {
        return u64::MAX;
    }
    nanos as u64
}

/// Calculates the delay and returns the deadline.
///
/// Convenience function that adds the delay to the current time.
#[must_use]
pub fn calculate_deadline(
    policy: &RetryPolicy,
    attempt: u32,
    now: Time,
    rng: Option<&mut DetRng>,
) -> Time {
    let delay = calculate_delay(policy, attempt, rng);
    let nanos = delay.as_nanos();
    let safe_nanos = if nanos <= u128::from(u64::MAX) {
        nanos as u64
    } else {
        u64::MAX
    };
    now.saturating_add_nanos(safe_nanos)
}

/// Calculates the total worst-case budget needed for all retries.
///
/// This is the sum of all delays across max_attempts - 1 retries.
/// Note: The first attempt has no delay before it.
#[must_use]
#[allow(clippy::cast_precision_loss, clippy::cast_sign_loss)]
pub fn total_delay_budget(policy: &RetryPolicy) -> Duration {
    let mut total = Duration::ZERO;
    for attempt in 1..policy.max_attempts {
        // Use None for RNG to get base delays (upper bound without jitter)
        let delay = calculate_delay(policy, attempt, None);
        // With jitter, actual delay could be up to (1 + jitter) * base
        let max_delay_nanos = clamp_nanos_f64(delay.as_nanos() as f64 * (1.0 + policy.jitter));
        let additional = Duration::from_nanos(max_delay_nanos);

        total = total.saturating_add(additional);

        if delay == policy.max_delay || total == Duration::MAX {
            // remaining loop iterations: the loop runs 1..max_attempts, so at
            // position `attempt` there are (max_attempts - 1 - attempt) left.
            let remaining_iters = (policy.max_attempts - 1).saturating_sub(attempt);
            if let Some(rest) = additional.checked_mul(remaining_iters) {
                total = total.saturating_add(rest);
            } else {
                total = Duration::MAX;
            }
            break;
        }
    }
    total
}

/// Error type for retry operations.
///
/// Contains the final error after all attempts exhausted, plus metadata
/// about the retry history.
#[derive(Debug, Clone)]
pub struct RetryError<E> {
    /// The error from the final attempt.
    pub final_error: E,
    /// Number of attempts made.
    pub attempts: u32,
    /// Total time spent retrying (not including operation time).
    pub total_delay: Duration,
}

impl<E> RetryError<E> {
    /// Creates a new retry error.
    #[must_use]
    pub const fn new(final_error: E, attempts: u32, total_delay: Duration) -> Self {
        Self {
            final_error,
            attempts,
            total_delay,
        }
    }

    /// Maps the error type.
    pub fn map<F, G: FnOnce(E) -> F>(self, f: G) -> RetryError<F> {
        RetryError {
            final_error: f(self.final_error),
            attempts: self.attempts,
            total_delay: self.total_delay,
        }
    }
}

impl<E: fmt::Display> fmt::Display for RetryError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "retry failed after {} attempts ({:?} total delay): {}",
            self.attempts, self.total_delay, self.final_error
        )
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for RetryError<E> {}

// ─── Token Bucket for Retry Rate Limiting ──────────────────────────────────

/// Token bucket for rate-limiting retry attempts.
///
/// Prevents retry storms by limiting the rate at which retries can be attempted.
/// Uses a classic token bucket algorithm where tokens refill at a steady rate
/// and operations consume tokens.
#[derive(Debug, Clone)]
pub struct RetryTokenBucket {
    /// Maximum number of tokens the bucket can hold.
    capacity: u32,
    /// Current number of available tokens.
    tokens: f64,
    /// Rate at which tokens are refilled (tokens per second).
    refill_rate: f64,
    /// Last time the bucket was refilled.
    last_refill: Time,
}

impl RetryTokenBucket {
    /// Creates a new token bucket with the specified capacity and refill rate.
    ///
    /// # Arguments
    /// * `capacity` - Maximum tokens the bucket can hold
    /// * `refill_rate` - Tokens added per second
    /// * `now` - Current time
    #[must_use]
    pub fn new(capacity: u32, refill_rate: f64, now: Time) -> Self {
        Self {
            capacity,
            tokens: capacity as f64, // Start with full bucket
            refill_rate,
            last_refill: now,
        }
    }

    /// Attempts to consume tokens from the bucket.
    ///
    /// Returns `true` if the tokens were successfully consumed, `false` otherwise.
    /// The bucket is automatically refilled based on time elapsed since last update.
    pub fn try_consume(&mut self, cost: u32, now: Time) -> bool {
        self.refill(now);

        if self.tokens >= cost as f64 {
            self.tokens -= cost as f64;
            true
        } else {
            false
        }
    }

    /// Calculates when the next token will be available.
    ///
    /// Returns the duration to wait before enough tokens are available.
    #[must_use]
    pub fn time_to_tokens(&self, cost: u32) -> Duration {
        if self.tokens >= cost as f64 {
            return Duration::ZERO;
        }

        let tokens_needed = cost as f64 - self.tokens;
        let time_needed_secs = tokens_needed / self.refill_rate;
        Duration::from_secs_f64(time_needed_secs)
    }

    /// Refills the bucket based on time elapsed.
    fn refill(&mut self, now: Time) {
        let elapsed_nanos = now.duration_since(self.last_refill);
        let elapsed_secs = elapsed_nanos as f64 / 1_000_000_000.0;

        let tokens_to_add = elapsed_secs * self.refill_rate;
        self.tokens = (self.tokens + tokens_to_add).min(self.capacity as f64);
        self.last_refill = now;
    }

    /// Returns the current number of available tokens.
    #[must_use]
    pub fn available_tokens(&self) -> u32 {
        self.tokens.floor() as u32
    }

    /// Returns the bucket capacity.
    #[must_use]
    pub const fn capacity(&self) -> u32 {
        self.capacity
    }

    /// Returns the refill rate (tokens per second).
    #[must_use]
    pub const fn refill_rate(&self) -> f64 {
        self.refill_rate
    }
}

/// Policy that includes token bucket rate limiting for retries.
#[derive(Debug, Clone)]
pub struct RateLimitedRetryPolicy {
    /// Base retry policy (backoff, attempts, etc.).
    pub retry_policy: RetryPolicy,
    /// Optional token bucket for rate limiting.
    pub token_bucket: Option<(u32, f64)>, // (capacity, refill_rate)
}

impl RateLimitedRetryPolicy {
    /// Creates a new rate-limited retry policy.
    #[must_use]
    pub fn new(retry_policy: RetryPolicy) -> Self {
        Self {
            retry_policy,
            token_bucket: None,
        }
    }

    /// Adds token bucket rate limiting.
    ///
    /// # Arguments
    /// * `capacity` - Maximum tokens in bucket
    /// * `refill_rate` - Tokens added per second
    #[must_use]
    pub fn with_token_bucket(mut self, capacity: u32, refill_rate: f64) -> Self {
        self.token_bucket = Some((capacity, refill_rate));
        self
    }
}

impl Default for RateLimitedRetryPolicy {
    fn default() -> Self {
        Self::new(RetryPolicy::default())
    }
}

/// Result type for retry operations, including cancellation.
#[derive(Debug, Clone)]
pub enum RetryResult<T, E> {
    /// Operation succeeded (possibly after retries).
    Ok(T),
    /// All attempts failed.
    Failed(RetryError<E>),
    /// Operation was cancelled.
    Cancelled(CancelReason),
    /// Operation panicked.
    Panicked(PanicPayload),
}

impl<T, E> RetryResult<T, E> {
    /// Returns true if the operation succeeded.
    #[inline]
    #[must_use]
    pub const fn is_ok(&self) -> bool {
        matches!(self, Self::Ok(_))
    }

    /// Returns true if all attempts failed.
    #[inline]
    #[must_use]
    pub const fn is_failed(&self) -> bool {
        matches!(self, Self::Failed(_))
    }

    /// Returns true if the operation was cancelled.
    #[inline]
    #[must_use]
    pub const fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled(_))
    }

    /// Returns true if the operation panicked.
    #[inline]
    #[must_use]
    pub const fn is_panicked(&self) -> bool {
        matches!(self, Self::Panicked(_))
    }

    /// Converts to an Outcome.
    #[inline]
    pub fn into_outcome(self) -> Outcome<T, RetryError<E>> {
        match self {
            Self::Ok(v) => Outcome::Ok(v),
            Self::Failed(e) => Outcome::Err(e),
            Self::Cancelled(r) => Outcome::Cancelled(r),
            Self::Panicked(p) => Outcome::Panicked(p),
        }
    }

    /// Converts to a standard Result.
    pub fn into_result(self) -> Result<T, RetryFailure<E>> {
        match self {
            Self::Ok(v) => Ok(v),
            Self::Failed(e) => Err(RetryFailure::Exhausted(e)),
            Self::Cancelled(r) => Err(RetryFailure::Cancelled(r)),
            Self::Panicked(p) => Err(RetryFailure::Panicked(p)),
        }
    }
}

/// Comprehensive failure type for retry operations.
#[derive(Debug, Clone)]
pub enum RetryFailure<E> {
    /// All retry attempts exhausted.
    Exhausted(RetryError<E>),
    /// Operation was cancelled.
    Cancelled(CancelReason),
    /// Operation panicked.
    Panicked(PanicPayload),
}

impl<E: fmt::Display> fmt::Display for RetryFailure<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Exhausted(e) => write!(f, "{e}"),
            Self::Cancelled(r) => write!(f, "retry cancelled: {r}"),
            Self::Panicked(p) => write!(f, "retry panicked: {p}"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for RetryFailure<E> {}

/// Tracks the state of a retry operation in progress.
#[derive(Debug, Clone)]
pub struct RetryState {
    /// Current attempt number (1-indexed).
    pub attempt: u32,
    /// Total delay accumulated so far.
    pub total_delay: Duration,
    /// Whether the retry was cancelled.
    pub cancelled: bool,
    /// The policy being used.
    policy: RetryPolicy,
}

impl RetryState {
    /// Creates a new retry state with the given policy.
    #[must_use]
    pub fn new(mut policy: RetryPolicy) -> Self {
        policy.max_attempts = policy.max_attempts.max(1);
        Self {
            attempt: 0,
            total_delay: Duration::ZERO,
            cancelled: false,
            policy,
        }
    }

    /// Returns true if more attempts are available.
    #[inline]
    #[must_use]
    pub fn has_attempts_remaining(&self) -> bool {
        !self.cancelled && self.attempt < self.policy.max_attempts
    }

    /// Returns the number of attempts remaining.
    #[inline]
    #[must_use]
    pub fn attempts_remaining(&self) -> u32 {
        if self.cancelled {
            0
        } else {
            self.policy.max_attempts.saturating_sub(self.attempt)
        }
    }

    /// Advances to the next attempt and returns the delay to wait.
    ///
    /// Returns `None` if no more attempts are available.
    pub fn next_attempt(&mut self, rng: Option<&mut DetRng>) -> Option<Duration> {
        if !self.has_attempts_remaining() {
            return None;
        }

        self.attempt += 1;

        // First attempt has no delay
        if self.attempt == 1 {
            return Some(Duration::ZERO);
        }

        // Calculate delay for retry
        let delay = calculate_delay(&self.policy, self.attempt - 1, rng);
        self.total_delay = self.total_delay.saturating_add(delay);
        Some(delay)
    }

    /// Marks the retry as cancelled.
    pub fn cancel(&mut self) {
        self.cancelled = true;
    }

    /// Creates a RetryError from the current state and final error.
    #[must_use]
    pub fn into_error<E>(self, final_error: E) -> RetryError<E> {
        RetryError::new(final_error, self.attempt, self.total_delay)
    }

    /// Returns the policy being used.
    #[inline]
    #[must_use]
    pub const fn policy(&self) -> &RetryPolicy {
        &self.policy
    }
}

/// Constructs a `RetryResult` from an outcome and retry state.
///
/// This function is used to map the outcome of a single attempt into
/// the appropriate retry result, taking into account whether more
/// attempts are available.
///
/// # Arguments
/// * `outcome` - The outcome from the most recent attempt
/// * `state` - The current retry state
/// * `is_final` - Whether this is the final attempt (no more retries available)
pub fn make_retry_result<T, E>(
    outcome: Outcome<T, E>,
    state: &RetryState,
    is_final: bool,
) -> Option<RetryResult<T, E>> {
    match outcome {
        Outcome::Ok(v) => Some(RetryResult::Ok(v)),
        Outcome::Err(e) => {
            if is_final {
                Some(RetryResult::Failed(RetryError::new(
                    e,
                    state.attempt,
                    state.total_delay,
                )))
            } else {
                // Not final, should retry
                None
            }
        }
        Outcome::Cancelled(r) => Some(RetryResult::Cancelled(r)),
        Outcome::Panicked(p) => Some(RetryResult::Panicked(p)),
    }
}

/// Determines if an error should be retried based on a predicate.
///
/// This allows selective retry based on error type (e.g., only retry
/// transient errors, not permanent failures).
pub trait RetryPredicate<E> {
    /// Returns true if the error should trigger a retry.
    fn should_retry(&self, error: &E, attempt: u32) -> bool;
}

/// Always retry on any error.
#[derive(Debug, Clone, Copy, Default)]
pub struct AlwaysRetry;

impl<E> RetryPredicate<E> for AlwaysRetry {
    fn should_retry(&self, _error: &E, _attempt: u32) -> bool {
        true
    }
}

/// Never retry (effectively max_attempts = 1).
#[derive(Debug, Clone, Copy, Default)]
pub struct NeverRetry;

impl<E> RetryPredicate<E> for NeverRetry {
    fn should_retry(&self, _error: &E, _attempt: u32) -> bool {
        false
    }
}

/// Retry based on a closure.
#[derive(Debug, Clone, Copy)]
pub struct RetryIf<F>(pub F);

impl<E, F: Fn(&E, u32) -> bool> RetryPredicate<E> for RetryIf<F> {
    fn should_retry(&self, error: &E, attempt: u32) -> bool {
        (self.0)(error, attempt)
    }
}

/// Internal state machine for the retry future.
#[pin_project(project = RetryInnerProj)]
enum RetryInner<F> {
    /// No operation in progress, ready to start next attempt.
    Idle,
    /// Polling the inner future.
    Polling(#[pin] F),
    /// Sleeping before the next attempt.
    Sleeping(#[pin] Sleep),
    /// Finished executing.
    Completed,
}

/// A future that executes a retry loop.
///
/// This struct is created by the [`retry`] function.
#[pin_project]
pub struct Retry<F, Fut, P, Pred> {
    factory: F,
    policy: P,
    predicate: Pred,
    state: RetryState,
    #[pin]
    inner: RetryInner<Fut>,
}

impl<F, Fut, P, Pred> Retry<F, Fut, P, Pred>
where
    P: Clone + Into<RetryPolicy>,
{
    fn new(factory: F, policy: P, predicate: Pred) -> Self {
        let policy_val = policy.clone().into();
        Self {
            factory,
            policy,
            predicate,
            state: RetryState::new(policy_val),
            inner: RetryInner::Idle,
        }
    }
}

impl<F, Fut, P, Pred, T, E> Future for Retry<F, Fut, P, Pred>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Outcome<T, E>>,
    P: Clone + Into<RetryPolicy>,
    Pred: RetryPredicate<E>,
{
    type Output = RetryResult<T, E>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            // Check cancellation from the context
            // WARNING: We must NOT force-drop the inner future if we are in Polling state,
            // because asupersync requires futures to be drained to Outcome::Cancelled.
            let cancel_reason = Cx::current().and_then(|c| {
                if c.checkpoint().is_err() {
                    Some(c.cancel_reason().unwrap_or_default())
                } else {
                    None
                }
            });

            let mut this = self.as_mut().project();

            match this.inner.as_mut().project() {
                RetryInnerProj::Completed => {
                    return Poll::Ready(RetryResult::Cancelled(CancelReason::user(
                        "polled after completion",
                    )));
                }
                RetryInnerProj::Idle => {
                    if let Some(r) = cancel_reason {
                        this.inner.set(RetryInner::Completed);
                        return Poll::Ready(RetryResult::Cancelled(r));
                    }

                    // Start next attempt or sleep
                    // Use Cx entropy if available
                    let mut rng = Cx::current().map(|c| DetRng::new(c.random_u64()));

                    if let Some(delay) = this.state.next_attempt(rng.as_mut()) {
                        if delay == Duration::ZERO {
                            // Start immediately
                            let fut = (this.factory)();
                            this.inner.set(RetryInner::Polling(fut));
                        } else {
                            // Sleep before starting
                            // Cx::current() will be used by Sleep internally
                            // We need to construct Sleep with a relative duration from "now"
                            // Sleep::after handles getting the time source correctly
                            let now = Cx::current().map_or_else(crate::time::wall_now, |current| {
                                current
                                    .timer_driver()
                                    .map_or_else(crate::time::wall_now, |driver| driver.now())
                            });

                            let sleep = Sleep::after(now, delay);
                            this.inner.set(RetryInner::Sleeping(sleep));
                        }
                    } else {
                        // This case is unreachable because we only transition to Idle
                        // if has_attempts_remaining() is true, or initially (attempt=0)
                        // where max_attempts >= 1.
                        unreachable!(
                            "Retry logic invariant violated: Idle state with no remaining attempts"
                        );
                    }
                }
                RetryInnerProj::Sleeping(sleep) => {
                    if let Some(r) = cancel_reason {
                        this.inner.set(RetryInner::Completed);
                        return Poll::Ready(RetryResult::Cancelled(r));
                    }
                    match sleep.poll(cx) {
                        Poll::Ready(()) => {
                            // Sleep done, start factory
                            let fut = (this.factory)();
                            this.inner.set(RetryInner::Polling(fut));
                        }
                        Poll::Pending => return Poll::Pending,
                    }
                }
                RetryInnerProj::Polling(fut) => {
                    match fut.poll(cx) {
                        Poll::Ready(outcome) => {
                            match outcome {
                                Outcome::Ok(val) => {
                                    this.inner.set(RetryInner::Completed);
                                    return Poll::Ready(RetryResult::Ok(val));
                                }
                                Outcome::Err(e) => {
                                    let attempt = this.state.attempt;
                                    // Check predicate
                                    if this.predicate.should_retry(&e, attempt)
                                        && this.state.has_attempts_remaining()
                                    {
                                        // Retry
                                        this.inner.set(RetryInner::Idle);
                                        // Loop will handle Idle -> Sleeping/Polling
                                    } else {
                                        // Final failure
                                        this.inner.set(RetryInner::Completed);
                                        return Poll::Ready(RetryResult::Failed(
                                            this.state.clone().into_error(e),
                                        ));
                                    }
                                }
                                Outcome::Cancelled(r) => {
                                    this.inner.set(RetryInner::Completed);
                                    return Poll::Ready(RetryResult::Cancelled(r));
                                }
                                Outcome::Panicked(p) => {
                                    this.inner.set(RetryInner::Completed);
                                    return Poll::Ready(RetryResult::Panicked(p));
                                }
                            }
                        }
                        Poll::Pending => return Poll::Pending,
                    }
                }
            }
        }
    }
}

/// Creates a retry future.
///
/// # Arguments
/// * `policy` - Retry policy (max attempts, delay, jitter).
/// * `predicate` - Logic to decide if an error is retriable.
/// * `factory` - Closure that produces the future to retry.
pub fn retry<F, Fut, P, Pred>(policy: P, predicate: Pred, factory: F) -> Retry<F, Fut, P, Pred>
where
    F: FnMut() -> Fut,
    P: Into<RetryPolicy> + Clone,
{
    Retry::new(factory, policy, predicate)
}

/// Retries an operation with configurable backoff.
///
/// # Semantics
///
/// ```ignore
/// let result = retry!(
///     attempts: 3,
///     backoff: exponential(100ms, 2.0),
///     || operation()
/// ).await;
/// ```
///
/// - Retries up to `max_attempts` times
/// - Waits `delay` between attempts (optionally with exponential backoff)
/// - Returns first success, or last error after exhausting retries
/// - Respects cancellation during both operation and delay
#[macro_export]
macro_rules! retry {
    // Simple syntax: retry!(max_attempts, || operation())
    ($max:expr, $factory:expr) => {
        $crate::combinator::retry::retry(
            $crate::combinator::retry::RetryPolicy::new().with_max_attempts($max),
            $crate::combinator::retry::AlwaysRetry,
            $factory,
        )
    };

    // With predicate: retry!(max_attempts, predicate, || operation())
    ($max:expr, $predicate:expr, $factory:expr) => {
        $crate::combinator::retry::retry(
            $crate::combinator::retry::RetryPolicy::new().with_max_attempts($max),
            $predicate,
            $factory,
        )
    };
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    #[test]
    fn policy_defaults() {
        let policy = RetryPolicy::new();
        assert_eq!(policy.max_attempts, 3);
        assert_eq!(policy.initial_delay, Duration::from_millis(100));
        assert_eq!(policy.max_delay, Duration::from_secs(30));
        assert!((policy.multiplier - 2.0).abs() < f64::EPSILON);
        assert!((policy.jitter - 0.1).abs() < f64::EPSILON);
    }

    #[test]
    fn policy_builder() {
        let policy = RetryPolicy::new()
            .with_max_attempts(5)
            .with_initial_delay(Duration::from_millis(50))
            .with_max_delay(Duration::from_secs(10))
            .with_multiplier(3.0)
            .with_jitter(0.2);

        assert_eq!(policy.max_attempts, 5);
        assert_eq!(policy.initial_delay, Duration::from_millis(50));
        assert_eq!(policy.max_delay, Duration::from_secs(10));
        assert!((policy.multiplier - 3.0).abs() < f64::EPSILON);
        assert!((policy.jitter - 0.2).abs() < f64::EPSILON);
    }

    #[test]
    fn policy_fixed_delay() {
        let policy = RetryPolicy::fixed_delay(Duration::from_millis(100), 3);
        assert_eq!(policy.max_attempts, 3);
        assert_eq!(policy.initial_delay, Duration::from_millis(100));
        assert_eq!(policy.max_delay, Duration::from_millis(100));
        assert!((policy.multiplier - 1.0).abs() < f64::EPSILON);
        assert!((policy.jitter - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn policy_immediate() {
        let policy = RetryPolicy::immediate(5);
        assert_eq!(policy.max_attempts, 5);
        assert_eq!(policy.initial_delay, Duration::ZERO);
        assert_eq!(policy.max_delay, Duration::ZERO);
    }

    #[test]
    fn policy_validation() {
        let valid = RetryPolicy::new();
        assert!(valid.validate().is_ok());

        let mut invalid = RetryPolicy::new();
        invalid.max_attempts = 0;
        assert!(invalid.validate().is_err());

        invalid = RetryPolicy::new();
        invalid.multiplier = 0.5;
        assert!(invalid.validate().is_err());

        invalid = RetryPolicy::new();
        invalid.jitter = 1.5;
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn calculate_delay_zero_attempt() {
        let policy = RetryPolicy::new();
        let delay = calculate_delay(&policy, 0, None);
        assert_eq!(delay, Duration::ZERO);
    }

    #[test]
    fn calculate_delay_exponential() {
        let policy = RetryPolicy::new()
            .with_initial_delay(Duration::from_millis(100))
            .with_multiplier(2.0)
            .with_max_delay(Duration::from_secs(30))
            .no_jitter();

        // Attempt 1: 100ms
        let delay1 = calculate_delay(&policy, 1, None);
        assert_eq!(delay1, Duration::from_millis(100));

        // Attempt 2: 100 * 2 = 200ms
        let delay2 = calculate_delay(&policy, 2, None);
        assert_eq!(delay2, Duration::from_millis(200));

        // Attempt 3: 100 * 4 = 400ms
        let delay3 = calculate_delay(&policy, 3, None);
        assert_eq!(delay3, Duration::from_millis(400));

        // Attempt 4: 100 * 8 = 800ms
        let delay4 = calculate_delay(&policy, 4, None);
        assert_eq!(delay4, Duration::from_millis(800));
    }

    #[test]
    fn calculate_delay_capped() {
        let policy = RetryPolicy::new()
            .with_initial_delay(Duration::from_secs(1))
            .with_multiplier(10.0)
            .with_max_delay(Duration::from_secs(5))
            .no_jitter();

        // Attempt 1: 1s
        let delay1 = calculate_delay(&policy, 1, None);
        assert_eq!(delay1, Duration::from_secs(1));

        // Attempt 2: 1 * 10 = 10s, but capped at 5s
        let delay2 = calculate_delay(&policy, 2, None);
        assert_eq!(delay2, Duration::from_secs(5));

        // Attempt 3: would be 100s, still capped at 5s
        let delay3 = calculate_delay(&policy, 3, None);
        assert_eq!(delay3, Duration::from_secs(5));
    }

    #[test]
    fn calculate_delay_deterministic_jitter() {
        let policy = RetryPolicy::new()
            .with_initial_delay(Duration::from_millis(100))
            .with_jitter(0.1);

        let mut rng1 = DetRng::new(42);
        let mut rng2 = DetRng::new(42);

        // Same seed should produce same jittered delays
        let first_from_rng1 = calculate_delay(&policy, 1, Some(&mut rng1));
        let first_from_rng2 = calculate_delay(&policy, 1, Some(&mut rng2));
        assert_eq!(first_from_rng1, first_from_rng2);

        let second_from_rng1 = calculate_delay(&policy, 2, Some(&mut rng1));
        let second_from_rng2 = calculate_delay(&policy, 2, Some(&mut rng2));
        assert_eq!(second_from_rng1, second_from_rng2);
    }

    #[test]
    fn calculate_delay_jitter_within_bounds() {
        let policy = RetryPolicy::new()
            .with_initial_delay(Duration::from_millis(100))
            .with_jitter(0.1);

        let mut rng = DetRng::new(12345);
        let base_delay = Duration::from_millis(100);
        let max_with_jitter = Duration::from_millis(110); // 100 * 1.1

        for _ in 0..100 {
            let delay = calculate_delay(&policy, 1, Some(&mut rng));
            assert!(delay >= base_delay);
            assert!(delay <= max_with_jitter);
        }
    }

    #[test]
    fn total_delay_budget_calculation() {
        let policy = RetryPolicy::new()
            .with_max_attempts(4)
            .with_initial_delay(Duration::from_millis(100))
            .with_multiplier(2.0)
            .with_max_delay(Duration::from_secs(30))
            .no_jitter();

        // Delays: attempt 1=100ms, attempt 2=200ms, attempt 3=400ms
        // Total: 100 + 200 + 400 = 700ms (for 3 retries after first attempt)
        let budget = total_delay_budget(&policy);
        assert_eq!(budget, Duration::from_millis(700));
    }

    #[test]
    fn retry_error_display() {
        let err = RetryError::new("connection failed", 3, Duration::from_millis(300));
        let display = err.to_string();
        assert!(display.contains("3 attempts"));
        assert!(display.contains("connection failed"));
    }

    #[test]
    fn retry_error_map() {
        let err = RetryError::new("error", 2, Duration::from_millis(100));
        let mapped = err.map(str::len);
        assert_eq!(mapped.final_error, 5);
        assert_eq!(mapped.attempts, 2);
    }

    #[test]
    fn retry_result_conversions() {
        let ok: RetryResult<i32, &str> = RetryResult::Ok(42);
        assert!(ok.is_ok());
        assert!(!ok.is_failed());
        assert!(!ok.is_cancelled());

        let failed: RetryResult<i32, &str> =
            RetryResult::Failed(RetryError::new("error", 3, Duration::ZERO));
        assert!(!failed.is_ok());
        assert!(failed.is_failed());

        let cancelled: RetryResult<i32, &str> = RetryResult::Cancelled(CancelReason::timeout());
        assert!(!cancelled.is_ok());
        assert!(cancelled.is_cancelled());
    }

    #[test]
    fn retry_result_into_outcome() {
        let ok: RetryResult<i32, &str> = RetryResult::Ok(42);
        let outcome = ok.into_outcome();
        assert!(outcome.is_ok());

        let failed: RetryResult<i32, &str> =
            RetryResult::Failed(RetryError::new("error", 3, Duration::ZERO));
        let outcome = failed.into_outcome();
        assert!(outcome.is_err());
    }

    #[test]
    fn retry_result_into_result() {
        let ok: RetryResult<i32, &str> = RetryResult::Ok(42);
        let result = ok.into_result();
        assert_eq!(result.unwrap(), 42);

        let failed: RetryResult<i32, &str> =
            RetryResult::Failed(RetryError::new("error", 3, Duration::ZERO));
        let result = failed.into_result();
        assert!(matches!(result, Err(RetryFailure::Exhausted(_))));
    }

    #[test]
    fn retry_state_tracks_attempts() {
        let policy = RetryPolicy::new().with_max_attempts(3);
        let mut state = RetryState::new(policy);

        assert_eq!(state.attempt, 0);
        assert!(state.has_attempts_remaining());
        assert_eq!(state.attempts_remaining(), 3);

        // First attempt
        let delay = state.next_attempt(None);
        assert_eq!(delay, Some(Duration::ZERO));
        assert_eq!(state.attempt, 1);
        assert!(state.has_attempts_remaining());

        // Second attempt (first retry)
        let delay = state.next_attempt(None);
        assert!(delay.is_some());
        assert!(delay.unwrap() > Duration::ZERO);
        assert_eq!(state.attempt, 2);
        assert!(state.has_attempts_remaining());

        // Third attempt (second retry)
        let delay = state.next_attempt(None);
        assert!(delay.is_some());
        assert_eq!(state.attempt, 3);
        assert!(!state.has_attempts_remaining());

        // No more attempts
        let delay = state.next_attempt(None);
        assert!(delay.is_none());
    }

    #[test]
    fn retry_policy_builders_clamp_out_of_range_values() {
        let policy = RetryPolicy::new()
            .with_max_attempts(0)
            .with_multiplier(0.25)
            .with_jitter(-1.0);

        assert_eq!(policy.max_attempts, 1);
        assert_eq!(policy.multiplier, 1.0);
        assert_eq!(policy.jitter, 0.0);

        let policy = RetryPolicy::new().with_jitter(2.0);
        assert_eq!(policy.jitter, 1.0);
    }

    #[test]
    fn mr_retry_state_total_delay_matches_calculated_retry_prefixes() {
        let policy = RetryPolicy::new()
            .with_max_attempts(5)
            .with_initial_delay(Duration::from_millis(10))
            .with_multiplier(3.0)
            .with_max_delay(Duration::from_millis(100))
            .no_jitter();
        let mut state = RetryState::new(policy.clone());
        let mut expected_total = Duration::ZERO;

        for attempt in 1..=policy.max_attempts {
            let observed_delay = state
                .next_attempt(None)
                .expect("attempt should be available before max_attempts");
            let expected_delay = if attempt == 1 {
                Duration::ZERO
            } else {
                calculate_delay(&policy, attempt - 1, None)
            };

            expected_total = expected_total.saturating_add(expected_delay);
            assert_eq!(
                observed_delay, expected_delay,
                "retry attempt {attempt} returned an unexpected delay"
            );
            assert_eq!(
                state.total_delay, expected_total,
                "retry total delay should equal the calculated prefix sum after attempt {attempt}",
            );
        }

        assert!(state.next_attempt(None).is_none());
    }

    #[test]
    fn retry_state_cancel() {
        let policy = RetryPolicy::new().with_max_attempts(3);
        let mut state = RetryState::new(policy);

        assert!(state.has_attempts_remaining());

        state.cancel();

        assert!(!state.has_attempts_remaining());
        assert_eq!(state.attempts_remaining(), 0);
        assert!(state.next_attempt(None).is_none());
    }

    #[test]
    fn retry_state_into_error() {
        let policy = RetryPolicy::new().with_max_attempts(3);
        let mut state = RetryState::new(policy);

        state.next_attempt(None); // attempt 1
        state.next_attempt(None); // attempt 2

        let error = state.into_error("failed");
        assert_eq!(error.final_error, "failed");
        assert_eq!(error.attempts, 2);
    }

    #[test]
    fn make_retry_result_success() {
        let state = RetryState::new(RetryPolicy::new());
        let outcome: Outcome<i32, &str> = Outcome::Ok(42);
        let result = make_retry_result(outcome, &state, false);
        assert!(matches!(result, Some(RetryResult::Ok(42))));
    }

    #[test]
    fn make_retry_result_error_not_final() {
        let state = RetryState::new(RetryPolicy::new());
        let outcome: Outcome<i32, &str> = Outcome::Err("error");
        let result = make_retry_result(outcome, &state, false);
        assert!(result.is_none()); // Should retry
    }

    #[test]
    fn make_retry_result_error_final() {
        let policy = RetryPolicy::new().with_max_attempts(3);
        let mut state = RetryState::new(policy);
        state.next_attempt(None);
        state.next_attempt(None);
        state.next_attempt(None);

        let outcome: Outcome<i32, &str> = Outcome::Err("error");
        let result = make_retry_result(outcome, &state, true);
        assert!(matches!(result, Some(RetryResult::Failed(_))));
    }

    #[test]
    fn make_retry_result_cancelled() {
        let state = RetryState::new(RetryPolicy::new());
        let outcome: Outcome<i32, &str> = Outcome::Cancelled(CancelReason::timeout());
        let result = make_retry_result(outcome, &state, false);
        assert!(matches!(result, Some(RetryResult::Cancelled(_))));
    }

    #[test]
    fn retry_predicates() {
        let always = AlwaysRetry;
        assert!(always.should_retry(&"any error", 1));
        assert!(always.should_retry(&"any error", 100));

        let never = NeverRetry;
        assert!(!never.should_retry(&"any error", 1));

        let retry_if = RetryIf(|e: &&str, _| e.contains("transient"));
        assert!(retry_if.should_retry(&"transient error", 1));
        assert!(!retry_if.should_retry(&"permanent error", 1));
    }

    #[test]
    fn retry_failure_display() {
        let exhausted: RetryFailure<&str> =
            RetryFailure::Exhausted(RetryError::new("error", 3, Duration::ZERO));
        assert!(exhausted.to_string().contains("3 attempts"));

        let cancelled: RetryFailure<&str> = RetryFailure::Cancelled(CancelReason::timeout());
        assert!(cancelled.to_string().contains("cancelled"));
    }

    #[test]
    fn calculate_deadline_adds_delay() {
        let policy = RetryPolicy::new()
            .with_initial_delay(Duration::from_millis(100))
            .no_jitter();

        let now = Time::from_nanos(1_000_000_000); // 1 second
        let deadline = calculate_deadline(&policy, 1, now, None);

        // Should be now + 100ms
        let expected = Time::from_nanos(1_100_000_000);
        assert_eq!(deadline, expected);
    }

    #[test]
    fn fixed_delay_consistent() {
        let policy = RetryPolicy::fixed_delay(Duration::from_millis(500), 5);

        // All delays should be 500ms
        for attempt in 1..=4 {
            let delay = calculate_delay(&policy, attempt, None);
            assert_eq!(delay, Duration::from_millis(500));
        }
    }

    #[test]
    fn retry_policy_debug_clone() {
        let p = RetryPolicy::new();
        let dbg = format!("{p:?}");
        assert!(dbg.contains("RetryPolicy"), "{dbg}");
        let cloned = p;
        assert_eq!(format!("{cloned:?}"), dbg);
    }

    #[test]
    fn always_retry_debug_clone_copy_default() {
        let a = AlwaysRetry;
        let dbg = format!("{a:?}");
        assert!(dbg.contains("AlwaysRetry"), "{dbg}");
        let copied: AlwaysRetry = a;
        let cloned = a;
        let _ = (copied, cloned);
    }

    #[test]
    fn never_retry_debug_clone_copy_default() {
        let n = NeverRetry;
        let dbg = format!("{n:?}");
        assert!(dbg.contains("NeverRetry"), "{dbg}");
        let copied: NeverRetry = n;
        let cloned = n;
        let _ = (copied, cloned);
    }

    #[test]
    fn retry_state_debug_clone() {
        let s = RetryState::new(RetryPolicy::new());
        let dbg = format!("{s:?}");
        assert!(dbg.contains("RetryState"), "{dbg}");
        let cloned = s;
        assert_eq!(format!("{cloned:?}"), dbg);
    }

    #[test]
    fn test_retry_execution() {
        // Use a counter to fail the first 2 times, then succeed
        // Must use Arc/Mutex or cell because the closure is called multiple times
        // and FnMut allows mutating state.
        let mut attempts = 0;

        let future = retry(
            RetryPolicy::new()
                .with_max_attempts(3)
                .no_jitter()
                .with_initial_delay(Duration::ZERO),
            AlwaysRetry,
            move || {
                attempts += 1;
                let current_attempt = attempts;
                std::future::ready(if current_attempt < 3 {
                    Outcome::Err("fail")
                } else {
                    Outcome::Ok(42)
                })
            },
        );

        let result = futures_lite::future::block_on(future);
        assert!(result.is_ok());
        if let RetryResult::Ok(val) = result {
            assert_eq!(val, 42);
        }
    }

    #[test]
    fn test_retry_exhausted() {
        // Always fail
        let future = retry(
            RetryPolicy::new()
                .with_max_attempts(3)
                .no_jitter()
                .with_initial_delay(Duration::ZERO),
            AlwaysRetry,
            || std::future::ready(Outcome::<i32, &str>::Err("fail forever")),
        );

        let result = futures_lite::future::block_on(future);
        assert!(result.is_failed());
        if let RetryResult::Failed(err) = result {
            assert_eq!(err.attempts, 3);
            assert_eq!(err.final_error, "fail forever");
        }
    }

    // ─── Token Bucket Golden Tests ──────────────────────────────────────────

    mod token_bucket_golden_tests {
        use super::*;

        /// Helper to create a consistent test time baseline
        fn test_time_baseline() -> Time {
            Time::from_millis(1_000_000) // 1M ms = 1000 seconds
        }

        /// Golden test 1: Token refill rate respected
        ///
        /// Verifies that tokens are refilled at the exact rate specified.
        /// Tests deterministic timing across different intervals.
        #[test]
        fn golden_token_refill_rate_respected() {
            let capacity = 10;
            let refill_rate = 5.0; // 5 tokens per second
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Start with empty bucket
            let _ = bucket.try_consume(10, test_time_baseline());
            assert_eq!(bucket.available_tokens(), 0);

            // After 1 second, should have 5 tokens
            let time_1s = test_time_baseline() + Duration::from_secs(1);
            bucket.refill(time_1s);
            assert_eq!(bucket.available_tokens(), 5);

            // After 2 seconds total, should have 10 tokens (capped)
            let time_2s = test_time_baseline() + Duration::from_secs(2);
            bucket.refill(time_2s);
            assert_eq!(bucket.available_tokens(), 10);

            // After 0.5 seconds more, should still have 10 tokens (at capacity)
            let time_2_5s = time_2s + Duration::from_millis(500);
            bucket.refill(time_2_5s);
            assert_eq!(bucket.available_tokens(), 10);

            // Consume 8 tokens, leaving 2
            assert!(bucket.try_consume(8, time_2_5s));
            assert_eq!(bucket.available_tokens(), 2);

            // After 0.4 seconds, should have 2 + (0.4 * 5) = 4 tokens
            let time_2_9s = time_2_5s + Duration::from_millis(400);
            bucket.refill(time_2_9s);
            assert_eq!(bucket.available_tokens(), 4);

            // Golden assertion: exact refill rate
            assert_golden_token_refill_rate(refill_rate, &bucket, time_2_9s);
        }

        fn assert_golden_token_refill_rate(
            expected_rate: f64,
            bucket: &RetryTokenBucket,
            _now: Time,
        ) {
            const EPSILON: f64 = 0.001;
            let actual_rate = bucket.refill_rate();
            assert!(
                (actual_rate - expected_rate).abs() < EPSILON,
                "Golden token refill rate mismatch: expected {}, got {}",
                expected_rate,
                actual_rate
            );
        }

        /// Golden test 2: Burst absorbs exact bucket capacity
        ///
        /// Verifies that the bucket can handle burst traffic up to its exact capacity
        /// and no more.
        #[test]
        fn golden_burst_absorbs_exact_capacity() {
            let capacity = 5;
            let refill_rate = 1.0; // 1 token per second
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Should be able to consume exactly the capacity in one burst
            assert!(bucket.try_consume(capacity, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), 0);

            // Should not be able to consume any more immediately
            assert!(!bucket.try_consume(1, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), 0);

            // Reset bucket to full
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Should not be able to consume more than capacity
            assert!(!bucket.try_consume(capacity + 1, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), capacity); // Should remain unchanged

            // Golden assertion: exact capacity handling
            assert_golden_burst_capacity(capacity, bucket.capacity());
        }

        fn assert_golden_burst_capacity(expected_capacity: u32, actual_capacity: u32) {
            assert_eq!(
                actual_capacity, expected_capacity,
                "Golden burst capacity mismatch: expected {}, got {}",
                expected_capacity, actual_capacity
            );
        }

        /// Golden test 3: Exhausted bucket blocks with Retry-After signal
        ///
        /// Verifies that when the bucket is exhausted, it provides accurate
        /// timing information about when tokens will be available.
        #[test]
        fn golden_exhausted_bucket_blocks_with_retry_after() {
            let capacity = 3;
            let refill_rate = 2.0; // 2 tokens per second
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Exhaust the bucket
            assert!(bucket.try_consume(capacity, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), 0);

            // Try to consume 1 token - should fail
            assert!(!bucket.try_consume(1, test_time_baseline()));

            // Check retry-after signal
            let retry_after = bucket.time_to_tokens(1);
            let expected_retry_after = Duration::from_millis(500); // 1 token at 2 tokens/sec = 0.5s

            assert_golden_retry_after_signal(expected_retry_after, retry_after);

            // Try to consume 2 tokens - should need longer wait
            let retry_after_2 = bucket.time_to_tokens(2);
            let expected_retry_after_2 = Duration::from_secs(1); // 2 tokens at 2 tokens/sec = 1s

            assert_golden_retry_after_signal(expected_retry_after_2, retry_after_2);

            // Partially refill and check again
            let time_quarter_sec = test_time_baseline() + Duration::from_millis(250);
            bucket.refill(time_quarter_sec);
            assert_eq!(bucket.available_tokens(), 0); // 0.25 * 2 = 0.5 tokens, floor = 0

            let retry_after_partial = bucket.time_to_tokens(1);
            let expected_partial = Duration::from_millis(250); // Need 0.5 more tokens = 0.25s

            assert_golden_retry_after_signal(expected_partial, retry_after_partial);
        }

        fn assert_golden_retry_after_signal(expected: Duration, actual: Duration) {
            let tolerance = Duration::from_millis(1); // 1ms tolerance for floating point
            let diff = actual
                .checked_sub(expected)
                .unwrap_or_else(|| expected.checked_sub(actual).unwrap());
            assert!(
                diff <= tolerance,
                "Golden retry-after signal mismatch: expected {:?}, got {:?}, diff {:?}",
                expected,
                actual,
                diff
            );
        }

        /// Golden test 4: Tokens consumed atomically per retry
        ///
        /// Verifies that token consumption is atomic - either the full cost
        /// is consumed or nothing is consumed.
        #[test]
        fn golden_tokens_consumed_atomically() {
            let capacity = 5;
            let refill_rate = 1.0;
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Start with 3 tokens
            assert!(bucket.try_consume(2, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), 3);

            // Try to consume 4 tokens atomically - should fail and leave bucket unchanged
            let tokens_before = bucket.available_tokens();
            assert!(!bucket.try_consume(4, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), tokens_before);

            // Try to consume 3 tokens atomically - should succeed
            assert!(bucket.try_consume(3, test_time_baseline()));
            assert_eq!(bucket.available_tokens(), 0);

            // Multiple atomic operations in sequence
            let mut bucket = RetryTokenBucket::new(10, 5.0, test_time_baseline());

            let operations = vec![3, 2, 1, 4]; // Total: 10 tokens
            for cost in operations {
                assert!(
                    bucket.try_consume(cost, test_time_baseline()),
                    "Should be able to consume {} tokens atomically",
                    cost
                );
            }
            assert_eq!(bucket.available_tokens(), 0);

            assert_golden_atomic_consumption(&bucket);
        }

        fn assert_golden_atomic_consumption(bucket: &RetryTokenBucket) {
            // All tokens should be consumed (demonstrating atomic behavior)
            assert_eq!(
                bucket.available_tokens(),
                0,
                "Golden atomic consumption: all tokens should be consumed atomically"
            );
        }

        /// Golden test 5: LabRuntime replay identical
        ///
        /// Verifies that token bucket behavior is deterministic and replay-identical
        /// when using the same time sequence.
        #[test]
        fn golden_lab_runtime_replay_identical() {
            let capacity = 4;
            let refill_rate = 2.0;
            let time_sequence = vec![
                test_time_baseline(),
                test_time_baseline() + Duration::from_millis(500),
                test_time_baseline() + Duration::from_millis(1000),
                test_time_baseline() + Duration::from_millis(1500),
                test_time_baseline() + Duration::from_millis(2000),
            ];

            // First execution
            let mut bucket1 = RetryTokenBucket::new(capacity, refill_rate, time_sequence[0]);
            let mut trace1 = Vec::new();

            for &time in &time_sequence[1..] {
                let before_tokens = bucket1.available_tokens();
                bucket1.refill(time);
                let after_tokens = bucket1.available_tokens();
                let consumed = bucket1.try_consume(1, time);
                let final_tokens = bucket1.available_tokens();

                trace1.push((before_tokens, after_tokens, consumed, final_tokens));
            }

            // Second execution (replay)
            let mut bucket2 = RetryTokenBucket::new(capacity, refill_rate, time_sequence[0]);
            let mut trace2 = Vec::new();

            for &time in &time_sequence[1..] {
                let before_tokens = bucket2.available_tokens();
                bucket2.refill(time);
                let after_tokens = bucket2.available_tokens();
                let consumed = bucket2.try_consume(1, time);
                let final_tokens = bucket2.available_tokens();

                trace2.push((before_tokens, after_tokens, consumed, final_tokens));
            }

            // Golden assertion: traces must be identical
            assert_golden_replay_identical(&trace1, &trace2);

            // Additional determinism test with complex pattern
            let complex_pattern = vec![
                (test_time_baseline(), 2),
                (test_time_baseline() + Duration::from_millis(333), 1),
                (test_time_baseline() + Duration::from_millis(666), 3),
                (test_time_baseline() + Duration::from_millis(1000), 1),
            ];

            let trace_a = execute_token_bucket_pattern(capacity, refill_rate, &complex_pattern);
            let trace_b = execute_token_bucket_pattern(capacity, refill_rate, &complex_pattern);

            assert_golden_replay_identical(&trace_a, &trace_b);
        }

        fn execute_token_bucket_pattern(
            capacity: u32,
            refill_rate: f64,
            pattern: &[(Time, u32)],
        ) -> Vec<(bool, u32)> {
            if pattern.is_empty() {
                return Vec::new();
            }

            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, pattern[0].0);
            let mut trace = Vec::new();

            for &(time, cost) in &pattern[1..] {
                bucket.refill(time);
                let consumed = bucket.try_consume(cost, time);
                let remaining = bucket.available_tokens();
                trace.push((consumed, remaining));
            }

            trace
        }

        fn assert_golden_replay_identical<T: PartialEq + std::fmt::Debug>(
            trace1: &[T],
            trace2: &[T],
        ) {
            assert_eq!(
                trace1.len(),
                trace2.len(),
                "Golden replay traces have different lengths"
            );

            for (i, (t1, t2)) in trace1.iter().zip(trace2).enumerate() {
                assert_eq!(
                    t1, t2,
                    "Golden replay mismatch at step {}: {:?} != {:?}",
                    i, t1, t2
                );
            }
        }

        /// Composite golden test: All token bucket properties together
        ///
        /// Tests multiple properties in combination to catch interaction bugs.
        #[test]
        fn golden_composite_token_bucket_properties() {
            let capacity = 6;
            let refill_rate = 3.0; // 3 tokens per second
            let mut bucket = RetryTokenBucket::new(capacity, refill_rate, test_time_baseline());

            // Property 1 + 2: Burst capacity + refill rate
            assert!(bucket.try_consume(capacity, test_time_baseline())); // Use full burst
            assert_eq!(bucket.available_tokens(), 0);

            // Property 3: Retry-after when exhausted
            let retry_after = bucket.time_to_tokens(3);
            assert_eq!(retry_after, Duration::from_secs(1)); // 3 tokens at 3 tokens/sec

            // Property 1: Refill rate over time
            let time_1s = test_time_baseline() + Duration::from_secs(1);
            bucket.refill(time_1s);
            assert_eq!(bucket.available_tokens(), 3);

            // Property 4: Atomic consumption
            assert!(bucket.try_consume(3, time_1s)); // Should consume all 3 atomically
            assert_eq!(bucket.available_tokens(), 0);

            assert!(!bucket.try_consume(1, time_1s)); // Should fail atomically

            // Property 5: Deterministic behavior
            let time_2s = test_time_baseline() + Duration::from_secs(2);
            bucket.refill(time_2s);
            assert_eq!(bucket.available_tokens(), 3); // Predictable refill

            // All properties maintained together
            assert_golden_composite_properties(&bucket, capacity, refill_rate);
        }

        fn assert_golden_composite_properties(
            bucket: &RetryTokenBucket,
            expected_capacity: u32,
            expected_refill_rate: f64,
        ) {
            assert_eq!(bucket.capacity(), expected_capacity);
            assert!((bucket.refill_rate() - expected_refill_rate).abs() < 0.001);
            assert!(bucket.available_tokens() <= expected_capacity);
        }
    }

    // =========================================================================
    // Metamorphic relations for calculate_delay:
    // backoff monotonicity, cap invariance, jitter bounds.
    //
    // Oracle problem: expected absolute delay is specified only up to the
    // documented formula, which is sensitive to f64 rounding across
    // multiplier^n paths. Relations between delays under input transforms
    // (attempt, multiplier, jitter, seed) are deterministic and exactly
    // checkable and therefore stronger than a single-point oracle.
    // =========================================================================

    mod backoff_jitter_mr {
        use super::super::*;
        use crate::util::det_rng::DetRng;
        use std::time::Duration;

        fn base_policy() -> RetryPolicy {
            RetryPolicy {
                max_attempts: 32,
                initial_delay: Duration::from_millis(10),
                max_delay: Duration::from_secs(600),
                multiplier: 2.0,
                jitter: 0.0,
            }
        }

        /// MR1 — Base backoff is monotonically non-decreasing in `attempt`.
        /// With jitter disabled and multiplier ≥ 1.0, calculate_delay(_, a+1, None)
        /// ≥ calculate_delay(_, a, None) for every a ≥ 1.
        #[test]
        fn mr_monotonic_non_decreasing_in_attempt_without_jitter() {
            for &multiplier in &[1.0_f64, 1.25, 1.5, 2.0, 3.0, 10.0] {
                let policy = RetryPolicy {
                    multiplier,
                    jitter: 0.0,
                    ..base_policy()
                };
                let mut prev = calculate_delay(&policy, 1, None);
                for attempt in 2..=32 {
                    let next = calculate_delay(&policy, attempt, None);
                    assert!(
                        next >= prev,
                        "attempt {attempt} produced smaller delay than {}: multiplier={multiplier}, prev={prev:?}, next={next:?}",
                        attempt - 1,
                    );
                    prev = next;
                }
            }
        }

        /// MR2 — Cap invariance: once base ≥ max_delay, further attempts
        /// stay pinned at max_delay (exactly, not just ≤).
        #[test]
        fn mr_cap_invariant_after_saturation() {
            let policy = RetryPolicy {
                initial_delay: Duration::from_millis(10),
                multiplier: 2.0,
                max_delay: Duration::from_millis(160), // saturates at attempt 5
                jitter: 0.0,
                ..base_policy()
            };
            let saturated = calculate_delay(&policy, 5, None);
            assert_eq!(saturated, policy.max_delay);
            for attempt in 6..=32 {
                let d = calculate_delay(&policy, attempt, None);
                assert_eq!(
                    d, policy.max_delay,
                    "attempt {attempt} exceeded cap: expected {:?}, got {d:?}",
                    policy.max_delay,
                );
            }
        }

        /// MR3 — Attempt 0 is always Duration::ZERO regardless of other
        /// parameters or jitter RNG state.
        #[test]
        fn mr_attempt_zero_is_always_zero() {
            let mut rng = DetRng::new(0xDEAD_BEEF);
            for &jitter in &[0.0_f64, 0.1, 0.5, 1.0] {
                let policy = RetryPolicy {
                    jitter,
                    ..base_policy()
                };
                assert_eq!(
                    calculate_delay(&policy, 0, None),
                    Duration::ZERO,
                    "attempt 0 without RNG was non-zero at jitter={jitter}",
                );
                assert_eq!(
                    calculate_delay(&policy, 0, Some(&mut rng)),
                    Duration::ZERO,
                    "attempt 0 with RNG was non-zero at jitter={jitter}",
                );
            }
        }

        /// MR4 — Jitter is additive, never subtractive.
        /// For any jitter factor j ∈ (0, 1] and any RNG state, the jittered
        /// delay is at least the un-jittered base delay at the same attempt.
        #[test]
        fn mr_jitter_never_shrinks_below_base() {
            for &jitter in &[0.05_f64, 0.1, 0.25, 0.5, 1.0] {
                let no_jitter_policy = RetryPolicy {
                    jitter: 0.0,
                    ..base_policy()
                };
                let jittered_policy = RetryPolicy {
                    jitter,
                    ..base_policy()
                };
                for seed in 0u64..16 {
                    for attempt in 1..=8u32 {
                        let mut rng = DetRng::new(seed);
                        let base = calculate_delay(&no_jitter_policy, attempt, None);
                        let jittered = calculate_delay(&jittered_policy, attempt, Some(&mut rng));
                        assert!(
                            jittered >= base,
                            "jitter shrank below base at attempt={attempt} seed={seed} jitter={jitter}: base={base:?}, jittered={jittered:?}",
                        );
                    }
                }
            }
        }

        /// MR5 — Jitter upper bound: jittered delay ≤ base * (1 + jitter).
        /// Tolerate one-nanosecond rounding from the f64 → u64 cast.
        #[test]
        fn mr_jitter_bounded_above_by_base_times_one_plus_jitter() {
            for &jitter in &[0.05_f64, 0.1, 0.25, 0.5, 1.0] {
                let no_jitter_policy = RetryPolicy {
                    jitter: 0.0,
                    ..base_policy()
                };
                let jittered_policy = RetryPolicy {
                    jitter,
                    ..base_policy()
                };
                for seed in 0u64..16 {
                    for attempt in 1..=8u32 {
                        let mut rng = DetRng::new(seed);
                        let base = calculate_delay(&no_jitter_policy, attempt, None);
                        let jittered = calculate_delay(&jittered_policy, attempt, Some(&mut rng));
                        // base_nanos * (1 + jitter), with +1 ns slack for the
                        // single floor-cast inside calculate_delay.
                        #[allow(clippy::cast_precision_loss, clippy::cast_sign_loss)]
                        let upper_nanos =
                            (base.as_nanos() as f64 * (1.0 + jitter)).ceil() as u128 + 1;
                        assert!(
                            jittered.as_nanos() <= upper_nanos,
                            "jitter exceeded upper bound at attempt={attempt} seed={seed} jitter={jitter}: base={base:?}, jittered={jittered:?}, upper_nanos={upper_nanos}",
                        );
                    }
                }
            }
        }

        /// MR6 — Determinism under identical seeds.
        /// Two runs of calculate_delay with the same policy, attempt, and seed
        /// produce exactly the same Duration.
        #[test]
        fn mr_same_seed_same_delay() {
            let policy = RetryPolicy {
                jitter: 0.25,
                ..base_policy()
            };
            for seed in 0u64..32 {
                for attempt in 1..=8u32 {
                    let mut rng_a = DetRng::new(seed);
                    let mut rng_b = DetRng::new(seed);
                    let da = calculate_delay(&policy, attempt, Some(&mut rng_a));
                    let db = calculate_delay(&policy, attempt, Some(&mut rng_b));
                    assert_eq!(
                        da, db,
                        "determinism violated at seed={seed} attempt={attempt}: {da:?} vs {db:?}",
                    );
                }
            }
        }

        /// MR7 — Multiplier monotonicity.
        /// Holding (initial_delay, attempt, max_delay) fixed and jitter=0,
        /// increasing multiplier ≥ 1 monotonically grows (or preserves) delay
        /// up to the max_delay cap.
        #[test]
        fn mr_larger_multiplier_never_shrinks_pre_cap_delay() {
            let multipliers = [1.0_f64, 1.25, 1.5, 2.0, 3.0, 5.0];
            // Pick a max_delay large enough that attempts 1..=3 stay below cap.
            let policy_at = |multiplier: f64| RetryPolicy {
                initial_delay: Duration::from_millis(10),
                multiplier,
                max_delay: Duration::from_secs(60 * 60),
                jitter: 0.0,
                ..base_policy()
            };
            for attempt in 1..=3u32 {
                let mut prev = calculate_delay(&policy_at(multipliers[0]), attempt, None);
                for &mult in &multipliers[1..] {
                    let next = calculate_delay(&policy_at(mult), attempt, None);
                    assert!(
                        next >= prev,
                        "multiplier {mult} produced smaller delay than a smaller multiplier at attempt={attempt}: prev={prev:?}, next={next:?}",
                    );
                    prev = next;
                }
            }
        }

        /// MR8 — Composition: (monotonic-in-attempt) ∘ (jitter-upper-bound).
        /// For every seed, a jittered delay at attempt a+1 must not fall
        /// below the un-jittered base at attempt a. This would catch a
        /// sign-flip in the jitter formula AND a reversed attempt exponent
        /// simultaneously.
        #[test]
        fn mr_composite_jittered_attempt_plus_one_ge_base_attempt() {
            let policy_base = RetryPolicy {
                jitter: 0.0,
                ..base_policy()
            };
            let policy_jittered = RetryPolicy {
                jitter: 0.5,
                ..base_policy()
            };
            for seed in 0u64..16 {
                for attempt in 1..=6u32 {
                    let base_now = calculate_delay(&policy_base, attempt, None);
                    let mut rng = DetRng::new(seed);
                    let jittered_next =
                        calculate_delay(&policy_jittered, attempt + 1, Some(&mut rng));
                    assert!(
                        jittered_next >= base_now,
                        "composite MR violated: seed={seed} attempt={attempt} base(a)={base_now:?} jittered(a+1)={jittered_next:?}",
                    );
                }
            }
        }
    }

    // =========================================================================
    // Retry-budget invariant conformance (Pattern 4: spec-derived).
    //
    // Spec: retry.rs doc comments lines 21-27 state:
    //   retry_budget = Σ(attempt_budget[i] + sleep_budget[i])
    //                = max_attempts * per_attempt_budget + Σ(delays)
    //
    // This suite covers the Σ(delays) component — i.e., total_delay_budget
    // and the validate() pre-conditions that keep the budget formula
    // well-defined. Each test maps to exactly one MUST/SHOULD clause and
    // emits a structured JSON-line for CI parsing.
    // =========================================================================

    mod retry_budget_conformance {
        use super::*;

        /// Compute the expected worst-case jittered budget straight from
        /// the documented formula (not the implementation).
        fn reference_budget(policy: &RetryPolicy) -> Duration {
            let mut total = Duration::ZERO;
            for attempt in 1..policy.max_attempts {
                let base = calculate_delay(policy, attempt, None);
                #[allow(clippy::cast_precision_loss, clippy::cast_sign_loss)]
                let jittered_nanos = (base.as_nanos() as f64) * (1.0 + policy.jitter);
                let jittered =
                    Duration::from_nanos(jittered_nanos.min(u64::MAX as f64).max(0.0) as u64);
                total = total.saturating_add(jittered);
            }
            total
        }

        /// RETRY-BUDGET-1 (MUST): total_delay_budget equals
        ///   Σ(calculate_delay(i) * (1 + jitter)) for i in 1..max_attempts.
        ///
        /// Tolerate 1-nanosecond slack per attempt to absorb the f64→u64
        /// cast in clamp_nanos_f64 vs the reference formula's own casts.
        #[test]
        fn retry_budget_1_matches_documented_formula() {
            let policies = [
                RetryPolicy::default(),
                RetryPolicy::fixed_delay(Duration::from_millis(50), 5),
                RetryPolicy::immediate(8),
                RetryPolicy::new()
                    .with_max_attempts(6)
                    .with_initial_delay(Duration::from_micros(500))
                    .with_multiplier(3.0)
                    .with_max_delay(Duration::from_secs(10))
                    .no_jitter(),
                RetryPolicy::new()
                    .with_max_attempts(4)
                    .with_initial_delay(Duration::from_millis(10))
                    .with_multiplier(2.0)
                    .with_max_delay(Duration::from_secs(60))
                    .with_jitter(0.5),
            ];
            for (i, policy) in policies.iter().enumerate() {
                let got = total_delay_budget(policy);
                let want = reference_budget(policy);
                let slack = Duration::from_nanos(policy.max_attempts.saturating_sub(1) as u64);
                let diff = got.abs_diff(want);
                assert!(
                    diff <= slack,
                    "RETRY-BUDGET-1 case {i}: budget {got:?} diverged from reference {want:?} by {diff:?} (slack {slack:?})",
                );
            }
        }

        /// RETRY-BUDGET-2 (MUST): total_delay_budget is monotonically
        /// non-decreasing as max_attempts grows, holding other fields fixed.
        #[test]
        fn retry_budget_2_monotonic_in_max_attempts() {
            let base = RetryPolicy::new()
                .with_initial_delay(Duration::from_millis(20))
                .with_multiplier(2.0)
                .with_max_delay(Duration::from_secs(5))
                .no_jitter();
            let mut prev = total_delay_budget(&base.clone().with_max_attempts(1));
            for attempts in 2..=12u32 {
                let policy = base.clone().with_max_attempts(attempts);
                let got = total_delay_budget(&policy);
                assert!(
                    got >= prev,
                    "RETRY-BUDGET-2: budget shrank from {prev:?} to {got:?} when max_attempts grew from {} to {attempts}",
                    attempts - 1,
                );
                prev = got;
            }
        }

        /// RETRY-BUDGET-3 (MUST): max_attempts = 1 yields Duration::ZERO
        /// (the first attempt has no pre-delay; loop range 1..1 is empty).
        #[test]
        fn retry_budget_3_zero_when_max_attempts_is_one() {
            for multiplier in [1.0_f64, 1.25, 2.0, 5.0] {
                for jitter in [0.0_f64, 0.1, 0.5, 1.0] {
                    let policy = RetryPolicy::new()
                        .with_max_attempts(1)
                        .with_initial_delay(Duration::from_millis(42))
                        .with_multiplier(multiplier)
                        .with_max_delay(Duration::from_secs(30))
                        .with_jitter(jitter);
                    assert_eq!(
                        total_delay_budget(&policy),
                        Duration::ZERO,
                        "RETRY-BUDGET-3: max_attempts=1 must have zero budget (multiplier={multiplier}, jitter={jitter})",
                    );
                }
            }
        }

        /// RETRY-BUDGET-4 (MUST): total budget is bounded above by
        /// (max_attempts - 1) × max_delay × (1 + jitter). The cap
        /// enforces that exponential blow-up of calculated delays cannot
        /// escape max_delay.
        #[test]
        fn retry_budget_4_upper_bound_by_cap_times_count() {
            let policies = [
                RetryPolicy::new()
                    .with_max_attempts(6)
                    .with_initial_delay(Duration::from_millis(10))
                    .with_multiplier(2.0)
                    .with_max_delay(Duration::from_millis(80))
                    .no_jitter(),
                RetryPolicy::new()
                    .with_max_attempts(10)
                    .with_initial_delay(Duration::from_micros(100))
                    .with_multiplier(3.0)
                    .with_max_delay(Duration::from_millis(500))
                    .with_jitter(0.25),
            ];
            for (i, policy) in policies.iter().enumerate() {
                let got = total_delay_budget(policy);
                #[allow(clippy::cast_precision_loss, clippy::cast_sign_loss)]
                let cap_nanos = (policy.max_delay.as_nanos() as f64) * (1.0 + policy.jitter);
                let cap_duration = Duration::from_nanos(cap_nanos.min(u64::MAX as f64) as u64);
                let upper = cap_duration
                    .checked_mul(policy.max_attempts.saturating_sub(1))
                    .unwrap_or(Duration::MAX);
                // 1-nanosecond slack per attempt for f64 rounding.
                let slack = Duration::from_nanos(policy.max_attempts.saturating_sub(1) as u64);
                assert!(
                    got <= upper.saturating_add(slack),
                    "RETRY-BUDGET-4 case {i}: budget {got:?} exceeds cap {upper:?} (slack {slack:?})",
                );
            }
        }

        /// RETRY-BUDGET-5 (MUST): total_delay_budget is a valid upper bound
        /// on any realized accumulated delay sequence under jitter.
        /// For every seed and every attempt index, the cumulative sum of
        /// jittered delays must not exceed the budget.
        #[test]
        fn retry_budget_5_dominates_any_jittered_realization() {
            let policy = RetryPolicy::new()
                .with_max_attempts(8)
                .with_initial_delay(Duration::from_millis(10))
                .with_multiplier(2.0)
                .with_max_delay(Duration::from_millis(200))
                .with_jitter(0.5);
            let budget = total_delay_budget(&policy);
            for seed in 0u64..32 {
                let mut rng = DetRng::new(seed);
                let mut realized = Duration::ZERO;
                for attempt in 1..policy.max_attempts {
                    let d = calculate_delay(&policy, attempt, Some(&mut rng));
                    realized = realized.saturating_add(d);
                }
                // 1-nanosecond slack per attempt.
                let slack = Duration::from_nanos(policy.max_attempts as u64);
                assert!(
                    realized <= budget.saturating_add(slack),
                    "RETRY-BUDGET-5 seed={seed}: realized {realized:?} exceeds budget {budget:?}",
                );
            }
        }

        /// RETRY-BUDGET-6 (MUST): total_delay_budget saturates at
        /// Duration::MAX for extreme inputs rather than panicking or
        /// wrapping around.
        #[test]
        fn retry_budget_6_saturates_without_overflow() {
            let policy = RetryPolicy::new()
                .with_max_attempts(u32::MAX)
                .with_initial_delay(Duration::from_secs(u64::MAX / 4))
                .with_multiplier(2.0)
                .with_max_delay(Duration::MAX)
                .with_jitter(1.0);
            // Must not panic.
            let got = total_delay_budget(&policy);
            assert!(
                got <= Duration::MAX,
                "RETRY-BUDGET-6: budget must remain bounded by Duration::MAX",
            );
        }

        /// RETRY-BUDGET-7 (MUST): validate() rejects configurations that
        /// would make the budget formula ill-defined:
        /// - max_attempts == 0 (formula divides by zero conceptually)
        /// - multiplier < 1.0 (delays could shrink, breaking monotonicity)
        /// - jitter outside [0.0, 1.0] (upper bound breaks)
        #[test]
        fn retry_budget_7_validate_rejects_ill_defined_inputs() {
            // max_attempts = 0 is impossible via builder (clamps to 1),
            // but a direct struct construction must be caught.
            let bad_attempts = RetryPolicy {
                max_attempts: 0,
                ..RetryPolicy::default()
            };
            assert!(
                bad_attempts.validate().is_err(),
                "max_attempts=0 must fail validate"
            );

            let bad_multiplier = RetryPolicy {
                multiplier: 0.5,
                ..RetryPolicy::default()
            };
            assert!(
                bad_multiplier.validate().is_err(),
                "multiplier<1.0 must fail validate",
            );

            let bad_jitter_high = RetryPolicy {
                jitter: 1.5,
                ..RetryPolicy::default()
            };
            assert!(
                bad_jitter_high.validate().is_err(),
                "jitter>1.0 must fail validate",
            );

            let bad_jitter_neg = RetryPolicy {
                jitter: -0.1,
                ..RetryPolicy::default()
            };
            assert!(
                bad_jitter_neg.validate().is_err(),
                "jitter<0.0 must fail validate",
            );

            // NaN jitter: not in [0.0, 1.0] by IEEE 754 comparison rules,
            // so validate() must reject it too.
            let bad_jitter_nan = RetryPolicy {
                jitter: f64::NAN,
                ..RetryPolicy::default()
            };
            assert!(
                bad_jitter_nan.validate().is_err(),
                "jitter=NaN must fail validate",
            );

            // Positive cases: default and common builders must pass.
            assert!(RetryPolicy::default().validate().is_ok());
            assert!(
                RetryPolicy::fixed_delay(Duration::from_millis(10), 3)
                    .validate()
                    .is_ok()
            );
            assert!(RetryPolicy::immediate(5).validate().is_ok());
        }
    }
}