asupersync 0.3.6

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
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
//! Sleep future for delaying execution.
//!
//! The [`Sleep`] future completes after a deadline has passed.
//! It works with both wall clock time (production) and virtual time (lab).
//!
//! # Timer Driver Integration
//!
//! When a timer driver is available via `Cx::current()`, Sleep registers
//! with the driver's timer wheel for efficient wakeups. Without a driver,
//! Sleep falls back to spawning an OS thread for timing (less efficient).

use crate::cx::Cx;
use crate::time::{TimerDriverHandle, TimerHandle};
use crate::trace::TraceEvent;
use crate::types::Time;
use parking_lot::Mutex;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

static START_TIME: OnceLock<Instant> = OnceLock::new();
const CUSTOM_TIME_GETTER_POLL_INTERVAL: Duration = Duration::from_millis(1);

/// Returns the canonical process epoch shared by every wall-clock-based time
/// source in the runtime.
///
/// Both `wall_now`'s capability-free fallback path AND the production
/// [`WallClock`](super::driver::WallClock) (the timer driver the deadline
/// monitor reads) must measure elapsed time from the *same* `Instant`.
/// Otherwise a `Time` produced by one is not comparable to a `Time` produced by
/// the other: e.g. a request-budget deadline computed via `wall_now()` (which
/// may hit this fallback when no timer-driver `Cx` is current) is compared by
/// the deadline monitor against `timer_driver.now()`. If the two anchor to
/// different epochs the skew equals the gap between their creation instants, so
/// once process uptime exceeds the request timeout every such request is born
/// already past its deadline and is cancelled immediately.
///
/// Anchoring both to this single `OnceLock` makes `wall_now` honor its
/// documented contract — "elapsed since the first call to any time-related
/// function in this module" — regardless of which branch it takes. Whichever
/// time source is constructed first (typically the driver's `WallClock` at
/// runtime startup) claims the epoch; all later ones share it.
#[must_use]
pub fn process_epoch() -> Instant {
    *START_TIME.get_or_init(Instant::now)
}

#[derive(Debug)]
struct FallbackThread {
    stop: Arc<AtomicBool>,
    completed: Arc<AtomicBool>,
    thread: std::thread::Thread,
    join: std::thread::JoinHandle<()>,
}

#[inline]
fn request_stop_fallback(fallback: &FallbackThread) {
    fallback.stop.store(true, Ordering::Release);
    fallback.thread.unpark();
}

#[inline]
fn take_finished_fallbacks(state: &mut SleepState) -> Vec<std::thread::JoinHandle<()>> {
    let mut finished = Vec::new();

    // Move logically completed but not yet fully exited threads to zombies
    if let Some(fallback) = state.fallback.as_ref() {
        if fallback.completed.load(Ordering::Acquire) {
            if let Some(fallback) = state.fallback.take() {
                state.zombie_fallbacks.push(fallback.join);
            }
        } else if fallback.join.is_finished() {
            if let Some(fallback) = state.fallback.take() {
                finished.push(fallback.join);
            }
        }
    }

    let mut i = 0;
    while i < state.zombie_fallbacks.len() {
        if state.zombie_fallbacks[i].is_finished() {
            finished.push(state.zombie_fallbacks.remove(i));
        } else {
            i += 1;
        }
    }

    finished
}

#[inline]
fn duration_to_nanos(duration: Duration) -> u64 {
    duration.as_nanos().min(u128::from(u64::MAX)) as u64
}

/// Process-global shared fallback timer (br-asupersync-runtime-cpu-overhaul-5vt09v.3.5).
///
/// A `Sleep` polled with no bound or ambient (`Cx`) timer driver used to spawn a
/// dedicated OS thread *per Sleep* to drive its deadline. A heavy consumer that
/// drives futures off the runtime's worker threads (so `Cx::current()` is `None`)
/// therefore paid a `pthread_create`/`pthread_exit` for every timeout — the
/// thread-per-`sleep` churn the frankenterm-gui profile caught (~37/sec).
///
/// This shared driver replaces that with ONE process-lifetime pump thread that
/// owns the standard wall-clock [`TimerDriver`](super::driver::TimerDriver) and
/// services every off-`Cx` sleep through the same wheel the runtime uses. It is
/// started lazily on the first off-`Cx` wall-clock sleep and never joined.
struct GlobalFallbackTimer {
    driver: TimerDriverHandle,
    pump: std::thread::Thread,
}

static GLOBAL_FALLBACK: OnceLock<GlobalFallbackTimer> = OnceLock::new();

/// Idle park used by the pump when no timers are pending. It only bounds how
/// long the pump sleeps when the wheel is empty; an arriving timer unparks the
/// pump immediately (see `arm` handling in `Sleep::poll`), so this does not
/// delay any registered deadline.
const FALLBACK_PUMP_IDLE_PARK: Duration = Duration::from_millis(250);

/// Returns the process-global shared fallback timer, starting its pump thread on
/// first use.
fn global_fallback_timer() -> &'static GlobalFallbackTimer {
    GLOBAL_FALLBACK.get_or_init(|| {
        let driver = TimerDriverHandle::with_wall_clock();
        let pump_driver = driver.clone();
        // One shared pump replaces N per-Sleep threads; count it once so the
        // `timer_threads_spawned` churn signal reflects reality (1, not N).
        crate::runtime::metrics::record_timer_thread_spawned();
        // ubs:ignore - intentional process-lifetime daemon timer pump shared by all off-Cx sleeps
        let handle = std::thread::Builder::new()
            .name("asupersync-fallback-timer".to_string())
            .spawn(move || fallback_pump_loop(&pump_driver))
            .expect("spawn shared fallback timer pump");
        GlobalFallbackTimer {
            driver,
            pump: handle.thread().clone(),
        }
    })
}

/// The shared fallback pump loop: fire due timers, then park until the next
/// deadline (or `FALLBACK_PUMP_IDLE_PARK` when the wheel is empty). A newly
/// armed sleep unparks this thread, so the park is recomputed against the
/// sooner deadline without busy-polling.
fn fallback_pump_loop(driver: &TimerDriverHandle) -> ! {
    loop {
        let _ = driver.process_timers();
        let park = match driver.next_deadline() {
            Some(deadline) => {
                let now = driver.now().as_nanos();
                let dl = deadline.as_nanos();
                if dl > now {
                    Duration::from_nanos(dl - now)
                } else {
                    // Already due; loop to fire it without parking.
                    continue;
                }
            }
            None => FALLBACK_PUMP_IDLE_PARK,
        };
        std::thread::park_timeout(park);
    }
}

/// Whether `handle` is the process-global shared fallback driver.
#[inline]
fn is_global_fallback_driver(handle: &TimerDriverHandle) -> bool {
    GLOBAL_FALLBACK
        .get()
        .is_some_and(|global| global.driver.ptr_eq(handle))
}

/// br-asupersync-runtime-cpu-overhaul-5vt09v.3.5: fired-once flag for the
/// "no timer driver, falling back to the shared fallback timer" diagnostic.
///
/// The shared fallback timer (above) is a *valid* path for runtimes legitimately
/// built without a timer driver, so taking it is not an error and must not panic
/// (that would break standalone `sleep()` usage and the off-`Cx` fallback tests).
/// But it is *also* exactly the symptom of a mis-configured consumer that forgot
/// to install a timer driver (the frankenterm churn). We therefore surface it as
/// a one-time WARN so the fallback shows up in logs instead of running silently,
/// matching the established `br-asupersync-9nn568` fallback-warn idiom in
/// `runtime::scheduler::three_lane`.
static FALLBACK_TIMER_WARNED: AtomicBool = AtomicBool::new(false);

/// Returns `true` exactly once for a given flag — the first caller observes the
/// `false -> true` transition, every later caller observes `true`. Factored out
/// so the warn-once semantics can be unit-tested deterministically against a
/// local flag without depending on process-global state or a `tracing`
/// subscriber.
#[inline]
fn claim_first_call(flag: &AtomicBool) -> bool {
    !flag.swap(true, Ordering::Relaxed)
}

/// Emit the missing-timer-driver WARN at most once per process.
///
/// Called when a `Sleep` is polled with neither a bound nor an ambient (`Cx`)
/// timer driver and routes through the process-global shared fallback timer.
#[inline]
fn warn_missing_timer_driver_once() {
    if claim_first_call(&FALLBACK_TIMER_WARNED) {
        crate::tracing_compat::warn!(
            target: "asupersync::time::sleep",
            "br-asupersync-runtime-cpu-overhaul-5vt09v.3.5: a Sleep was polled with no bound or \
             ambient (Cx) timer driver; routing through the process-global shared fallback timer. \
             Install a timer driver so timers are driven by the runtime's worker/wheel and stay \
             replay-deterministic in the lab runtime: run sleeps inside a runtime task \
             (RuntimeBuilder installs a wall-clock driver by default and tasks inherit it via Cx), \
             or build the runtime with RuntimeBuilder::enable_time()."
        );
    }
}

/// Returns the current wall clock time.
///
/// This function returns the elapsed time since the first call to any
/// time-related function in this module. It is suitable for production
/// use where real wall clock time is needed.
///
/// **Capability-aware**: First attempts to route through the current `Cx` context
/// and timer driver when available, only falling back to direct `Instant::now()`
/// when no capability context is present. This preserves the "no ambient authority"
/// invariant while still providing a fallback for contexts without capabilities.
///
/// For virtual time in tests/lab runtime, use a timer driver's `now()` method.
#[must_use]
#[inline]
pub fn wall_now() -> Time {
    // First try to route through current Cx capabilities if available
    if let Some(current_cx) = crate::cx::Cx::current() {
        if let Some(timer_driver) = current_cx.timer_driver() {
            return timer_driver.now();
        }
        // A Cx without a timer driver must fall through to the raw wall-clock
        // path. Calling `Cx::now()` here would recurse back through this helper.
    }

    // Absolute fallback: no Cx context or capabilities available.
    // This preserves compatibility for truly capability-free contexts. The
    // epoch is the shared process epoch so this branch stays comparable with
    // the production `WallClock` timer driver (see `process_epoch`).
    let start = process_epoch();
    let now = Instant::now();
    if now < start {
        Time::ZERO
    } else {
        let elapsed = now.duration_since(start);
        Time::from_nanos(duration_to_nanos(elapsed))
    }
}

#[derive(Debug)]
struct SleepState {
    waker: Option<Waker>,
    /// Background timing thread used when no timer driver is present.
    fallback: Option<FallbackThread>,
    /// Threads that have been asked to stop but haven't been joined yet.
    zombie_fallbacks: Vec<std::thread::JoinHandle<()>>,
    /// Handle to the registered timer in the timer driver.
    timer_handle: Option<TimerHandle>,
    /// Timer driver used to register the current handle.
    timer_driver: Option<TimerDriverHandle>,
}

#[derive(Debug)]
struct ReadyWaker {
    ready: Arc<AtomicBool>,
    inner: Waker,
}

use std::task::Wake;
impl Wake for ReadyWaker {
    #[inline]
    fn wake(self: Arc<Self>) {
        self.ready.store(true, Ordering::Release);
        self.inner.wake_by_ref();
    }

    #[inline]
    fn wake_by_ref(self: &Arc<Self>) {
        self.ready.store(true, Ordering::Release);
        self.inner.wake_by_ref();
    }
}

#[inline]
fn readiness_waker(ready: Arc<AtomicBool>, inner: Waker) -> Waker {
    Waker::from(Arc::new(ReadyWaker { ready, inner }))
}

/// A future that completes after a specified deadline.
///
/// `Sleep` is the core primitive for time-based delays. It can be awaited
/// to pause execution until the deadline has passed.
///
/// # Time Sources
///
/// By default, `Sleep` checks time at each poll. The actual time source
/// depends on the runtime context:
/// - Production: Uses wall clock time
/// - Lab runtime: Uses virtual time
///
/// For standalone use without a runtime, you can provide a time getter.
///
/// # Cancel Safety
///
/// `Sleep` is cancel-safe. Dropping it simply stops the wait with no
/// side effects. It can be recreated with the same or a different deadline.
///
/// # Example
///
/// ```ignore
/// use asupersync::time::sleep;
/// use std::time::Duration;
///
/// // Sleep for 100 milliseconds
/// sleep(Duration::from_millis(100)).await;
///
/// // Sleep until a specific time
/// use asupersync::time::sleep_until;
/// use asupersync::types::Time;
/// sleep_until(Time::from_secs(5)).await;
/// ```
#[derive(Debug)]
pub struct Sleep {
    /// The deadline when this sleep completes.
    deadline: Time,
    /// Optional time getter for standalone use.
    /// When None, uses a default mechanism (currently instant check).
    pub(crate) time_getter: Option<fn() -> Time>,
    /// Optional explicit timer driver for capability-bound waits.
    ///
    /// When present, polling does not consult `Cx::current()` for timer
    /// registration or time reads.
    bound_timer_driver: Option<TimerDriverHandle>,
    /// Whether this sleep has been polled at least once.
    /// Used for tracing/debugging.
    polled: std::sync::atomic::AtomicBool,
    /// Whether this sleep has already completed and not yet been reset.
    completed: std::sync::atomic::AtomicBool,
    /// Whether a timer/fallback wake has already made this sleep ready.
    ready: Arc<AtomicBool>,
    /// Shared state for background waiter thread.
    state: Arc<Mutex<SleepState>>,
}

impl Sleep {
    /// Creates a new `Sleep` that completes at the given deadline.
    ///
    /// # Arguments
    ///
    /// * `deadline` - The absolute time when this sleep completes
    ///
    /// # Example
    ///
    /// ```
    /// use asupersync::time::Sleep;
    /// use asupersync::types::Time;
    ///
    /// let sleep = Sleep::new(Time::from_secs(5));
    /// assert_eq!(sleep.deadline(), Time::from_secs(5));
    /// ```
    #[must_use]
    #[inline]
    pub fn new(deadline: Time) -> Self {
        Self {
            deadline,
            time_getter: None,
            bound_timer_driver: None,
            polled: std::sync::atomic::AtomicBool::new(false),
            completed: std::sync::atomic::AtomicBool::new(false),
            ready: Arc::new(AtomicBool::new(false)),
            state: Arc::new(Mutex::new(SleepState {
                waker: None,
                fallback: None,
                zombie_fallbacks: Vec::new(),
                timer_handle: None,
                timer_driver: None,
            })),
        }
    }

    /// Creates a `Sleep` that completes after the given duration from `now`.
    ///
    /// # Arguments
    ///
    /// * `now` - The current time
    /// * `duration` - How long to sleep
    ///
    /// # Example
    ///
    /// ```
    /// use asupersync::time::Sleep;
    /// use asupersync::types::Time;
    /// use std::time::Duration;
    ///
    /// let now = Time::from_secs(10);
    /// let sleep = Sleep::after(now, Duration::from_secs(5));
    /// assert_eq!(sleep.deadline(), Time::from_secs(15));
    /// ```
    #[must_use]
    #[inline]
    pub fn after(now: Time, duration: Duration) -> Self {
        let deadline = now.saturating_add_nanos(duration_to_nanos(duration));
        Self::new(deadline)
    }

    /// Creates a `Sleep` with a custom time getter function.
    ///
    /// This is useful for testing or when you need to control the time source.
    ///
    /// # Arguments
    ///
    /// * `deadline` - The deadline when this sleep completes
    /// * `time_getter` - Function that returns the current time
    #[inline]
    #[must_use]
    pub fn with_time_getter(deadline: Time, time_getter: fn() -> Time) -> Self {
        Self {
            deadline,
            time_getter: Some(time_getter),
            bound_timer_driver: None,
            polled: std::sync::atomic::AtomicBool::new(false),
            completed: std::sync::atomic::AtomicBool::new(false),
            ready: Arc::new(AtomicBool::new(false)),
            state: Arc::new(Mutex::new(SleepState {
                waker: None,
                fallback: None,
                zombie_fallbacks: Vec::new(),
                timer_handle: None,
                timer_driver: None,
            })),
        }
    }

    /// Creates a `Sleep` that is permanently bound to an explicit timer driver.
    ///
    /// This preserves capability-correct timing when the creator needs the
    /// future to keep using the captured driver even if it is later polled
    /// outside that creator's ambient `Cx`.
    #[inline]
    #[must_use]
    pub(crate) fn with_timer_driver(deadline: Time, timer_driver: TimerDriverHandle) -> Self {
        Self {
            deadline,
            time_getter: None,
            bound_timer_driver: Some(timer_driver),
            polled: std::sync::atomic::AtomicBool::new(false),
            completed: std::sync::atomic::AtomicBool::new(false),
            ready: Arc::new(AtomicBool::new(false)),
            state: Arc::new(Mutex::new(SleepState {
                waker: None,
                fallback: None,
                zombie_fallbacks: Vec::new(),
                timer_handle: None,
                timer_driver: None,
            })),
        }
    }

    /// Returns the deadline for this sleep.
    #[inline]
    #[must_use]
    pub const fn deadline(&self) -> Time {
        self.deadline
    }

    /// Returns the remaining duration until the deadline.
    ///
    /// Returns `Duration::ZERO` if the deadline has passed.
    ///
    /// # Arguments
    ///
    /// * `now` - The current time to compare against
    #[inline]
    #[must_use]
    pub fn remaining(&self, now: Time) -> Duration {
        if now >= self.deadline {
            Duration::ZERO
        } else {
            let nanos = self.deadline.as_nanos().saturating_sub(now.as_nanos());
            Duration::from_nanos(nanos)
        }
    }

    /// Checks if the deadline has elapsed.
    ///
    /// # Arguments
    ///
    /// * `now` - The current time to compare against
    #[inline]
    #[must_use]
    pub fn is_elapsed(&self, now: Time) -> bool {
        now >= self.deadline
    }

    /// Resets this sleep to a new deadline.
    ///
    /// This can be used to reuse a `Sleep` instance without allocating a new one.
    /// Any registered timer is cancelled and will be re-registered on next poll.
    #[inline]
    pub fn reset(&mut self, deadline: Time) {
        self.deadline = deadline;
        self.polled
            .store(false, std::sync::atomic::Ordering::Relaxed);
        self.completed
            .store(false, std::sync::atomic::Ordering::Relaxed);
        self.ready = Arc::new(AtomicBool::new(false));
        let (handle, driver, fallback_handles) = {
            let mut state = self.state.lock();
            let mut handles = std::mem::take(&mut state.zombie_fallbacks);
            if let Some(fallback) = state.fallback.take() {
                request_stop_fallback(&fallback);
                handles.push(fallback.join);
            }
            (
                state.timer_handle.take(),
                state.timer_driver.take(),
                handles,
            )
        };

        // Intentionally detach threads to avoid blocking the executor
        drop(fallback_handles);

        // Cancel any existing timer - will be re-registered on next poll
        if let (Some(handle), Some(driver)) = (handle, driver) {
            let trace = Cx::current().and_then(|current| current.trace_buffer());
            if let Some(trace) = trace.as_ref() {
                let now = driver.now();
                trace.record_event(|seq| TraceEvent::timer_cancelled(seq, now, handle.id()));
            }
            let _ = driver.cancel(&handle);
        }
    }

    /// Resets this sleep to complete after the given duration from `now`.
    ///
    /// Any registered timer is cancelled and will be re-registered on next poll.
    #[inline]
    pub fn reset_after(&mut self, now: Time, duration: Duration) {
        self.deadline = now.saturating_add_nanos(duration_to_nanos(duration));
        self.polled
            .store(false, std::sync::atomic::Ordering::Relaxed);
        self.completed
            .store(false, std::sync::atomic::Ordering::Relaxed);
        self.ready = Arc::new(AtomicBool::new(false));
        let (handle, driver, fallback_handles) = {
            let mut state = self.state.lock();
            let mut handles = std::mem::take(&mut state.zombie_fallbacks);
            if let Some(fallback) = state.fallback.take() {
                request_stop_fallback(&fallback);
                handles.push(fallback.join);
            }
            (
                state.timer_handle.take(),
                state.timer_driver.take(),
                handles,
            )
        };

        // Intentionally detach threads to avoid blocking the executor
        drop(fallback_handles);

        // Cancel any existing timer - will be re-registered on next poll
        if let (Some(handle), Some(driver)) = (handle, driver) {
            let trace = Cx::current().and_then(|current| current.trace_buffer());
            if let Some(trace) = trace.as_ref() {
                let now = driver.now();
                trace.record_event(|seq| TraceEvent::timer_cancelled(seq, now, handle.id()));
            }
            let _ = driver.cancel(&handle);
        }
    }

    /// Returns true if this sleep has been polled at least once.
    #[must_use]
    #[inline]
    pub fn was_polled(&self) -> bool {
        self.polled.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Gets the current time using the configured time getter or default.
    #[inline]
    fn current_time(&self) -> Time {
        self.time_getter.map_or_else(wall_now, |getter| getter())
    }

    fn timer_driver_for_poll(&self) -> Option<TimerDriverHandle> {
        self.bound_timer_driver
            .clone()
            .or_else(|| Cx::current().and_then(|current| current.timer_driver()))
    }

    pub(crate) fn has_timer_driver_for_poll(&self) -> bool {
        self.bound_timer_driver.is_some()
            || Cx::current()
                .and_then(|current| current.timer_driver())
                .is_some()
    }

    fn complete_ready_registration(&self, now: Time, timer_driver: Option<TimerDriverHandle>) {
        let (handle, driver) = {
            let mut state = self.state.lock();
            (state.timer_handle.take(), state.timer_driver.clone())
        };
        if let Some(handle) = handle {
            let trace = Cx::current().and_then(|current| current.trace_buffer());
            if let Some(trace) = trace.as_ref() {
                let fired_at = now.max(self.deadline);
                trace.record_event(|seq| TraceEvent::timer_fired(seq, fired_at, handle.id()));
            }
            if let Some(driver) = driver.or(timer_driver) {
                let _ = driver.cancel(&handle);
            }
        }
    }

    /// Returns whether this sleep uses a custom time source.
    #[inline]
    #[must_use]
    pub const fn has_custom_time_getter(&self) -> bool {
        self.time_getter.is_some()
    }

    /// Polls this sleep with an explicit time value.
    ///
    /// This is useful when you want to control the time source manually
    /// rather than using the built-in time getter.
    ///
    /// Returns `Poll::Ready(())` if the deadline has passed.
    pub fn poll_with_time(&self, now: Time) -> Poll<()> {
        assert!(
            !self.completed.load(std::sync::atomic::Ordering::Acquire),
            "Sleep polled after completion"
        );
        self.polled
            .store(true, std::sync::atomic::Ordering::Relaxed);
        if self.ready.swap(false, Ordering::AcqRel) || now >= self.deadline {
            self.completed
                .store(true, std::sync::atomic::Ordering::Release);
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }

    pub(crate) fn poll_ready_with_time(&self, now: Time) -> Poll<()> {
        assert!(
            !self.completed.load(std::sync::atomic::Ordering::Acquire),
            "Sleep polled after completion"
        );
        if self.ready.swap(false, Ordering::AcqRel) || now >= self.deadline {
            self.polled
                .store(true, std::sync::atomic::Ordering::Relaxed);
            self.completed
                .store(true, std::sync::atomic::Ordering::Release);
            self.complete_ready_registration(now, self.timer_driver_for_poll());
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}

impl Future for Sleep {
    type Output = ();

    #[allow(clippy::too_many_lines)]
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // Prefer an explicitly bound timer driver; otherwise use the ambient
        // runtime driver when one exists.
        let (ambient_timer_driver, trace) = Cx::current().map_or_else(
            || (None, None),
            |current| (current.timer_driver(), current.trace_buffer()),
        );
        let timer_driver = self
            .bound_timer_driver
            .clone()
            .or_else(|| ambient_timer_driver.clone())
            .or_else(|| {
                // No bound or ambient (Cx) driver. For the common wall-clock
                // case, route through the process-global shared fallback timer
                // instead of spawning an OS thread per Sleep
                // (br-asupersync-runtime-cpu-overhaul-5vt09v.3.5). A custom
                // logical clock (`time_getter`) keeps the short-poll thread
                // fallback below, since the wall-clock shared driver cannot
                // observe an injected clock.
                self.time_getter.is_none().then(|| {
                    // Defense-in-depth: surface the missing timer driver once so a
                    // mis-configured consumer is caught in logs instead of silently
                    // running on the fallback
                    // (br-asupersync-runtime-cpu-overhaul-5vt09v.3.5).
                    warn_missing_timer_driver_once();
                    global_fallback_timer().driver.clone()
                })
            });
        let now = if let Some(timer) = self.bound_timer_driver.as_ref() {
            timer.now()
        } else if self.time_getter.is_some() {
            self.current_time()
        } else {
            timer_driver
                .as_ref()
                .map_or_else(|| self.current_time(), TimerDriverHandle::now)
        };

        match self.poll_with_time(now) {
            Poll::Ready(()) => {
                // Cancel any registered timer on completion.
                self.complete_ready_registration(now, timer_driver.clone());
                Poll::Ready(())
            }
            Poll::Pending => {
                let mut state = self.state.lock();
                let finished_handles = take_finished_fallbacks(&mut state);
                let waker_changed = !state
                    .waker
                    .as_ref()
                    .is_some_and(|w| w.will_wake(cx.waker()));

                if waker_changed {
                    state.waker = Some(cx.waker().clone());
                }

                // Prefer timer driver over background thread
                if let Some(timer) = timer_driver.as_ref() {
                    // If a fallback thread exists, request it stop. We don't join here
                    // (poll must not block); Drop/reset will join.
                    if let Some(fallback) = state.fallback.take() {
                        request_stop_fallback(&fallback);
                        state.zombie_fallbacks.push(fallback.join);
                    }

                    // If we switched drivers, cancel the old timer handle first.
                    // Check if we need to cancel before taking any references.
                    let needs_cancel = state
                        .timer_driver
                        .as_ref()
                        .is_some_and(|prev| !timer.ptr_eq(prev));
                    if needs_cancel {
                        // Take both the old driver and handle to avoid borrow conflicts.
                        // The old handle is consumed by cancel(); a new one will be
                        // registered below.
                        let old_driver = state.timer_driver.take();
                        let old_handle = state.timer_handle.take();
                        if let (Some(prev_driver), Some(handle)) = (old_driver, old_handle) {
                            if let Some(trace) = trace.as_ref() {
                                trace.record_event(|seq| {
                                    TraceEvent::timer_cancelled(seq, prev_driver.now(), handle.id())
                                });
                            }
                            let _ = prev_driver.cancel(&handle);
                        }
                        // Note: timer_handle is now None; the code below will
                        // register a fresh handle on the new driver.
                    }

                    state.timer_driver = Some(timer.clone());

                    let mut armed = false;
                    if state.timer_handle.is_none() {
                        // Register new timer
                        let handle = timer.register(
                            self.deadline,
                            readiness_waker(Arc::clone(&self.ready), cx.waker().clone()),
                        );
                        if let Some(trace) = trace.as_ref() {
                            trace.record_event(|seq| {
                                TraceEvent::timer_scheduled(seq, now, handle.id(), self.deadline)
                            });
                        }
                        state.timer_handle = Some(handle);
                        armed = true;
                    } else if waker_changed {
                        // Update existing timer with new waker
                        if let Some(handle) = state.timer_handle.take() {
                            let old_id = handle.id();
                            let new_handle = timer.update(
                                &handle,
                                self.deadline,
                                readiness_waker(Arc::clone(&self.ready), cx.waker().clone()),
                            );
                            if let Some(trace) = trace.as_ref() {
                                trace.record_event(|seq| {
                                    TraceEvent::timer_cancelled(seq, now, old_id)
                                });
                                trace.record_event(|seq| {
                                    TraceEvent::timer_scheduled(
                                        seq,
                                        now,
                                        new_handle.id(),
                                        self.deadline,
                                    )
                                });
                            }
                            state.timer_handle = Some(new_handle);
                            armed = true;
                        }
                    }

                    // If this Sleep just (re)armed on the process-global shared
                    // fallback timer, wake its pump so it re-parks to the
                    // possibly-sooner next deadline. Arming a sooner timer MUST
                    // unpark the pump or the wakeup waits for the prior park.
                    if armed && is_global_fallback_driver(timer) {
                        global_fallback_timer().pump.unpark();
                    }
                } else {
                    // No timer driver; cancel any existing registration.
                    if let Some(prev_driver) = state.timer_driver.take() {
                        if let Some(old_handle) = state.timer_handle.take() {
                            if let Some(trace) = trace.as_ref() {
                                trace.record_event(|seq| {
                                    TraceEvent::timer_cancelled(
                                        seq,
                                        prev_driver.now(),
                                        old_handle.id(),
                                    )
                                });
                            }
                            let _ = prev_driver.cancel(&old_handle);
                        }
                    }

                    if state.fallback.is_none() {
                        // Fallback: spawn background thread for timing.
                        //
                        // IMPORTANT: We intentionally drop the JoinHandle (detaching the thread)
                        // rather than joining it, so we don't block the executor. OS threads
                        // naturally clean themselves up upon exit.
                        let deadline = self.deadline;
                        let getter = self.time_getter.unwrap_or(wall_now);
                        let polls_custom_time_getter = self.time_getter.is_some();
                        let state_clone = Arc::clone(&self.state);

                        let stop = Arc::new(AtomicBool::new(false));
                        let stop_for_thread = Arc::clone(&stop);
                        let completed = Arc::new(AtomicBool::new(false));
                        let completed_for_thread = Arc::clone(&completed);
                        let ready_for_thread = Arc::clone(&self.ready);
                        crate::runtime::metrics::record_timer_thread_spawned();
                        // ubs:ignore - intentional detach by dropping JoinHandle in Drop to avoid blocking executor
                        let handle = std::thread::spawn(move || {
                            // Allow prompt cancellation via `unpark()`.
                            while !stop_for_thread.load(Ordering::Acquire) {
                                let current = getter();
                                if current >= deadline {
                                    break;
                                }
                                let remaining =
                                    deadline.as_nanos().saturating_sub(current.as_nanos());
                                let mut park_dur = Duration::from_nanos(remaining);
                                if polls_custom_time_getter {
                                    // Custom logical clocks can jump forward without any
                                    // timer-driver wakeup. Poll them on short real-time slices
                                    // so the future becomes ready promptly after the injected
                                    // clock advances instead of sleeping until wall time catches up.
                                    park_dur = park_dur.min(CUSTOM_TIME_GETTER_POLL_INTERVAL);
                                }
                                std::thread::park_timeout(park_dur);
                            }

                            if stop_for_thread.load(Ordering::Acquire) {
                                return;
                            }

                            ready_for_thread.store(true, Ordering::Release);
                            let waker = state_clone.lock().waker.take();
                            if let Some(waker) = waker {
                                waker.wake();
                            }
                            completed_for_thread.store(true, Ordering::Release);
                        });
                        let thread = handle.thread().clone();
                        state.fallback = Some(FallbackThread {
                            stop,
                            completed,
                            thread,
                            join: handle,
                        });
                    }
                }

                drop(state);
                // Cleanly reap finished threads instead of detaching them.
                // Since they are verified finished, join() will not block.
                for handle in finished_handles {
                    let _ = handle.join();
                }

                Poll::Pending
            }
        }
    }
}

impl Drop for Sleep {
    fn drop(&mut self) {
        let (handle, driver, fallback_handles) = {
            let mut state = self.state.lock();
            // Clear waker to release task reference immediately, preventing
            // unbounded lifetime extension if background thread is running.
            state.waker = None;
            let mut handles = std::mem::take(&mut state.zombie_fallbacks);
            if let Some(fallback) = state.fallback.take() {
                request_stop_fallback(&fallback);
                handles.push(fallback.join);
            }
            (
                state.timer_handle.take(),
                state.timer_driver.take(),
                handles,
            )
        };

        // Intentionally detach threads to avoid blocking the executor
        drop(fallback_handles);

        if let (Some(handle), Some(driver)) = (handle, driver) {
            let trace = Cx::current().and_then(|current| current.trace_buffer());
            if let Some(trace) = trace.as_ref() {
                let now = driver.now();
                trace.record_event(|seq| TraceEvent::timer_cancelled(seq, now, handle.id()));
            }
            let _ = driver.cancel(&handle);
        }
    }
}

impl Clone for Sleep {
    fn clone(&self) -> Self {
        Self {
            deadline: self.deadline,
            time_getter: self.time_getter,
            bound_timer_driver: self.bound_timer_driver.clone(),
            polled: std::sync::atomic::AtomicBool::new(false), // Fresh clone hasn't been polled
            completed: std::sync::atomic::AtomicBool::new(false),
            ready: Arc::new(AtomicBool::new(false)),
            state: Arc::new(Mutex::new(SleepState {
                waker: None,
                fallback: None,
                zombie_fallbacks: Vec::new(),
                timer_handle: None, // Fresh clone has no timer registration
                timer_driver: None,
            })),
        }
    }
}

/// Creates a `Sleep` future that completes after the given duration.
///
/// This function requires a current time to compute the deadline.
/// For use without explicit time, see [`sleep_until`].
///
/// # Arguments
///
/// * `now` - The current time
/// * `duration` - How long to sleep
///
/// # Example
///
/// ```
/// use asupersync::time::sleep;
/// use asupersync::types::Time;
/// use std::time::Duration;
///
/// let now = Time::from_secs(10);
/// let sleep_future = sleep(now, Duration::from_millis(100));
/// assert_eq!(sleep_future.deadline(), Time::from_nanos(10_100_000_000));
/// ```
#[must_use]
#[inline]
pub fn sleep(now: Time, duration: Duration) -> Sleep {
    Sleep::after(now, duration)
}

/// Creates a `Sleep` future that completes at the given deadline.
///
/// # Arguments
///
/// * `deadline` - The absolute time when the sleep completes
///
/// # Example
///
/// ```
/// use asupersync::time::sleep_until;
/// use asupersync::types::Time;
///
/// let sleep_future = sleep_until(Time::from_secs(5));
/// assert_eq!(sleep_future.deadline(), Time::from_secs(5));
/// ```
#[must_use]
#[inline]
pub fn sleep_until(deadline: Time) -> Sleep {
    Sleep::new(deadline)
}

#[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::*;
    use crate::cx::Cx;
    use crate::test_utils::init_test_logging;
    use crate::time::{TimerDriverHandle, VirtualClock};
    use crate::types::{Budget, RegionId, TaskId};
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
    use std::task::{Context, Waker};

    // =========================================================================
    // Construction Tests
    // =========================================================================

    fn init_test(name: &str) {
        init_test_logging();
        crate::test_phase!(name);
    }

    static CURRENT_TIME: AtomicU64 = AtomicU64::new(0);

    #[test]
    fn wall_now_falls_back_when_current_cx_has_no_timer_driver() {
        init_test("wall_now_falls_back_when_current_cx_has_no_timer_driver");

        let cx = Cx::new(
            RegionId::new_for_test(0, 6),
            TaskId::new_for_test(0, 6),
            Budget::INFINITE,
        );
        let _guard = Cx::set_current(Some(cx));

        let first = wall_now();
        let second = wall_now();

        crate::assert_with_log!(
            second >= first,
            "wall clock remains monotonic",
            true,
            second >= first
        );
        crate::test_complete!("wall_now_falls_back_when_current_cx_has_no_timer_driver");
    }

    /// Regression: the production [`WallClock`](crate::time::driver::WallClock)
    /// timer driver and `wall_now()`'s capability-free fallback must measure
    /// elapsed time from the *same* process epoch.
    ///
    /// Before the fix each `WallClock::new()` captured its own
    /// `Instant::now()` epoch, distinct from `wall_now()`'s `START_TIME`
    /// fallback epoch. A request-budget deadline computed via `wall_now()` was
    /// then evaluated by the deadline monitor against `timer_driver.now()` on a
    /// *different* epoch; once process uptime exceeded the request timeout every
    /// such request was born already past its deadline and cancelled
    /// immediately — surfacing as spurious "pool acquire cancelled" DB failures
    /// under load.
    #[test]
    fn wall_clock_instances_share_process_epoch() {
        use crate::time::driver::{TimeSource, WallClock};
        init_test("wall_clock_instances_share_process_epoch");

        let first = WallClock::new();
        std::thread::sleep(Duration::from_millis(20));
        let second = WallClock::new();

        let a = first.now().as_nanos();
        let b = second.now().as_nanos();

        // Same shared epoch => readings taken back-to-back agree within a small
        // delta, NOT separated by the 20ms gap a per-instance epoch produces.
        let delta = a.abs_diff(b);
        crate::assert_with_log!(
            delta < 5_000_000,
            "WallClock instances share one process epoch (delta < 5ms)",
            true,
            delta < 5_000_000
        );
        // The later clock measures from the earlier shared epoch, so it observes
        // the 20ms that elapsed before it was even constructed.
        crate::assert_with_log!(
            b >= 15_000_000,
            "later WallClock observes pre-construction elapsed time",
            true,
            b >= 15_000_000
        );
        crate::test_complete!("wall_clock_instances_share_process_epoch");
    }

    fn get_time() -> Time {
        Time::from_nanos(CURRENT_TIME.load(Ordering::SeqCst))
    }

    #[test]
    fn new_creates_sleep_with_deadline() {
        init_test("new_creates_sleep_with_deadline");
        let sleep = Sleep::new(Time::from_secs(5));
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(5),
            "deadline",
            Time::from_secs(5),
            sleep.deadline()
        );
        crate::assert_with_log!(!sleep.was_polled(), "not polled", false, sleep.was_polled());
        crate::test_complete!("new_creates_sleep_with_deadline");
    }

    #[test]
    fn after_computes_deadline() {
        init_test("after_computes_deadline");
        let now = Time::from_secs(10);
        let sleep = Sleep::after(now, Duration::from_secs(5));
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(15),
            "deadline",
            Time::from_secs(15),
            sleep.deadline()
        );
        crate::test_complete!("after_computes_deadline");
    }

    #[test]
    fn after_saturates() {
        init_test("after_saturates");
        let now = Time::from_nanos(u64::MAX - 1000);
        let sleep = Sleep::after(now, Duration::from_secs(1));
        crate::assert_with_log!(
            sleep.deadline() == Time::MAX,
            "deadline",
            Time::MAX,
            sleep.deadline()
        );
        crate::test_complete!("after_saturates");
    }

    #[test]
    fn sleep_function() {
        init_test("sleep_function");
        let now = Time::from_millis(100);
        let s = sleep(now, Duration::from_millis(50));
        crate::assert_with_log!(
            s.deadline() == Time::from_millis(150),
            "deadline",
            Time::from_millis(150),
            s.deadline()
        );
        crate::test_complete!("sleep_function");
    }

    #[test]
    fn sleep_until_function() {
        init_test("sleep_until_function");
        let s = sleep_until(Time::from_secs(42));
        crate::assert_with_log!(
            s.deadline() == Time::from_secs(42),
            "deadline",
            Time::from_secs(42),
            s.deadline()
        );
        crate::test_complete!("sleep_until_function");
    }

    // =========================================================================
    // Time Getter Tests
    // =========================================================================

    #[test]
    fn with_time_getter() {
        init_test("with_time_getter");
        CURRENT_TIME.store(0, Ordering::SeqCst);

        let sleep = Sleep::with_time_getter(Time::from_secs(5), get_time);

        // Time is 0, should be pending
        let elapsed = sleep.is_elapsed(get_time());
        crate::assert_with_log!(!elapsed, "not elapsed", false, elapsed);

        // Advance time past deadline
        CURRENT_TIME.store(6_000_000_000, Ordering::SeqCst);
        let elapsed = sleep.is_elapsed(get_time());
        crate::assert_with_log!(elapsed, "elapsed", true, elapsed);
        crate::test_complete!("with_time_getter");
    }

    #[test]
    fn custom_time_getter_wakes_promptly_after_logical_time_advance() {
        init_test("custom_time_getter_wakes_promptly_after_logical_time_advance");
        CURRENT_TIME.store(0, Ordering::SeqCst);

        let woken = Arc::new(AtomicBool::new(false));
        let waker = waker_that_sets(Arc::clone(&woken));
        let mut task_cx = Context::from_waker(&waker);
        let mut sleep = Sleep::with_time_getter(Time::from_secs(10), get_time);

        let first = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            first.is_pending(),
            "first pending",
            true,
            first.is_pending()
        );

        CURRENT_TIME.store(Time::from_secs(10).as_nanos(), Ordering::SeqCst);

        let wait_deadline = Instant::now() + Duration::from_millis(500);
        while !woken.load(Ordering::SeqCst) && Instant::now() < wait_deadline {
            std::thread::sleep(Duration::from_millis(1));
        }

        let woke = woken.load(Ordering::SeqCst);
        crate::assert_with_log!(woke, "waker fired", true, woke);

        let second = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(second.is_ready(), "second ready", true, second.is_ready());
        crate::test_complete!("custom_time_getter_wakes_promptly_after_logical_time_advance");
    }

    // =========================================================================
    // is_elapsed and remaining Tests
    // =========================================================================

    #[test]
    fn is_elapsed_before_deadline() {
        init_test("is_elapsed_before_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let elapsed = sleep.is_elapsed(Time::from_secs(5));
        crate::assert_with_log!(!elapsed, "not elapsed", false, elapsed);
        crate::test_complete!("is_elapsed_before_deadline");
    }

    #[test]
    fn is_elapsed_at_deadline() {
        init_test("is_elapsed_at_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let elapsed = sleep.is_elapsed(Time::from_secs(10));
        crate::assert_with_log!(elapsed, "elapsed", true, elapsed);
        crate::test_complete!("is_elapsed_at_deadline");
    }

    #[test]
    fn is_elapsed_after_deadline() {
        init_test("is_elapsed_after_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let elapsed = sleep.is_elapsed(Time::from_secs(15));
        crate::assert_with_log!(elapsed, "elapsed", true, elapsed);
        crate::test_complete!("is_elapsed_after_deadline");
    }

    #[test]
    fn remaining_before_deadline() {
        init_test("remaining_before_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let remaining = sleep.remaining(Time::from_secs(7));
        crate::assert_with_log!(
            remaining == Duration::from_secs(3),
            "remaining",
            Duration::from_secs(3),
            remaining
        );
        crate::test_complete!("remaining_before_deadline");
    }

    #[test]
    fn remaining_at_deadline() {
        init_test("remaining_at_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let remaining = sleep.remaining(Time::from_secs(10));
        crate::assert_with_log!(
            remaining == Duration::ZERO,
            "remaining",
            Duration::ZERO,
            remaining
        );
        crate::test_complete!("remaining_at_deadline");
    }

    #[test]
    fn remaining_after_deadline() {
        init_test("remaining_after_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let remaining = sleep.remaining(Time::from_secs(15));
        crate::assert_with_log!(
            remaining == Duration::ZERO,
            "remaining",
            Duration::ZERO,
            remaining
        );
        crate::test_complete!("remaining_after_deadline");
    }

    // =========================================================================
    // poll_with_time Tests
    // =========================================================================

    #[test]
    fn poll_with_time_before_deadline() {
        init_test("poll_with_time_before_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let poll = sleep.poll_with_time(Time::from_secs(5));
        crate::assert_with_log!(poll.is_pending(), "pending", true, poll.is_pending());
        crate::assert_with_log!(sleep.was_polled(), "was polled", true, sleep.was_polled());
        crate::test_complete!("poll_with_time_before_deadline");
    }

    #[test]
    fn poll_with_time_at_deadline() {
        init_test("poll_with_time_at_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let poll = sleep.poll_with_time(Time::from_secs(10));
        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::test_complete!("poll_with_time_at_deadline");
    }

    #[test]
    fn poll_with_time_after_deadline() {
        init_test("poll_with_time_after_deadline");
        let sleep = Sleep::new(Time::from_secs(10));
        let poll = sleep.poll_with_time(Time::from_secs(15));
        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::test_complete!("poll_with_time_after_deadline");
    }

    #[test]
    fn poll_with_time_zero_deadline() {
        init_test("poll_with_time_zero_deadline");
        let sleep = Sleep::new(Time::ZERO);
        let poll = sleep.poll_with_time(Time::ZERO);
        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::test_complete!("poll_with_time_zero_deadline");
    }

    #[test]
    fn poll_ready_with_time_before_deadline_does_not_register() {
        init_test("poll_ready_with_time_before_deadline_does_not_register");
        let sleep = Sleep::new(Time::from_secs(10));

        let poll = sleep.poll_ready_with_time(Time::from_secs(5));

        crate::assert_with_log!(poll.is_pending(), "pending", true, poll.is_pending());
        crate::assert_with_log!(!sleep.was_polled(), "not polled", false, sleep.was_polled());
        let state = sleep.state.lock();
        crate::assert_with_log!(
            state.timer_handle.is_none(),
            "timer handle absent",
            true,
            state.timer_handle.is_none()
        );
        crate::assert_with_log!(
            state.fallback.is_none(),
            "fallback absent",
            true,
            state.fallback.is_none()
        );
        crate::test_complete!("poll_ready_with_time_before_deadline_does_not_register");
    }

    #[test]
    fn poll_ready_with_time_at_deadline_completes() {
        init_test("poll_ready_with_time_at_deadline_completes");
        let sleep = Sleep::new(Time::from_secs(10));

        let poll = sleep.poll_ready_with_time(Time::from_secs(10));

        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::assert_with_log!(sleep.was_polled(), "was polled", true, sleep.was_polled());
        crate::test_complete!("poll_ready_with_time_at_deadline_completes");
    }

    #[test]
    fn poll_with_time_repoll_after_completion_panics() {
        init_test("poll_with_time_repoll_after_completion_panics");
        let sleep = Sleep::new(Time::from_secs(10));

        let first = sleep.poll_with_time(Time::from_secs(10));
        crate::assert_with_log!(first.is_ready(), "first ready", true, first.is_ready());

        let repoll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = sleep.poll_with_time(Time::from_secs(10));
        }));
        crate::assert_with_log!(repoll.is_err(), "repoll panics", true, repoll.is_err());

        crate::test_complete!("poll_with_time_repoll_after_completion_panics");
    }

    // =========================================================================
    // Reset Tests
    // =========================================================================

    #[test]
    fn reset_changes_deadline() {
        init_test("reset_changes_deadline");
        let mut sleep = Sleep::new(Time::from_secs(10));

        // Poll it
        let _ = sleep.poll_with_time(Time::from_secs(5));
        crate::assert_with_log!(sleep.was_polled(), "was polled", true, sleep.was_polled());

        // Reset
        sleep.reset(Time::from_secs(20));
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(20),
            "deadline",
            Time::from_secs(20),
            sleep.deadline()
        );
        crate::assert_with_log!(
            !sleep.was_polled(),
            "reset clears polled",
            false,
            sleep.was_polled()
        ); // Reset clears polled flag
        crate::test_complete!("reset_changes_deadline");
    }

    #[test]
    fn reset_after_changes_deadline() {
        init_test("reset_after_changes_deadline");
        let mut sleep = Sleep::new(Time::from_secs(10));
        sleep.reset_after(Time::from_secs(5), Duration::from_secs(3));
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(8),
            "deadline",
            Time::from_secs(8),
            sleep.deadline()
        );
        crate::test_complete!("reset_after_changes_deadline");
    }

    #[test]
    fn reset_after_completion_allows_sleep_reuse() {
        init_test("reset_after_completion_allows_sleep_reuse");
        let mut sleep = Sleep::new(Time::from_secs(10));

        let first = sleep.poll_with_time(Time::from_secs(10));
        crate::assert_with_log!(first.is_ready(), "first ready", true, first.is_ready());

        sleep.reset(Time::from_secs(20));

        let second = sleep.poll_with_time(Time::from_secs(15));
        crate::assert_with_log!(
            second.is_pending(),
            "pending after reset before deadline",
            true,
            second.is_pending()
        );

        let third = sleep.poll_with_time(Time::from_secs(20));
        crate::assert_with_log!(
            third.is_ready(),
            "ready after reset",
            true,
            third.is_ready()
        );

        crate::test_complete!("reset_after_completion_allows_sleep_reuse");
    }

    // =========================================================================
    // Timer Driver Integration Tests
    // =========================================================================

    fn noop_waker() -> Waker {
        std::task::Waker::noop().clone()
    }

    fn waker_that_sets(flag: Arc<AtomicBool>) -> Waker {
        struct FlagWaker {
            flag: Arc<AtomicBool>,
        }

        impl Wake for FlagWaker {
            fn wake(self: Arc<Self>) {
                self.flag.store(true, Ordering::SeqCst);
            }

            fn wake_by_ref(self: &Arc<Self>) {
                self.flag.store(true, Ordering::SeqCst);
            }
        }

        Waker::from(Arc::new(FlagWaker { flag }))
    }

    #[test]
    fn drop_cancels_timer_registration() {
        init_test("drop_cancels_timer_registration");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock);
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 1),
            TaskId::new_for_test(0, 0),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let mut sleep = Sleep::after(timer.now(), Duration::from_secs(1));
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        let poll = Pin::new(&mut sleep).poll(&mut cx);
        crate::assert_with_log!(poll.is_pending(), "pending", true, poll.is_pending());
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "timer registered",
            1,
            timer.pending_count()
        );

        drop(sleep);

        crate::assert_with_log!(
            timer.pending_count() == 0,
            "timer cancelled on drop",
            0,
            timer.pending_count()
        );
        crate::test_complete!("drop_cancels_timer_registration");
    }

    #[test]
    fn reset_cancels_old_timer_and_re_registers_on_poll() {
        init_test("reset_cancels_old_timer_and_re_registers_on_poll");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 1),
            TaskId::new_for_test(0, 0),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let mut sleep = Sleep::after(timer.now(), Duration::from_secs(5));
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "first poll pending",
            true,
            first_poll.is_pending()
        );
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "first timer registration",
            1,
            timer.pending_count()
        );

        sleep.reset(Time::from_secs(10));
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "reset cancels previous timer",
            0,
            timer.pending_count()
        );
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(10),
            "deadline updated on reset",
            Time::from_secs(10),
            sleep.deadline()
        );

        let second_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            second_poll.is_pending(),
            "second poll pending after reset",
            true,
            second_poll.is_pending()
        );
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "timer re-registered after reset",
            1,
            timer.pending_count()
        );

        clock.set(Time::from_secs(9));
        let fired_before_deadline = timer.process_timers();
        crate::assert_with_log!(
            fired_before_deadline == 0,
            "no timers fire before new deadline",
            0,
            fired_before_deadline
        );

        clock.set(Time::from_secs(10));
        let _ = timer.process_timers();
        let ready_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            ready_poll.is_ready(),
            "sleep ready at reset deadline",
            true,
            ready_poll.is_ready()
        );
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "timer registration cleared on completion",
            0,
            timer.pending_count()
        );

        crate::test_complete!("reset_cancels_old_timer_and_re_registers_on_poll");
    }

    #[test]
    #[should_panic(expected = "Sleep polled after completion")]
    fn future_repoll_after_completion_panics() {
        init_test("future_repoll_after_completion_panics");

        let mut sleep = Sleep::new(Time::from_secs(0));
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(first.is_ready(), "first ready", true, first.is_ready());

        let _ = Pin::new(&mut sleep).poll(&mut task_cx);

        crate::test_complete!("future_repoll_after_completion_panics");
    }

    #[test]
    fn poll_with_new_timer_driver_migrates_registration() {
        init_test("poll_with_new_timer_driver_migrates_registration");

        let clock1 = Arc::new(VirtualClock::new());
        let timer1 = TimerDriverHandle::with_virtual_clock(clock1);
        let cx1 = Cx::new_with_drivers(
            RegionId::new_for_test(0, 1),
            TaskId::new_for_test(0, 1),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer1.clone()),
            None,
        );
        let _guard1 = Cx::set_current(Some(cx1));

        let mut sleep = Sleep::after(timer1.now(), Duration::from_secs(5));
        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        let first_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "first poll pending",
            true,
            first_poll.is_pending()
        );
        crate::assert_with_log!(
            timer1.pending_count() == 1,
            "timer1 has registration",
            1,
            timer1.pending_count()
        );

        let clock2 = Arc::new(VirtualClock::new());
        let timer2 = TimerDriverHandle::with_virtual_clock(clock2);
        let cx2 = Cx::new_with_drivers(
            RegionId::new_for_test(0, 2),
            TaskId::new_for_test(0, 2),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer2.clone()),
            None,
        );
        {
            let _guard2 = Cx::set_current(Some(cx2));

            let second_poll = Pin::new(&mut sleep).poll(&mut task_cx);
            crate::assert_with_log!(
                second_poll.is_pending(),
                "second poll pending on new driver",
                true,
                second_poll.is_pending()
            );
            crate::assert_with_log!(
                timer1.pending_count() == 0,
                "timer1 registration canceled after migration",
                0,
                timer1.pending_count()
            );
            crate::assert_with_log!(
                timer2.pending_count() == 1,
                "timer2 owns migrated registration",
                1,
                timer2.pending_count()
            );

            drop(sleep);
            crate::assert_with_log!(
                timer2.pending_count() == 0,
                "drop cancels migrated timer registration",
                0,
                timer2.pending_count()
            );
        }

        crate::test_complete!("poll_with_new_timer_driver_migrates_registration");
    }

    #[test]
    fn poll_after_timer_fire_stays_ready_across_driver_migration() {
        init_test("poll_after_timer_fire_stays_ready_across_driver_migration");

        let clock1 = Arc::new(VirtualClock::new());
        let timer1 = TimerDriverHandle::with_virtual_clock(clock1.clone());
        let cx1 = Cx::new_with_drivers(
            RegionId::new_for_test(0, 3),
            TaskId::new_for_test(0, 3),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer1.clone()),
            None,
        );
        let _guard1 = Cx::set_current(Some(cx1));

        let mut sleep = Sleep::after(timer1.now(), Duration::from_secs(5));
        let woke = Arc::new(AtomicBool::new(false));
        let waker = waker_that_sets(Arc::clone(&woke));
        let mut task_cx = Context::from_waker(&waker);

        let first_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "first poll pending",
            true,
            first_poll.is_pending()
        );

        clock1.set(Time::from_secs(6));
        let fired = timer1.process_timers();
        crate::assert_with_log!(fired == 1, "old driver fires timer once", 1usize, fired);
        crate::assert_with_log!(
            woke.load(Ordering::SeqCst),
            "timer wake reached task waker",
            true,
            woke.load(Ordering::SeqCst)
        );

        let clock2 = Arc::new(VirtualClock::new());
        let timer2 = TimerDriverHandle::with_virtual_clock(clock2);
        let cx2 = Cx::new_with_drivers(
            RegionId::new_for_test(0, 4),
            TaskId::new_for_test(0, 4),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer2.clone()),
            None,
        );
        let _guard2 = Cx::set_current(Some(cx2));

        let second_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            second_poll.is_ready(),
            "fired timer remains ready on new driver",
            true,
            second_poll.is_ready()
        );
        crate::assert_with_log!(
            timer2.pending_count() == 0,
            "new driver does not re-arm an already fired sleep",
            0,
            timer2.pending_count()
        );

        crate::test_complete!("poll_after_timer_fire_stays_ready_across_driver_migration");
    }

    #[test]
    fn poll_after_fallback_wake_stays_ready_on_driver() {
        init_test("poll_after_fallback_wake_stays_ready_on_driver");

        let _guard = Cx::set_current(None);

        let mut sleep = Sleep::after(wall_now(), Duration::from_millis(10));
        let woke = Arc::new(AtomicBool::new(false));
        let waker = waker_that_sets(Arc::clone(&woke));
        let mut task_cx = Context::from_waker(&waker);

        let first_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "first poll pending",
            true,
            first_poll.is_pending()
        );

        let start = Instant::now();
        while !woke.load(Ordering::SeqCst) && start.elapsed() < Duration::from_millis(250) {
            std::thread::sleep(Duration::from_millis(1));
        }
        crate::assert_with_log!(
            woke.load(Ordering::SeqCst),
            "fallback thread wakes task",
            true,
            woke.load(Ordering::SeqCst)
        );

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock);
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 5),
            TaskId::new_for_test(0, 5),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard2 = Cx::set_current(Some(cx));

        let second_poll = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            second_poll.is_ready(),
            "fallback wake remains ready after driver appears",
            true,
            second_poll.is_ready()
        );
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "driver does not re-arm an already fired fallback sleep",
            0,
            timer.pending_count()
        );

        crate::test_complete!("poll_after_fallback_wake_stays_ready_on_driver");
    }

    // =========================================================================
    // Clone Tests
    // =========================================================================

    #[test]
    fn clone_copies_deadline() {
        init_test("clone_copies_deadline");
        let original = Sleep::new(Time::from_secs(10));
        let cloned = original.clone();
        crate::assert_with_log!(
            original.deadline() == Time::from_secs(10),
            "original deadline",
            Time::from_secs(10),
            original.deadline()
        );
        crate::assert_with_log!(
            cloned.deadline() == Time::from_secs(10),
            "cloned deadline",
            Time::from_secs(10),
            cloned.deadline()
        );
        crate::test_complete!("clone_copies_deadline");
    }

    #[test]
    fn clone_has_fresh_polled_flag() {
        init_test("clone_has_fresh_polled_flag");
        let original = Sleep::new(Time::from_secs(10));
        let _ = original.poll_with_time(Time::from_secs(5));
        crate::assert_with_log!(
            original.was_polled(),
            "original polled",
            true,
            original.was_polled()
        );

        let cloned = original.clone();
        crate::assert_with_log!(
            original.was_polled(),
            "original still polled",
            true,
            original.was_polled()
        );
        crate::assert_with_log!(
            !cloned.was_polled(),
            "cloned not polled",
            false,
            cloned.was_polled()
        );
        crate::test_complete!("clone_has_fresh_polled_flag");
    }

    // =========================================================================
    // Edge Cases
    // =========================================================================

    #[test]
    fn zero_duration_sleep() {
        init_test("zero_duration_sleep");
        let now = Time::from_secs(10);
        let sleep = sleep(now, Duration::ZERO);
        crate::assert_with_log!(
            sleep.deadline() == Time::from_secs(10),
            "deadline",
            Time::from_secs(10),
            sleep.deadline()
        );

        // Should be immediately ready
        let poll = sleep.poll_with_time(now);
        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::test_complete!("zero_duration_sleep");
    }

    #[test]
    fn max_time_deadline() {
        init_test("max_time_deadline");
        let sleep = Sleep::new(Time::MAX);
        let poll = sleep.poll_with_time(Time::from_secs(1000));
        crate::assert_with_log!(poll.is_pending(), "pending", true, poll.is_pending());

        // Only ready at MAX
        let poll = sleep.poll_with_time(Time::MAX);
        crate::assert_with_log!(poll.is_ready(), "ready at max", true, poll.is_ready());
        crate::test_complete!("max_time_deadline");
    }

    #[test]
    fn time_zero_deadline() {
        init_test("time_zero_deadline");
        let sleep = Sleep::new(Time::ZERO);

        // Any non-zero time is past deadline
        let poll = sleep.poll_with_time(Time::from_nanos(1));
        crate::assert_with_log!(poll.is_ready(), "ready", true, poll.is_ready());
        crate::test_complete!("time_zero_deadline");
    }

    // =========================================================================
    // Metamorphic Testing: Sleep Cancel Relations
    // =========================================================================

    /// MR1: Cancellation idempotency - reset(reset(sleep)) ≡ reset(sleep)
    /// Tests that multiple resets to the same deadline are equivalent to a single reset.
    #[test]
    fn mr_cancel_idempotency() {
        init_test("mr_cancel_idempotency");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 100),
            TaskId::new_for_test(0, 100),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let initial_deadline = Time::from_secs(10);
        let reset_deadline = Time::from_secs(20);

        // Create two identical sleeps
        let mut sleep1 = Sleep::new(initial_deadline);
        let mut sleep2 = Sleep::new(initial_deadline);

        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        // Poll both to register timers
        let _ = Pin::new(&mut sleep1).poll(&mut task_cx);
        let _ = Pin::new(&mut sleep2).poll(&mut task_cx);

        // Reset once vs reset twice to same deadline
        sleep1.reset(reset_deadline); // Single reset
        sleep2.reset(reset_deadline); // Double reset (first)
        sleep2.reset(reset_deadline); // Double reset (second)

        // Both should behave identically
        crate::assert_with_log!(
            sleep1.deadline() == sleep2.deadline(),
            "deadlines equal after reset idempotency",
            sleep1.deadline(),
            sleep2.deadline()
        );
        crate::assert_with_log!(
            sleep1.was_polled() == sleep2.was_polled(),
            "polled state equal after reset idempotency",
            sleep1.was_polled(),
            sleep2.was_polled()
        );

        // Both should poll identically
        let poll1 = Pin::new(&mut sleep1).poll(&mut task_cx);
        let poll2 = Pin::new(&mut sleep2).poll(&mut task_cx);
        crate::assert_with_log!(
            poll1.is_pending() && poll2.is_pending(),
            "both pending after reset idempotency",
            true,
            poll1.is_pending() && poll2.is_pending()
        );

        // Fire both and check they complete identically
        clock.set(reset_deadline);
        let _ = timer.process_timers();
        let final1 = Pin::new(&mut sleep1).poll(&mut task_cx);
        let final2 = Pin::new(&mut sleep2).poll(&mut task_cx);
        crate::assert_with_log!(
            final1.is_ready() && final2.is_ready(),
            "both ready after timer fires",
            true,
            final1.is_ready() && final2.is_ready()
        );

        crate::test_complete!("mr_cancel_idempotency");
    }

    /// MR2: Cancel after fire is no-op
    /// Tests that operations on a completed Sleep have no effect.
    #[test]
    fn mr_cancel_after_fire_noop() {
        init_test("mr_cancel_after_fire_noop");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 101),
            TaskId::new_for_test(0, 101),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let deadline = Time::from_secs(5);
        let mut sleep = Sleep::new(deadline);

        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        // Poll to register timer
        let initial = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            initial.is_pending(),
            "initial poll pending",
            true,
            initial.is_pending()
        );

        // Fire the timer
        clock.set(deadline);
        let _ = timer.process_timers();
        let fired = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            fired.is_ready(),
            "sleep ready after timer fires",
            true,
            fired.is_ready()
        );

        // After completion, timer should be deregistered
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "no timers pending after completion",
            0,
            timer.pending_count()
        );

        // Now test that reset after completion works (creates fresh timer)
        let new_deadline = Time::from_secs(10);
        sleep.reset(new_deadline);
        crate::assert_with_log!(
            sleep.deadline() == new_deadline,
            "deadline updated after reset",
            new_deadline,
            sleep.deadline()
        );
        crate::assert_with_log!(
            !sleep.was_polled(),
            "polled flag cleared after reset",
            false,
            sleep.was_polled()
        );

        // Should be able to use normally after reset
        let after_reset = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            after_reset.is_pending(),
            "pending after reset on completed sleep",
            true,
            after_reset.is_pending()
        );

        crate::test_complete!("mr_cancel_after_fire_noop");
    }

    /// MR3: Reset-after-cancel yields fresh timer
    /// Tests that reset() creates a completely independent timer registration.
    #[test]
    fn mr_reset_after_cancel_fresh() {
        init_test("mr_reset_after_cancel_fresh");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 102),
            TaskId::new_for_test(0, 102),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let original_deadline = Time::from_secs(5);
        let reset_deadline = Time::from_secs(15);
        let mut sleep = Sleep::new(original_deadline);

        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        // Register original timer
        let _ = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "original timer registered",
            1,
            timer.pending_count()
        );

        // Reset cancels old timer and prepares for new one
        sleep.reset(reset_deadline);
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "reset cancels original timer",
            0,
            timer.pending_count()
        );
        crate::assert_with_log!(
            sleep.deadline() == reset_deadline,
            "deadline updated by reset",
            reset_deadline,
            sleep.deadline()
        );

        // Poll registers new timer
        let after_reset = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            after_reset.is_pending(),
            "pending after reset",
            true,
            after_reset.is_pending()
        );
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "new timer registered after reset",
            1,
            timer.pending_count()
        );

        // Original deadline should not fire the reset timer
        clock.set(original_deadline);
        let original_fires = timer.process_timers();
        crate::assert_with_log!(
            original_fires == 0,
            "original deadline does not fire reset timer",
            0,
            original_fires
        );
        let still_pending = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            still_pending.is_pending(),
            "sleep still pending at original deadline",
            true,
            still_pending.is_pending()
        );

        // Reset deadline should fire
        clock.set(reset_deadline);
        let reset_fires = timer.process_timers();
        crate::assert_with_log!(
            reset_fires == 1,
            "reset deadline fires timer",
            1,
            reset_fires
        );
        let ready = Pin::new(&mut sleep).poll(&mut task_cx);
        crate::assert_with_log!(
            ready.is_ready(),
            "sleep ready at reset deadline",
            true,
            ready.is_ready()
        );

        crate::test_complete!("mr_reset_after_cancel_fresh");
    }

    /// MR4: N sleeps with same deadline fire in deterministic order under LabRuntime
    /// Tests that timer firing order is consistent across multiple identical sleeps.
    #[test]
    fn mr_deterministic_order_same_deadline() {
        init_test("mr_deterministic_order_same_deadline");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 103),
            TaskId::new_for_test(0, 103),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let shared_deadline = Time::from_secs(10);
        let mut sleeps = Vec::new();
        let mut woke_flags = Vec::new();

        // Create multiple sleeps with same deadline and register them
        for i in 0..5 {
            let mut sleep = Sleep::new(shared_deadline);
            let woke = Arc::new(AtomicBool::new(false));
            let waker = waker_that_sets(Arc::clone(&woke));
            let mut task_cx = Context::from_waker(&waker);

            // Register each timer in order
            let poll = Pin::new(&mut sleep).poll(&mut task_cx);
            crate::assert_with_log!(
                poll.is_pending(),
                &format!("sleep {} pending", i),
                true,
                poll.is_pending()
            );

            sleeps.push(sleep);
            woke_flags.push(woke);
        }

        crate::assert_with_log!(
            timer.pending_count() == 5,
            "all timers registered",
            5,
            timer.pending_count()
        );

        // Fire all timers at deadline
        clock.set(shared_deadline);
        let fired_count = timer.process_timers();
        crate::assert_with_log!(
            fired_count == 5,
            "all timers fire at deadline",
            5,
            fired_count
        );

        // All wakers should fire
        for (i, woke) in woke_flags.iter().enumerate() {
            crate::assert_with_log!(
                woke.load(Ordering::SeqCst),
                &format!("waker {} fired", i),
                true,
                woke.load(Ordering::SeqCst)
            );
        }

        // All sleeps should be ready when polled with fresh context
        for (i, sleep) in sleeps.iter_mut().enumerate() {
            let waker = noop_waker();
            let mut task_cx = Context::from_waker(&waker);
            let ready = Pin::new(sleep).poll(&mut task_cx);
            crate::assert_with_log!(
                ready.is_ready(),
                &format!("sleep {} ready after timer fire", i),
                true,
                ready.is_ready()
            );
        }

        crate::assert_with_log!(
            timer.pending_count() == 0,
            "no pending timers after completion",
            0,
            timer.pending_count()
        );

        crate::test_complete!("mr_deterministic_order_same_deadline");
    }

    /// MR5: Drop cancellation removes from wheel atomically
    /// Tests that dropping a Sleep cleanly removes its timer registration.
    #[test]
    fn mr_drop_removes_atomically() {
        init_test("mr_drop_removes_atomically");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 104),
            TaskId::new_for_test(0, 104),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        crate::assert_with_log!(
            timer.pending_count() == 0,
            "timer starts empty",
            0,
            timer.pending_count()
        );

        // Scope to control when Sleep is dropped
        {
            let mut sleep = Sleep::new(Time::from_secs(10));
            let waker = noop_waker();
            let mut task_cx = Context::from_waker(&waker);

            // Register timer
            let poll = Pin::new(&mut sleep).poll(&mut task_cx);
            crate::assert_with_log!(
                poll.is_pending(),
                "sleep pending after registration",
                true,
                poll.is_pending()
            );
            crate::assert_with_log!(
                timer.pending_count() == 1,
                "timer registered",
                1,
                timer.pending_count()
            );

            // Test timer is functional
            clock.set(Time::from_secs(5));
            let midway_fires = timer.process_timers();
            crate::assert_with_log!(
                midway_fires == 0,
                "timer does not fire before deadline",
                0,
                midway_fires
            );

            // Sleep will be dropped here, should cancel timer
        }

        // Verify timer was cancelled on drop
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "timer cancelled on drop",
            0,
            timer.pending_count()
        );

        // Verify timer wheel is clean - no spurious fires
        clock.set(Time::from_secs(10));
        let dropped_fires = timer.process_timers();
        crate::assert_with_log!(
            dropped_fires == 0,
            "no spurious fires after drop",
            0,
            dropped_fires
        );

        clock.set(Time::from_secs(15));
        let later_fires = timer.process_timers();
        crate::assert_with_log!(
            later_fires == 0,
            "timer wheel remains clean",
            0,
            later_fires
        );

        crate::test_complete!("mr_drop_removes_atomically");
    }

    /// Composite MR: Cancellation composition properties
    /// Tests that combinations of operations preserve metamorphic relations.
    #[test]
    fn mr_cancellation_composition() {
        init_test("mr_cancellation_composition");

        let clock = Arc::new(VirtualClock::new());
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = Cx::new_with_drivers(
            RegionId::new_for_test(0, 105),
            TaskId::new_for_test(0, 105),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer.clone()),
            None,
        );
        let _guard = Cx::set_current(Some(cx));

        let waker = noop_waker();
        let mut task_cx = Context::from_waker(&waker);

        // Test: clone + reset preserves independence
        let original = Sleep::new(Time::from_secs(5));
        let mut cloned = original.clone();

        let _ = Pin::new(&mut cloned).poll(&mut task_cx);
        crate::assert_with_log!(
            timer.pending_count() == 1,
            "cloned sleep registers independently",
            1,
            timer.pending_count()
        );

        cloned.reset(Time::from_secs(10));
        crate::assert_with_log!(
            original.deadline() == Time::from_secs(5),
            "original unaffected by clone reset",
            Time::from_secs(5),
            original.deadline()
        );
        crate::assert_with_log!(
            cloned.deadline() == Time::from_secs(10),
            "cloned deadline updated",
            Time::from_secs(10),
            cloned.deadline()
        );

        // Test: multiple resets + drop is equivalent to single drop
        let mut sleep1 = Sleep::new(Time::from_secs(1));
        let mut sleep2 = Sleep::new(Time::from_secs(1));

        let _ = Pin::new(&mut sleep1).poll(&mut task_cx);
        let _ = Pin::new(&mut sleep2).poll(&mut task_cx);
        crate::assert_with_log!(
            timer.pending_count() == 2,
            "reset clone was cancelled; direct sleeps registered",
            2,
            timer.pending_count()
        );

        // sleep1: reset multiple times then drop
        sleep1.reset(Time::from_secs(2));
        sleep1.reset(Time::from_secs(3));
        sleep1.reset(Time::from_secs(4));
        drop(sleep1);

        // sleep2: drop directly
        drop(sleep2);

        // Both should result in same timer state (only cloned sleep remains)
        crate::assert_with_log!(
            timer.pending_count() == 0,
            "multiple resets + drop ≡ direct drop",
            0,
            timer.pending_count()
        );

        crate::test_complete!("mr_cancellation_composition");
    }

    #[test]
    fn off_cx_wall_clock_sleep_completes_via_shared_fallback() {
        init_test("off_cx_wall_clock_sleep_completes_via_shared_fallback");
        // No Cx is set on this thread, so Cx::current() is None: a wall-clock
        // sleep must route through the process-global shared fallback timer
        // (not a per-Sleep OS thread) and still fire
        // (br-asupersync-runtime-cpu-overhaul-5vt09v.3.5).
        crate::assert_with_log!(
            Cx::current().is_none(),
            "no ambient Cx",
            true,
            Cx::current().is_none()
        );
        let mut s = sleep(wall_now(), Duration::from_millis(20));
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        let give_up = Instant::now() + Duration::from_secs(2);
        loop {
            if Pin::new(&mut s).poll(&mut cx).is_ready() {
                break;
            }
            crate::assert_with_log!(
                Instant::now() < give_up,
                "off-Cx sleep fired within 2s",
                true,
                Instant::now() < give_up
            );
            std::thread::sleep(Duration::from_millis(1));
        }
        crate::test_complete!("off_cx_wall_clock_sleep_completes_via_shared_fallback");
    }

    #[cfg(feature = "runtime-metrics")]
    #[test]
    fn off_cx_sleeps_share_one_fallback_thread() {
        init_test("off_cx_sleeps_share_one_fallback_thread");
        // N off-Cx wall-clock sleeps must register with the single shared
        // fallback driver, NOT spawn one OS thread each (the churn this fix
        // targets). Counters are process-global and the suite runs in parallel,
        // so assert robust bounds: registrations grow by >= N (they used the
        // driver), and thread spawns grow by < N (not one-per-sleep).
        let n: u64 = 8;
        let before = crate::runtime::metrics::snapshot();
        for _ in 0..n {
            let mut s = sleep(wall_now(), Duration::from_millis(5));
            let waker = noop_waker();
            let mut cx = Context::from_waker(&waker);
            let give_up = Instant::now() + Duration::from_secs(2);
            loop {
                if Pin::new(&mut s).poll(&mut cx).is_ready() {
                    break;
                }
                assert!(Instant::now() < give_up, "off-Cx sleep stalled");
                std::thread::sleep(Duration::from_millis(1));
            }
        }
        let after = crate::runtime::metrics::snapshot();
        let registered = after.timers_registered - before.timers_registered;
        let spawned = after.timer_threads_spawned - before.timer_threads_spawned;
        crate::assert_with_log!(
            registered >= n,
            "off-Cx sleeps registered with shared driver",
            true,
            registered >= n
        );
        crate::assert_with_log!(
            spawned < n,
            "shared pump, not one thread per sleep",
            true,
            spawned < n
        );
        crate::test_complete!("off_cx_sleeps_share_one_fallback_thread");
    }

    #[test]
    fn sleep_with_driver_registers_without_spawning_thread() {
        init_test("sleep_with_driver_registers_without_spawning_thread");
        // Positive counterpart to the off-Cx fallback tests: a Sleep polled WITH
        // a bound timer driver must register on that driver's wheel and create
        // NO per-Sleep fallback OS thread. This is the premise of the whole fix
        // — when a driver IS installed (the normal RuntimeBuilder / enable_time
        // path) there is no per-Sleep churn
        // (br-asupersync-runtime-cpu-overhaul-5vt09v.3.6).
        //
        // Both assertions are driver-local / per-Sleep (NOT the process-global
        // timer_threads_spawned counter), so they stay deterministic under the
        // parallel test runner — a concurrent test cannot perturb this driver's
        // pending count or this Sleep's fallback slot.
        let driver = TimerDriverHandle::with_wall_clock();
        let deadline = Time::from_nanos(
            driver.now().as_nanos() + duration_to_nanos(Duration::from_millis(100)),
        );
        let mut s = Sleep::with_timer_driver(deadline, driver.clone());
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        // First poll registers on the driver's wheel and returns Pending.
        let first = Pin::new(&mut s).poll(&mut cx);
        crate::assert_with_log!(
            first.is_pending(),
            "driver-backed sleep pending on first poll",
            true,
            first.is_pending()
        );
        crate::assert_with_log!(
            driver.pending_count() == 1,
            "driver-backed sleep registered exactly one timer on the wheel",
            1usize,
            driver.pending_count()
        );
        // The whole point: a driver-backed sleep takes the timer-driver poll
        // branch and never reaches the no-driver `std::thread::spawn` path, so
        // its per-Sleep fallback slot stays empty.
        let no_fallback = s.state.lock().fallback.is_none();
        crate::assert_with_log!(
            no_fallback,
            "driver-backed sleep created no per-Sleep fallback thread",
            true,
            no_fallback
        );
        // Drive it to completion through the (passive) wall-clock driver so the
        // registration is cleaned up and we prove it still fires.
        let give_up = Instant::now() + Duration::from_secs(2);
        loop {
            let _ = driver.process_timers();
            if Pin::new(&mut s).poll(&mut cx).is_ready() {
                break;
            }
            assert!(Instant::now() < give_up, "driver-backed sleep stalled");
            std::thread::sleep(Duration::from_millis(1));
        }
        crate::test_complete!("sleep_with_driver_registers_without_spawning_thread");
    }

    #[test]
    fn missing_timer_driver_warns_exactly_once() {
        init_test("missing_timer_driver_warns_exactly_once");
        // The fallback warn must fire on the FIRST take and never again
        // (br-asupersync-runtime-cpu-overhaul-5vt09v.3.5). Test the once-claim
        // primitive against a LOCAL flag so the assertion is deterministic and
        // independent of process-global state / parallel test ordering (the real
        // call site uses the module-global FALLBACK_TIMER_WARNED, which other
        // off-Cx tests may have already flipped).
        let flag = AtomicBool::new(false);
        let first = claim_first_call(&flag);
        crate::assert_with_log!(first, "first call claims the warn", true, first);
        // Every subsequent call must observe the flag already set.
        for _ in 0..5 {
            let again = claim_first_call(&flag);
            crate::assert_with_log!(!again, "subsequent calls do not re-warn", false, again);
        }
        // Calling the real warn helper must not panic regardless of whether the
        // process-global flag was already consumed by another test.
        warn_missing_timer_driver_once();
        warn_missing_timer_driver_once();
        crate::test_complete!("missing_timer_driver_warns_exactly_once");
    }
}