nexus-timer 1.5.0

High-performance timer wheel with O(1) insert and cancel
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
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
//! Timer wheel — the main data structure.
//!
//! `TimerWheel<T, S>` is a multi-level, rebalancing timer wheel. Entries are
//! placed into a level based on how far in the future their deadline is, and
//! **rebalanced** down to finer levels as their deadline approaches; `poll`
//! then collects ready timers from the small, exact fine-level slots. Timers
//! fire at their exact tick, never early, never missed.

use std::cell::Cell;
use std::marker::PhantomData;
use std::mem;
use std::time::{Duration, Instant};

use nexus_slab::{Full, Slot, bounded, unbounded};

use crate::entry::{EntryPtr, WheelEntry, entry_ref};
use crate::handle::TimerHandle;
use crate::level::Level;
use crate::store::{BoundedStore, SlabStore};

/// Error returned by a builder's `build` when the configuration is invalid.
///
/// A wheel / queue is configured at construction from your own constants, so an
/// invalid config is a programmer error — but it is *returned* rather than
/// panicked, both for consistency with the rest of the workspace and so a caller
/// that sources configuration from runtime input can handle it. The message
/// names the constraint that was violated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    /// A configuration value is out of range; the message names the constraint.
    Invalid(&'static str),
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Invalid(msg) => write!(f, "timer configuration error: {msg}"),
        }
    }
}

impl std::error::Error for ConfigError {}

// =============================================================================
// WheelBuilder (typestate)
// =============================================================================

/// Builder for configuring a timer wheel.
///
/// Defaults match the Linux kernel timer wheel (1ms tick, 64 slots/level,
/// 8x multiplier, 7 levels → ~4.7 hour range).
///
/// # Examples
///
/// ```
/// use std::time::{Duration, Instant};
/// use nexus_timer::{Wheel, WheelBuilder};
///
/// let now = Instant::now();
///
/// // All defaults
/// let wheel: Wheel<u64> = WheelBuilder::default().unbounded(4096).build(now).unwrap();
///
/// // Custom config
/// let wheel: Wheel<u64> = WheelBuilder::default()
///     .tick_duration(Duration::from_micros(100))
///     .slots_per_level(32)
///     .unbounded(4096)
///     .build(now)
///     .unwrap();
/// ```
#[derive(Debug, Clone, Copy)]
pub struct WheelBuilder {
    tick_duration: Duration,
    slots_per_level: usize,
    clk_shift: u32,
    num_levels: usize,
    max_rebalances_per_poll: usize,
}

impl Default for WheelBuilder {
    fn default() -> Self {
        WheelBuilder {
            tick_duration: Duration::from_millis(1),
            slots_per_level: 64,
            clk_shift: 3,
            num_levels: 7,
            max_rebalances_per_poll: usize::MAX,
        }
    }
}

impl WheelBuilder {
    /// Creates a new builder with default configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the tick duration. Default: 1ms.
    pub fn tick_duration(mut self, d: Duration) -> Self {
        self.tick_duration = d;
        self
    }

    /// Sets the number of slots per level. Must be a power of 2, at most 64, and
    /// greater than `2^clk_shift` so a rebalance always moves an entry to a
    /// strictly finer level (`clk_shift` and `slots_per_level` are validated
    /// together at [`build`](UnboundedWheelBuilder::build)). Default: 64.
    pub fn slots_per_level(mut self, n: usize) -> Self {
        self.slots_per_level = n;
        self
    }

    /// Sets the bit shift between levels (multiplier = 2^clk_shift). Must satisfy
    /// `2^clk_shift < slots_per_level` so a rebalance always moves an entry to a
    /// strictly finer level (validated at build); with the default 64 slots that
    /// allows `clk_shift` up to 5. Default: 3 (8x).
    pub fn clk_shift(mut self, s: u32) -> Self {
        self.clk_shift = s;
        self
    }

    /// Sets the number of levels. Default: 7.
    pub fn num_levels(mut self, n: usize) -> Self {
        self.num_levels = n;
        self
    }

    /// Sets the maximum number of entries **rebalanced** (moved to a finer
    /// level) per [`poll_and_rebalance`](TimerWheel::poll_and_rebalance).
    /// Default: `usize::MAX` (unbounded).
    ///
    /// Rebalancing is maintenance: as time advances, a timer scheduled far in
    /// the future is placed in a coarse level, and when its slot comes due it is
    /// moved down to a finer level so it is not re-scanned on every future poll.
    /// Unbounded (the default), one poll rebalances a whole slot at once — least
    /// total work, but a rare poll can spike. A cap spreads that work across
    /// several polls: each poll rebalances at most `n` entries and leaves the
    /// rest in place, trading the rare spike for slightly more total work (the
    /// leftover entries are walked again on a later poll).
    ///
    /// **This bounds only rebalancing, never firing.** Every due timer is still
    /// collected at its exact deadline regardless of the cap, because a
    /// not-yet-due entry left un-rebalanced simply fires from whatever level it
    /// is sitting in when its time comes. The cap can therefore never make a
    /// timer fire late or be missed; it is purely a latency-smoothing knob for
    /// the poll hot path.
    ///
    /// **Recommended to tune** for latency-sensitive loops: pick `n` large
    /// enough to keep up with the steady rebalance rate (roughly
    /// `population * num_levels / average_timeout_in_ticks`) so entries do not
    /// backlog, yet small enough that no single poll stalls.
    pub fn max_rebalances_per_poll(mut self, n: usize) -> Self {
        self.max_rebalances_per_poll = n;
        self
    }

    /// Transitions to an unbounded wheel builder.
    ///
    /// `chunk_capacity` is the slab chunk size (entries per chunk). The slab
    /// grows by adding new chunks as needed.
    pub fn unbounded(self, chunk_capacity: usize) -> UnboundedWheelBuilder {
        UnboundedWheelBuilder {
            config: self,
            chunk_capacity,
        }
    }

    /// Transitions to a bounded wheel builder.
    ///
    /// `capacity` is the maximum number of concurrent timers.
    pub fn bounded(self, capacity: usize) -> BoundedWheelBuilder {
        BoundedWheelBuilder {
            config: self,
            capacity,
        }
    }

    fn validate(&self) -> Result<(), ConfigError> {
        if !self.slots_per_level.is_power_of_two() {
            return Err(ConfigError::Invalid("slots_per_level must be a power of 2"));
        }
        if self.slots_per_level > 64 {
            return Err(ConfigError::Invalid(
                "slots_per_level must be <= 64 (u64 bitmask)",
            ));
        }
        if self.num_levels == 0 {
            return Err(ConfigError::Invalid("num_levels must be > 0"));
        }
        if self.num_levels > 8 {
            return Err(ConfigError::Invalid("num_levels must be <= 8 (u8 bitmask)"));
        }
        if self.clk_shift == 0 {
            return Err(ConfigError::Invalid("clk_shift must be > 0"));
        }
        if self.tick_duration.is_zero() {
            return Err(ConfigError::Invalid("tick_duration must be non-zero"));
        }
        // tick_ns() narrows as_nanos() (u128) to u64; a duration whose nanos
        // exceed u64::MAX would truncate — and a nonzero multiple of 2^64 would
        // truncate to 0, making inv_tick_ns a divide-by-zero. Reject up front so
        // build() stays panic-free.
        if self.tick_duration.as_nanos() > u64::MAX as u128 {
            return Err(ConfigError::Invalid(
                "tick_duration must fit in u64 nanoseconds",
            ));
        }
        let max_shift = (self.num_levels - 1) as u64 * self.clk_shift as u64;
        if max_shift >= 64 {
            return Err(ConfigError::Invalid(
                "(num_levels - 1) * clk_shift must be < 64",
            ));
        }
        let slots_log2 = self.slots_per_level.trailing_zeros() as u64;
        if slots_log2 + max_shift >= 64 {
            return Err(ConfigError::Invalid(
                "slots_per_level << max_shift would overflow u64",
            ));
        }
        // Rebalance progress guard. When a due slot is polled, a not-yet-due
        // entry is relocated to a strictly finer level (see `TimerWheel::poll_level`);
        // that requires 2^clk_shift < slots_per_level (both powers of two, so
        // `clk_shift < slots_log2`, avoiding a shift that could overflow for
        // absurd clk_shift). Checked last so a config that also overflows reports
        // the overflow first.
        if (self.clk_shift as u64) >= slots_log2 {
            return Err(ConfigError::Invalid(
                "2^clk_shift must be < slots_per_level so rebalancing relocates to a strictly finer level",
            ));
        }
        Ok(())
    }

    fn tick_ns(&self) -> u64 {
        self.tick_duration.as_nanos() as u64
    }
}

/// Terminal builder for an unbounded timer wheel.
///
/// Created via [`WheelBuilder::unbounded`]. The only method is `.build()`.
#[derive(Debug)]
pub struct UnboundedWheelBuilder {
    config: WheelBuilder,
    chunk_capacity: usize,
}

impl UnboundedWheelBuilder {
    /// Builds the unbounded timer wheel, validating the configuration.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the configuration is invalid (e.g.
    /// non-power-of-2 `slots_per_level`, out-of-range `num_levels` / `clk_shift`,
    /// zero tick duration, or `2^clk_shift >= slots_per_level`).
    pub fn build<T: 'static>(self, now: Instant) -> Result<Wheel<T>, ConfigError> {
        self.config.validate()?;
        // SAFETY: Timer wheel is single-threaded (!Send, !Sync). All slots
        // are freed via Slot::from_raw() + slab.free() before the wheel drops.
        // The slab is never shared across threads.
        let slab = unsafe { unbounded::Slab::with_chunk_capacity(self.chunk_capacity) };
        let levels = build_levels::<T>(&self.config);
        let tick_ns = self.config.tick_ns();
        Ok(TimerWheel {
            slab,
            num_levels: self.config.num_levels,
            levels,
            current_ticks: 0,
            tick_ns,
            inv_tick_ns: (1u128 << 64) / tick_ns as u128,
            epoch: now,
            active_levels: 0,
            len: 0,
            min_deadline: Cell::new(None),
            max_rebalances_per_poll: self.config.max_rebalances_per_poll,
            _marker: PhantomData,
        })
    }
}

/// Terminal builder for a bounded timer wheel.
///
/// Created via [`WheelBuilder::bounded`]. The only method is `.build()`.
#[derive(Debug)]
pub struct BoundedWheelBuilder {
    config: WheelBuilder,
    capacity: usize,
}

impl BoundedWheelBuilder {
    /// Builds the bounded timer wheel, validating the configuration.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the configuration is invalid (e.g.
    /// non-power-of-2 `slots_per_level`, out-of-range `num_levels` / `clk_shift`,
    /// zero tick duration, or `2^clk_shift >= slots_per_level`).
    pub fn build<T: 'static>(self, now: Instant) -> Result<BoundedWheel<T>, ConfigError> {
        self.config.validate()?;
        // SAFETY: Timer wheel is single-threaded (!Send, !Sync). All slots
        // are freed via Slot::from_raw() + slab.free() before the wheel drops.
        // The slab is never shared across threads.
        let slab = unsafe { bounded::Slab::with_capacity(self.capacity) };
        let levels = build_levels::<T>(&self.config);
        let tick_ns = self.config.tick_ns();
        Ok(TimerWheel {
            slab,
            num_levels: self.config.num_levels,
            levels,
            current_ticks: 0,
            tick_ns,
            inv_tick_ns: (1u128 << 64) / tick_ns as u128,
            epoch: now,
            active_levels: 0,
            len: 0,
            min_deadline: Cell::new(None),
            max_rebalances_per_poll: self.config.max_rebalances_per_poll,
            _marker: PhantomData,
        })
    }
}

// =============================================================================
// TimerWheel
// =============================================================================

/// A multi-level, rebalancing timer wheel.
///
/// Generic over:
/// - `T` — the user payload stored with each timer.
/// - `S` — the slab storage backend. Defaults to `unbounded::Slab`.
///
/// # Thread Safety
///
/// `Send` but `!Sync`. Can be moved to a thread at setup but must not
/// be shared. All internal raw pointers point into owned allocations
/// (slab chunks, level slot arrays) — moving the wheel moves the heap
/// data with it.
pub struct TimerWheel<
    T: 'static,
    S: SlabStore<Item = WheelEntry<T>> = unbounded::Slab<WheelEntry<T>>,
> {
    slab: S,
    levels: Vec<Level<T>>,
    num_levels: usize,
    active_levels: u8,
    current_ticks: u64,
    tick_ns: u64,
    inv_tick_ns: u128,
    epoch: Instant,
    len: usize,
    min_deadline: Cell<Option<u64>>,
    /// Max entries rebalanced (moved to a finer level) per poll_and_rebalance (see
    /// [`WheelBuilder::max_rebalances_per_poll`]). `usize::MAX` = unbounded.
    max_rebalances_per_poll: usize,
    _marker: PhantomData<*const ()>, // !Send (overridden below), !Sync
}

// SAFETY: TimerWheel<T, S> exclusively owns all memory behind its raw pointers.
//
// Pointer inventory and ownership:
// - Slot `entry_head`/`entry_tail` — point into slab-owned memory (SlotCell
//   in a slab chunk). Slab chunks are Vec<SlotCell<T>> heap allocations.
// - DLL links (`WheelEntry::prev`, `WheelEntry::next`) — point to other
//   SlotCells in the same slab.
// - `Level::slots` — `Box<[WheelSlot<T>]>`, owned by the level.
//
// All pointed-to memory lives inside owned collections (Vec, Box<[T]>).
// When TimerWheel is moved, the heap allocations stay at their addresses —
// the internal pointers remain valid. No thread-local state. No shared
// ownership.
//
// T: Send is required because timer values cross the thread boundary with
// the wheel.
//
// S is NOT required to be Send. Slab types are !Send (raw pointers, Cell)
// but the wheel exclusively owns its slab — no shared access, no aliasing.
// Moving the wheel moves the slab; heap allocations stay at their addresses
// so internal pointers remain valid.
//
// Outstanding TimerHandle<T> values are !Send and cannot follow the wheel
// across threads. They become inert — consuming them requires &mut
// TimerWheel which the original thread no longer has. The debug_assert in
// TimerHandle::drop catches this as a programming error. Worst case is a
// slot leak (refcount stuck at 1), not unsoundness.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T: Send + 'static, S: SlabStore<Item = WheelEntry<T>>> Send for TimerWheel<T, S> {}

/// A timer wheel backed by a fixed-capacity slab.
pub type BoundedWheel<T> = TimerWheel<T, bounded::Slab<WheelEntry<T>>>;

/// A timer wheel backed by a growable slab.
pub type Wheel<T> = TimerWheel<T, unbounded::Slab<WheelEntry<T>>>;

// =============================================================================
// Construction
// =============================================================================

impl<T: 'static> Wheel<T> {
    /// Creates an unbounded timer wheel with default configuration.
    ///
    /// `now` fixes the reference epoch — pass one monotone clock source
    /// (e.g. `Instant::now()`) here and to every `schedule`/`poll`. For custom
    /// configuration, use [`WheelBuilder`].
    pub fn unbounded(chunk_capacity: usize, now: Instant) -> Self {
        WheelBuilder::default()
            .unbounded(chunk_capacity)
            .build(now)
            .expect("default WheelBuilder config is valid")
    }
}

impl<T: 'static> BoundedWheel<T> {
    /// Creates a bounded timer wheel with default configuration.
    ///
    /// `now` fixes the reference epoch — pass one monotone clock source
    /// (e.g. `Instant::now()`) here and to every `schedule`/`poll`. For custom
    /// configuration, use [`WheelBuilder`].
    pub fn bounded(capacity: usize, now: Instant) -> Self {
        WheelBuilder::default()
            .bounded(capacity)
            .build(now)
            .expect("default WheelBuilder config is valid")
    }
}

fn build_levels<T: 'static>(config: &WheelBuilder) -> Vec<Level<T>> {
    (0..config.num_levels)
        .map(|i| Level::new(config.slots_per_level, i, config.clk_shift))
        .collect()
}

// =============================================================================
// Schedule
// =============================================================================

impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S> {
    /// Schedules a timer and returns a handle for cancellation.
    ///
    /// The handle must be consumed via [`cancel`](Self::cancel) or
    /// [`free`](Self::free). Dropping it is a programming error.
    ///
    /// # Panics
    ///
    /// Panics if the backing slab is at capacity (bounded slabs only).
    /// This is a capacity planning error — size your wheel for peak load.
    pub fn schedule(&mut self, deadline: Instant, value: T) -> TimerHandle<T> {
        let deadline_ticks = self.instant_to_ticks(deadline);
        let entry = WheelEntry::new(deadline_ticks, value, 2);
        let slot = self.slab.alloc(entry);
        let ptr = slot.into_raw();
        self.insert_entry(ptr, deadline_ticks);
        self.len += 1;
        TimerHandle::new(ptr)
    }

    /// Schedules a fire-and-forget timer (no handle returned).
    ///
    /// The timer will fire during poll and the value will be collected.
    /// Cannot be cancelled.
    ///
    /// # Panics
    ///
    /// Panics if the backing slab is at capacity (bounded slabs only).
    /// This is a capacity planning error — size your wheel for peak load.
    pub fn schedule_forget(&mut self, deadline: Instant, value: T) {
        let deadline_ticks = self.instant_to_ticks(deadline);
        let entry = WheelEntry::new(deadline_ticks, value, 1);
        let slot = self.slab.alloc(entry);
        let ptr = slot.into_raw();
        self.insert_entry(ptr, deadline_ticks);
        self.len += 1;
    }
}

// =============================================================================
// Schedule — fallible (bounded slabs only)
// =============================================================================

impl<T: 'static, S: BoundedStore<Item = WheelEntry<T>>> TimerWheel<T, S> {
    /// Attempts to schedule a timer, returning a handle on success.
    ///
    /// Returns `Err(Full(value))` if the slab is at capacity. Use this
    /// when you need graceful error handling. For the common case where
    /// capacity exhaustion is fatal, use [`schedule`](Self::schedule).
    pub fn try_schedule(&mut self, deadline: Instant, value: T) -> Result<TimerHandle<T>, Full<T>> {
        let deadline_ticks = self.instant_to_ticks(deadline);
        let entry = WheelEntry::new(deadline_ticks, value, 2);
        match self.slab.try_alloc(entry) {
            Ok(slot) => {
                let ptr = slot.into_raw();
                self.insert_entry(ptr, deadline_ticks);
                self.len += 1;
                Ok(TimerHandle::new(ptr))
            }
            Err(full) => {
                // Extract the user's T from the WheelEntry wrapper
                let wheel_entry = full.into_inner();
                // SAFETY: entry was just constructed with Some(value) and never inserted
                // into the wheel — no other code has accessed it. Single-threaded.
                let value = unsafe { wheel_entry.take_value() }
                    .expect("entry was just constructed with Some(value)");
                Err(Full(value))
            }
        }
    }

    /// Attempts to schedule a fire-and-forget timer.
    ///
    /// Returns `Err(Full(value))` if the slab is at capacity. Use this
    /// when you need graceful error handling. For the common case where
    /// capacity exhaustion is fatal, use [`schedule_forget`](Self::schedule_forget).
    pub fn try_schedule_forget(&mut self, deadline: Instant, value: T) -> Result<(), Full<T>> {
        let deadline_ticks = self.instant_to_ticks(deadline);
        let entry = WheelEntry::new(deadline_ticks, value, 1);
        match self.slab.try_alloc(entry) {
            Ok(slot) => {
                let ptr = slot.into_raw();
                self.insert_entry(ptr, deadline_ticks);
                self.len += 1;
                Ok(())
            }
            Err(full) => {
                let wheel_entry = full.into_inner();
                // SAFETY: entry was just constructed with Some(value) and never inserted
                // into the wheel — no other code has accessed it. Single-threaded.
                let value = unsafe { wheel_entry.take_value() }
                    .expect("entry was just constructed with Some(value)");
                Err(Full(value))
            }
        }
    }
}

// =============================================================================
// Cancel / Free / Poll / Query — generic over any store
// =============================================================================

impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> TimerWheel<T, S> {
    /// Cancels a timer and returns its value.
    ///
    /// - If the timer is still active: unlinks from the wheel, extracts value,
    ///   frees the slab entry. Returns `Some(T)`.
    /// - If the timer already fired (zombie handle): frees the slab entry.
    ///   Returns `None`.
    ///
    /// Consumes the handle (no Drop runs).
    pub fn cancel(&mut self, handle: TimerHandle<T>) -> Option<T> {
        let ptr = handle.ptr;
        // Consume handle without running Drop
        mem::forget(handle);

        // SAFETY: handle guarantees ptr is valid and allocated from our slab.
        let entry = unsafe { entry_ref(ptr) };
        let refs = entry.refs();

        if refs == 2 {
            // Active timer with handle — unlink, extract, free
            // SAFETY: single-threaded access; entry is still in the wheel (refs==2),
            // so the value has not been taken by fire_entry.
            let value = unsafe { entry.take_value() };
            let cancelled_deadline = entry.deadline_ticks();
            self.remove_entry(ptr);
            self.len -= 1;
            if self.len == 0 {
                self.min_deadline.set(None);
            } else if let Some(cur) = self.min_deadline.get()
                && cancelled_deadline == cur
            {
                self.min_deadline.set(None);
            }
            // SAFETY: ptr was allocated from our slab via into_raw()
            self.slab.free(unsafe { Slot::from_raw(ptr) });
            value
        } else {
            // refs == 1 means the wheel already fired this (zombie).
            // The fire path decremented 2→1 and left the entry for us to free.
            debug_assert_eq!(refs, 1, "unexpected refcount {refs} in cancel");
            // SAFETY: ptr was allocated from our slab via into_raw()
            self.slab.free(unsafe { Slot::from_raw(ptr) });
            None
        }
    }

    /// Releases a timer handle without cancelling.
    ///
    /// - If the timer is still active: converts to fire-and-forget (refs 2→1).
    ///   Timer stays in the wheel and will fire normally during poll.
    /// - If the timer already fired (zombie): frees the slab entry (refs 1→0).
    ///
    /// Consumes the handle (no Drop runs).
    pub fn free(&mut self, handle: TimerHandle<T>) {
        let ptr = handle.ptr;
        mem::forget(handle);

        // SAFETY: handle guarantees ptr is valid
        let entry = unsafe { entry_ref(ptr) };
        let new_refs = entry.dec_refs();

        if new_refs == 0 {
            // Was a zombie (fired already, refs was 1) — free the entry
            // SAFETY: ptr was allocated from our slab via into_raw()
            self.slab.free(unsafe { Slot::from_raw(ptr) });
        }
        // new_refs == 1: timer is now fire-and-forget, stays in wheel
    }

    /// Reschedules an active timer to a new deadline.
    ///
    /// Moves the entry from its current slot to the correct slot for
    /// `new_deadline` without extracting or reconstructing the value.
    ///
    /// # Panics
    ///
    /// Panics if the timer has already fired (zombie handle). Only active
    /// timers (refs == 2) can be rescheduled.
    ///
    /// Consumes and returns a new handle (same entry, new position).
    pub fn reschedule(&mut self, handle: TimerHandle<T>, new_deadline: Instant) -> TimerHandle<T> {
        let ptr = handle.ptr;
        mem::forget(handle);

        // SAFETY: handle guarantees ptr is valid
        let entry = unsafe { entry_ref(ptr) };
        assert_eq!(entry.refs(), 2, "cannot reschedule a fired timer");

        let old_deadline = entry.deadline_ticks();

        // Remove from current position
        self.remove_entry(ptr);

        // Update deadline and reinsert
        let new_ticks = self.instant_to_ticks(new_deadline);
        entry.set_deadline_ticks(new_ticks);
        self.insert_entry(ptr, new_ticks);

        // Cache: if old deadline was the cached min and new is later,
        // we may have lost the min. insert_entry already handles
        // new < old (lowers cache), but can't detect old == cached
        // when moving later.
        if let Some(cur) = self.min_deadline.get()
            && old_deadline == cur
            && new_ticks > cur
        {
            self.min_deadline.set(None);
        }

        TimerHandle::new(ptr)
    }

    /// Collects all ready (due) timers into `buf`, **without rebalancing**, and
    /// returns how many were collected.
    ///
    /// This is the minimal poll: it hands back the timers whose deadline has
    /// passed and does no maintenance, so a not-yet-due entry stays in whatever
    /// level it was placed in. Cheap on any single call — but if you *only* ever
    /// call `poll`, entries are never moved to finer levels and a busy wheel
    /// degrades to an O(population) scan per poll. For steady low-latency
    /// polling, prefer [`poll_and_rebalance`](Self::poll_and_rebalance)
    /// (collect + maintain in one pass).
    pub fn poll(&mut self, now: Instant, buf: &mut Vec<T>) -> usize {
        self.poll_with_limit(now, usize::MAX, buf)
    }

    /// Collects up to `limit` ready timers into `buf`, without rebalancing.
    ///
    /// Resumable: if the limit is hit, the next call continues where this one
    /// left off (as long as `now` hasn't changed). See [`poll`](Self::poll) for
    /// the rebalancing tradeoff.
    ///
    /// Returns the number collected in this call.
    pub fn poll_with_limit(&mut self, now: Instant, limit: usize, buf: &mut Vec<T>) -> usize {
        // Rebalance budget 0 → collect only, never move an entry to a finer level.
        self.poll_inner(now, limit, 0, buf)
    }

    /// Collects all ready timers into `buf` **and rebalances** the wheel in the
    /// same pass — the batteries-included poll. Returns how many were collected.
    ///
    /// Collecting is unbounded; **rebalancing** (moving not-yet-due entries to
    /// finer levels so future polls stay cheap) is capped at
    /// [`max_rebalances_per_poll`](WheelBuilder::max_rebalances_per_poll)
    /// (default unbounded). The cap only smooths rebalance work across polls — it
    /// never delays or drops a fire.
    pub fn poll_and_rebalance(&mut self, now: Instant, buf: &mut Vec<T>) -> usize {
        self.poll_and_rebalance_with_limit(now, usize::MAX, buf)
    }

    /// Collects up to `limit` ready timers into `buf` and rebalances the wheel.
    ///
    /// The collect phase is resumable like
    /// [`poll_with_limit`](Self::poll_with_limit); rebalancing is capped by
    /// [`max_rebalances_per_poll`](WheelBuilder::max_rebalances_per_poll).
    /// Returns the number collected in this call.
    pub fn poll_and_rebalance_with_limit(
        &mut self,
        now: Instant,
        limit: usize,
        buf: &mut Vec<T>,
    ) -> usize {
        self.poll_inner(now, limit, self.max_rebalances_per_poll, buf)
    }

    /// **Proactively** rebalances the wheel: moves up to `limit` not-yet-due
    /// entries down to the finest level they now belong in, and returns how many
    /// moved. Does **not** collect or fire anything.
    ///
    /// This is the maintenance half of [`poll_and_rebalance`](Self::poll_and_rebalance),
    /// exposed on its own so you can move it *off* the collect hot path.
    ///
    /// # When to reach for this
    ///
    /// Use `poll` + `rebalance` (instead of `poll_and_rebalance`) when you have a
    /// **large number of outstanding timers and want to cut the poll tail**. The
    /// cost of a poll that has work is dominated by walking a fat coarse slot to
    /// find the ready timers; by pulling entries down to exact fine-level slots
    /// *before* their slot comes due, `rebalance` keeps that walk small, so the
    /// collect stays cheap and flat. In practice this moves the poll-tail work
    /// off the hot path onto `rebalance`, roughly quartering the collect's p99.9
    /// on a busy wheel — at the price of doing the maintenance yourself, when it
    /// suits you.
    ///
    /// # Recommended pattern: opportunistic + bounded
    ///
    /// Rebalance only when a poll came back empty — i.e. during genuine slack —
    /// and bound each call so a high-frequency loop spreads the work instead of
    /// stalling on one big sweep (`rebalance` is resumable; the next call
    /// continues):
    ///
    /// ```ignore
    /// let collected = wheel.poll(now, &mut buf);
    /// if collected == 0 {
    ///     // nothing to deliver — maintain during the slack, a bounded slice
    ///     wheel.rebalance(now, REBALANCE_BUDGET);
    /// }
    /// ```
    ///
    /// This self-tunes to load: busy iterations pay only the cheap collect, and
    /// the maintenance lands exactly on the idle ones. A fixed cadence (rebalance
    /// every N iterations) also works — just avoid rebalancing on *every* poll,
    /// which re-walks the look-ahead window and is pure overhead.
    ///
    /// # Safety of skipping it
    ///
    /// `rebalance` only visits slots whose earliest entry is already within a
    /// finer level's reach, and moving nothing is always safe: an un-rebalanced
    /// entry simply fires from wherever it is sitting when its time comes. If you
    /// never call it, the wheel still works — it just degrades to walking coarse
    /// slots on the collect path (which is what [`poll_and_rebalance`] does for
    /// you in one call).
    ///
    /// [`poll_and_rebalance`]: Self::poll_and_rebalance
    pub fn rebalance(&mut self, now: Instant, limit: usize) -> usize {
        let now_ticks = self.instant_to_ticks(now);
        self.current_ticks = now_ticks; // select_level / rebalance_level read this.

        let mut moved = 0;
        // Level 0 is already the finest — nothing to pull down from it. Ascending
        // order; select_level places each entry at its correct level directly, so
        // no entry is touched twice.
        let mut mask = self.active_levels & !1;
        while mask != 0 && moved < limit {
            let lvl_idx = mask.trailing_zeros() as usize;
            mask &= mask - 1;
            // An entry at this level belongs at a finer one once it is within the
            // next-finer level's range; a slot is worth visiting only if its
            // earliest entry has reached that window.
            let finer_reach = now_ticks.saturating_add(self.levels[lvl_idx - 1].range());
            moved += self.rebalance_level(lvl_idx, finer_reach, limit - moved);
        }

        // Entries moved and per-slot minima changed; refresh the global-min cache.
        self.min_deadline.set(self.walk_min_deadline());
        moved
    }

    /// Shared poll body: collect ready timers (up to `limit`) and rebalance
    /// not-yet-due entries to finer levels (up to `rebalance_budget`).
    /// `rebalance_budget == 0` is collect-only.
    fn poll_inner(
        &mut self,
        now: Instant,
        limit: usize,
        rebalance_budget: usize,
        buf: &mut Vec<T>,
    ) -> usize {
        let now_ticks = self.instant_to_ticks(now);
        self.current_ticks = now_ticks; // MUST precede the early return — select_level reads it.

        // Fast path: if the cached global minimum is beyond now, nothing is due,
        // so skip the level walk entirely — and with nothing due there is nothing
        // to rebalance either. The cache may be stale-low (a lower bound), so this
        // is conservative: it can miss the shortcut, never fire late.
        if let Some(min) = self.min_deadline.get()
            && min > now_ticks
        {
            return 0;
        }

        let mut fired = 0;
        // Rebalance budget for this whole poll. Bounds only rebalancing, never
        // collection — so the level loop below is NOT gated on it; due entries
        // keep being collected after the budget is spent.
        let mut rebalances = 0;
        let mut mask = self.active_levels;

        while mask != 0 && fired < limit {
            let lvl_idx = mask.trailing_zeros() as usize;
            mask &= mask - 1; // clear lowest set bit
            fired += self.poll_level(
                lvl_idx,
                now_ticks,
                limit - fired,
                rebalance_budget,
                &mut rebalances,
                buf,
            );
        }

        // Refresh the global-min cache from the (now-healed) per-slot minima.
        // poll_level heals every slot it walks, so this recomputes an accurate
        // minimum (> now when nothing is due). Without it the cache can stay
        // stale-low (<= now) after a cancel or a no-fire poll, permanently
        // defeating the early-exit above and making next_deadline() report a
        // past instant. Cheap now — one compare per active slot. (If a limit
        // truncated the poll, a walked-but-not-drained slot stays stale-low, so
        // the cache stays <= now and the next poll correctly re-enters.)
        self.min_deadline.set(self.walk_min_deadline());

        fired
    }

    /// Returns an `Instant` no later than when the next timer fires, or `None`
    /// if the wheel is empty.
    ///
    /// **Lower bound, not exact.** The per-slot minima are stale-low after a
    /// cancel/fire (they are not recomputed on removal — see the design), so the
    /// returned instant may be *earlier* than the true next deadline, never
    /// later. It is safe as a sleep/wake bound: you may wake early and find
    /// nothing due, but you can never miss a timer.
    ///
    /// O(1) on cache hit; otherwise ~one compare per active slot to recompute.
    pub fn next_deadline(&self) -> Option<Instant> {
        if let Some(ticks) = self.min_deadline.get() {
            return Some(self.ticks_to_instant(ticks));
        }
        if self.len == 0 {
            return None;
        }
        let min_ticks = self.walk_min_deadline();
        self.min_deadline.set(min_ticks);
        min_ticks.map(|t| self.ticks_to_instant(t))
    }

    /// Recomputes the wheel's minimum deadline from the per-slot minima —
    /// ~one compare per active slot, not one per entry.
    ///
    /// The per-slot minima may be stale-low (see `WheelSlot::min_deadline`), so
    /// the result is a **lower bound**: it may be earlier than the true minimum,
    /// never later. Callers (`next_deadline`, the poll early-exit) treat it
    /// conservatively — an under-estimate only ever costs extra work.
    #[cold]
    fn walk_min_deadline(&self) -> Option<u64> {
        // `any` (not `min_ticks != u64::MAX`) is the emptiness test: a real
        // far-future deadline can saturate to exactly u64::MAX in
        // `instant_to_ticks`, so the sentinel value is a legitimate minimum.
        let mut min_ticks = u64::MAX;
        let mut any = false;
        let mut lvl_mask = self.active_levels;
        while lvl_mask != 0 {
            let lvl_idx = lvl_mask.trailing_zeros() as usize;
            lvl_mask &= lvl_mask - 1;
            let level = &self.levels[lvl_idx];
            let mut slot_mask = level.active_slots();
            while slot_mask != 0 {
                let slot_idx = slot_mask.trailing_zeros() as usize;
                slot_mask &= slot_mask - 1;
                any = true;
                min_ticks = min_ticks.min(level.slot(slot_idx).min_deadline());
            }
        }
        any.then_some(min_ticks)
    }

    /// Test-only **exact** minimum deadline via a full entry walk (ignoring the
    /// per-slot minima) — the ground truth the lower-bound [`next_deadline`] is
    /// checked against.
    #[cfg(test)]
    fn next_deadline_uncached(&self) -> Option<Instant> {
        let mut min_ticks: Option<u64> = None;
        let mut lvl_mask = self.active_levels;
        while lvl_mask != 0 {
            let lvl_idx = lvl_mask.trailing_zeros() as usize;
            lvl_mask &= lvl_mask - 1;
            let level = &self.levels[lvl_idx];
            let mut slot_mask = level.active_slots();
            while slot_mask != 0 {
                let slot_idx = slot_mask.trailing_zeros() as usize;
                slot_mask &= slot_mask - 1;
                let slot = level.slot(slot_idx);
                let mut entry_ptr = slot.entry_head();
                while !entry_ptr.is_null() {
                    // SAFETY: entry_ptr is in this slot's DLL
                    let entry = unsafe { entry_ref(entry_ptr) };
                    let dt = entry.deadline_ticks();
                    min_ticks = Some(min_ticks.map_or(dt, |c| c.min(dt)));
                    entry_ptr = entry.next();
                }
            }
        }
        min_ticks.map(|t| self.ticks_to_instant(t))
    }

    /// Returns the number of timers currently in the wheel.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the wheel contains no timers.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    // =========================================================================
    // Internal: tick conversion
    // =========================================================================

    #[inline]
    fn instant_to_ticks(&self, instant: Instant) -> u64 {
        let dur = instant.saturating_duration_since(self.epoch);
        let nanos = dur.as_nanos().min(u64::MAX as u128) as u64;
        ((nanos as u128 * self.inv_tick_ns) >> 64) as u64
    }

    #[inline]
    fn ticks_to_instant(&self, ticks: u64) -> Instant {
        self.epoch + Duration::from_nanos(ticks.saturating_mul(self.tick_ns))
    }

    // =========================================================================
    // Internal: level selection
    // =========================================================================

    /// Selects the appropriate level for a deadline.
    ///
    /// Walks levels from finest to coarsest, picking the first level whose
    /// range can represent the delta. Clamps to the highest level if the
    /// deadline exceeds the wheel's total range.
    #[inline]
    fn select_level(&self, deadline_ticks: u64) -> usize {
        let delta = deadline_ticks.saturating_sub(self.current_ticks);

        for (i, level) in self.levels.iter().enumerate() {
            if delta < level.range() {
                return i;
            }
        }

        // Beyond max range — clamp to highest level
        self.num_levels - 1
    }

    // =========================================================================
    // Internal: entry insertion into a level's slot
    // =========================================================================

    /// Inserts an entry into the appropriate level and slot.
    ///
    /// Records the level and slot index on the entry so `remove_entry` can
    /// find it without recomputing (which would be unsound after time advances).
    #[inline]
    #[allow(clippy::needless_pass_by_ref_mut)]
    fn insert_entry(&mut self, entry_ptr: EntryPtr<T>, deadline_ticks: u64) {
        let lvl_idx = self.select_level(deadline_ticks);
        let slot_idx = self.levels[lvl_idx].slot_index(deadline_ticks);

        // Record location on the entry for O(1) lookup at cancel time.
        // SAFETY: entry_ptr is valid (just allocated)
        let entry = unsafe { entry_ref(entry_ptr) };
        entry.set_location(lvl_idx as u8, slot_idx as u16);

        // SAFETY: entry_ptr is valid (just allocated), not in any DLL yet
        unsafe { self.levels[lvl_idx].slot(slot_idx).push_entry(entry_ptr) };

        // Per-slot min: this entry may lower the slot's minimum. (Maintained here,
        // not in push_entry, so TimeoutQueue's shared slot pays nothing.)
        {
            let slot = self.levels[lvl_idx].slot(slot_idx);
            slot.set_min_deadline(slot.min_deadline().min(deadline_ticks));
        }

        // Activate slot and level (idempotent — OR is a no-op if already set)
        self.levels[lvl_idx].activate_slot(slot_idx);
        self.active_levels |= 1 << lvl_idx;

        // Cache: new entry may lower the minimum.
        // len is incremented by the caller AFTER insert_entry returns,
        // so self.len == 0 means the wheel was empty before this insert.
        match self.min_deadline.get() {
            None if self.len == 0 => {
                self.min_deadline.set(Some(deadline_ticks));
            }
            Some(cur) if deadline_ticks < cur => {
                self.min_deadline.set(Some(deadline_ticks));
            }
            _ => {}
        }
    }

    /// Removes an entry from its level's slot DLL.
    ///
    /// Reads the stored level and slot index from the entry (set at insertion
    /// time). Does NOT recompute from delta — that would be unsound after
    /// `current_ticks` advances.
    #[inline]
    #[allow(clippy::needless_pass_by_ref_mut)]
    fn remove_entry(&mut self, entry_ptr: EntryPtr<T>) {
        // SAFETY: entry_ptr is valid (caller guarantee)
        let entry = unsafe { entry_ref(entry_ptr) };

        let lvl_idx = entry.level() as usize;
        let slot_idx = entry.slot_idx() as usize;

        // SAFETY: entry_ptr is in this slot's DLL (invariant from insert_entry)
        unsafe { self.levels[lvl_idx].slot(slot_idx).remove_entry(entry_ptr) };

        if self.levels[lvl_idx].slot(slot_idx).is_empty() {
            // Drained: reset the slot min so an empty slot never reports a
            // stale-low deadline. A non-empty slot is left stale-low on purpose
            // (safe — see WheelSlot::min_deadline).
            self.levels[lvl_idx]
                .slot(slot_idx)
                .set_min_deadline(u64::MAX);
            self.levels[lvl_idx].deactivate_slot(slot_idx);
            if !self.levels[lvl_idx].is_active() {
                self.active_levels &= !(1 << lvl_idx);
            }
        }
    }

    // =========================================================================
    // Internal: fire an entry
    // =========================================================================

    /// Fires a single entry: extracts value, decrements refcount, possibly frees.
    ///
    /// Returns `Some(T)` if the value was still present (not already cancelled).
    #[inline]
    fn fire_entry(&mut self, entry_ptr: EntryPtr<T>) -> Option<T> {
        // SAFETY: entry_ptr is valid (we're walking the DLL)
        let entry = unsafe { entry_ref(entry_ptr) };

        let fired_deadline = entry.deadline_ticks();

        // Extract value
        // SAFETY: single-threaded
        let value = unsafe { entry.take_value() };

        let new_refs = entry.dec_refs();
        if new_refs == 0 {
            // Fire-and-forget (was refs=1) — free the slab entry immediately
            // SAFETY: entry_ptr was allocated from our slab via into_raw()
            self.slab.free(unsafe { Slot::from_raw(entry_ptr) });
        }
        // new_refs == 1: handle exists (was refs=2), entry becomes zombie.
        // Handle holder will free via cancel() or free().

        self.len -= 1;

        if self.len == 0 {
            self.min_deadline.set(None);
        } else if let Some(cur) = self.min_deadline.get()
            && fired_deadline == cur
        {
            self.min_deadline.set(None);
        }

        value
    }

    // =========================================================================
    // Internal: poll a single level
    // =========================================================================

    /// Polls a single level for expired entries up to `limit`.
    ///
    fn poll_level(
        &mut self,
        lvl_idx: usize,
        now_ticks: u64,
        limit: usize,
        rebalance_budget: usize,
        rebalances: &mut usize,
        buf: &mut Vec<T>,
    ) -> usize {
        let mut fired = 0;
        let mut mask = self.levels[lvl_idx].active_slots();

        while mask != 0 && fired < limit {
            let slot_idx = mask.trailing_zeros() as usize;
            mask &= mask - 1;

            let slot_ptr = self.levels[lvl_idx].slot(slot_idx) as *const crate::level::WheelSlot<T>;
            // SAFETY: slot_ptr points into self.levels[lvl_idx].slots
            // (Box<[WheelSlot<T>]>), a stable heap allocation never reallocated
            // during poll. fire_entry and insert_entry mutate self.slab, self.len,
            // self.active_levels, self.min_deadline, and *other* levels' slots —
            // rebalancing relocates only to strictly finer levels (< lvl_idx), never
            // this slot — so this slot's backing memory is untouched and `slot`
            // stays valid across the loop.
            let slot = unsafe { &*slot_ptr };

            // Slot-skip: if the slot's minimum deadline is beyond now, nothing
            // in it is due — do not touch a single entry. Stale-low is safe: it
            // only costs an unnecessary walk (handled below), never a skip.
            if slot.min_deadline() > now_ticks {
                continue;
            }

            let mut new_min = u64::MAX; // min over entries that stay in this slot
            let mut entry_ptr = slot.entry_head();

            while !entry_ptr.is_null() && fired < limit {
                // SAFETY: entry_ptr is in this slot's DLL
                let entry = unsafe { entry_ref(entry_ptr) };
                let next_entry = entry.next(); // captured before any unlink below
                let dt = entry.deadline_ticks();

                if dt <= now_ticks {
                    // Due — fire it.
                    // SAFETY: entry_ptr is in this slot's DLL (from entry_head,
                    // walked via next pointers within the same slot).
                    unsafe { slot.remove_entry(entry_ptr) };
                    if let Some(value) = self.fire_entry(entry_ptr) {
                        buf.push(value);
                    }
                    fired += 1;
                } else if *rebalances < rebalance_budget && self.select_level(dt) < lvl_idx {
                    // Not due, it now belongs at a strictly finer level, and we are
                    // still under the per-poll rebalance budget: relocate it down
                    // instead of re-walking it every poll until this slot's span
                    // passes. The target (< lvl_idx) is never this slot, so the walk
                    // terminates and the entry is not re-processed this poll (finer
                    // levels are polled first). current_ticks == now_ticks (set in
                    // poll_inner before this loop), so insert_entry selects the
                    // correct finer level.
                    // SAFETY: entry_ptr is in this slot's DLL.
                    unsafe { slot.remove_entry(entry_ptr) };
                    self.insert_entry(entry_ptr, dt);
                    *rebalances += 1;
                } else {
                    // Not due, and left in place — either it still belongs at this
                    // level (a far entry sharing the slot via the modular index:
                    // deadlines a full level-range apart map to the same slot), or
                    // the per-poll rebalance budget is spent. Either way it stays put
                    // and fires (or rebalances) on a later poll from wherever it sits;
                    // track it as the slot's surviving minimum. A spent budget can
                    // never make a timer fire late — poll still fires it the moment
                    // dt <= now, regardless of which level it is in.
                    new_min = new_min.min(dt);
                }

                entry_ptr = next_entry;
            }

            // If we walked the whole slot, its minimum is exactly the min over the
            // entries that stayed (u64::MAX — the empty sentinel — when the slot
            // drained via fires + rebalances). A limit-truncated walk (entry_ptr
            // non-null) leaves the min stale-low; the next poll re-walks and heals.
            if entry_ptr.is_null() {
                slot.set_min_deadline(new_min);
            }

            if slot.is_empty() {
                self.levels[lvl_idx].deactivate_slot(slot_idx);
            }
        }

        // Deactivate level if all slots drained
        if !self.levels[lvl_idx].is_active() {
            self.active_levels &= !(1 << lvl_idx);
        }

        fired
    }

    /// Proactively pulls not-yet-due entries at `lvl_idx` down to a finer level.
    /// Visits only active slots whose earliest entry has reached `finer_reach`
    /// (is within the next-finer level's range) and relocates each entry that now
    /// belongs at a strictly finer level, up to `limit`. Returns how many moved.
    /// Fires nothing.
    fn rebalance_level(&mut self, lvl_idx: usize, finer_reach: u64, limit: usize) -> usize {
        let mut moved = 0;
        let mut mask = self.levels[lvl_idx].active_slots();

        while mask != 0 && moved < limit {
            let slot_idx = mask.trailing_zeros() as usize;
            mask &= mask - 1;

            let slot_ptr = self.levels[lvl_idx].slot(slot_idx) as *const crate::level::WheelSlot<T>;
            // SAFETY: same argument as poll_level — slot_ptr points into the
            // stable Box<[WheelSlot<T>]>; insert_entry only ever relocates to a
            // strictly finer level (< lvl_idx), never this slot, so `slot` stays
            // valid across the loop.
            let slot = unsafe { &*slot_ptr };

            // Nothing to pull down yet if the earliest entry hasn't reached the
            // finer level's window.
            if slot.min_deadline() >= finer_reach {
                continue;
            }

            let mut new_min = u64::MAX;
            let mut entry_ptr = slot.entry_head();

            while !entry_ptr.is_null() && moved < limit {
                // SAFETY: entry_ptr is in this slot's DLL.
                let entry = unsafe { entry_ref(entry_ptr) };
                let next_entry = entry.next();
                let dt = entry.deadline_ticks();

                if self.select_level(dt) < lvl_idx {
                    // SAFETY: entry_ptr is in this slot's DLL.
                    unsafe { slot.remove_entry(entry_ptr) };
                    self.insert_entry(entry_ptr, dt);
                    moved += 1;
                } else {
                    // Still belongs at this level (modular-index neighbor a full
                    // range away, or budget-truncated). Leave it; track its min.
                    new_min = new_min.min(dt);
                }

                entry_ptr = next_entry;
            }

            // Fully-walked slot: its min is exactly the min over entries that
            // stayed. A limit-truncated walk (entry_ptr non-null) leaves it
            // stale-low; the next rebalance/poll re-walks and heals it.
            if entry_ptr.is_null() {
                slot.set_min_deadline(new_min);
            }

            if slot.is_empty() {
                self.levels[lvl_idx].deactivate_slot(slot_idx);
            }
        }

        moved
    }
}

// =============================================================================
// Drop
// =============================================================================

impl<T: 'static, S: SlabStore<Item = WheelEntry<T>>> Drop for TimerWheel<T, S> {
    fn drop(&mut self) {
        // Walk active levels and slots via bitmasks, free every entry.
        let mut lvl_mask = self.active_levels;
        while lvl_mask != 0 {
            let lvl_idx = lvl_mask.trailing_zeros() as usize;
            lvl_mask &= lvl_mask - 1;

            let level = &self.levels[lvl_idx];
            let mut slot_mask = level.active_slots();
            while slot_mask != 0 {
                let slot_idx = slot_mask.trailing_zeros() as usize;
                slot_mask &= slot_mask - 1;

                let slot = level.slot(slot_idx);
                let mut entry_ptr = slot.entry_head();
                while !entry_ptr.is_null() {
                    // SAFETY: entry_ptr is in this slot's DLL
                    let entry = unsafe { entry_ref(entry_ptr) };
                    let next_entry = entry.next();

                    // SAFETY: entry_ptr was allocated from our slab via into_raw()
                    self.slab.free(unsafe { Slot::from_raw(entry_ptr) });

                    entry_ptr = next_entry;
                }
            }
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, Instant};

    fn ms(millis: u64) -> Duration {
        Duration::from_millis(millis)
    }

    // -------------------------------------------------------------------------
    // Thread safety
    // -------------------------------------------------------------------------

    fn assert_send<T: Send>() {}

    #[test]
    fn wheel_is_send() {
        assert_send::<Wheel<u64>>();
        assert_send::<BoundedWheel<u64>>();
    }

    // -------------------------------------------------------------------------
    // Construction
    // -------------------------------------------------------------------------

    #[test]
    fn default_config() {
        let now = Instant::now();
        let wheel: Wheel<u64> = Wheel::unbounded(1024, now);
        assert!(wheel.is_empty());
        assert_eq!(wheel.len(), 0);
    }

    #[test]
    fn bounded_construction() {
        let now = Instant::now();
        let wheel: BoundedWheel<u64> = BoundedWheel::bounded(128, now);
        assert!(wheel.is_empty());
    }

    #[test]
    fn invalid_config_non_power_of_two() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .slots_per_level(65)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "power of 2");
    }

    // -------------------------------------------------------------------------
    // Schedule + Cancel
    // -------------------------------------------------------------------------

    #[test]
    fn schedule_and_cancel() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(50), 42);
        assert_eq!(wheel.len(), 1);

        let val = wheel.cancel(h);
        assert_eq!(val, Some(42));
        assert_eq!(wheel.len(), 0);
    }

    #[test]
    fn schedule_forget_fires() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(10), 99);
        assert_eq!(wheel.len(), 1);

        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(20), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![99]);
        assert_eq!(wheel.len(), 0);
    }

    #[test]
    fn cancel_after_fire_returns_none() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(10), 42);

        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);
        assert_eq!(buf, vec![42]);

        // Handle is now a zombie
        let val = wheel.cancel(h);
        assert_eq!(val, None);
    }

    #[test]
    fn free_active_timer_becomes_fire_and_forget() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(10), 42);
        wheel.free(h); // releases handle, timer stays
        assert_eq!(wheel.len(), 1);

        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);
        assert_eq!(buf, vec![42]);
        assert_eq!(wheel.len(), 0);
    }

    #[test]
    fn free_zombie_handle() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(10), 42);

        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);

        // Handle is zombie, free should clean up
        wheel.free(h);
    }

    // -------------------------------------------------------------------------
    // Bounded wheel
    // -------------------------------------------------------------------------

    #[test]
    fn bounded_full() {
        let now = Instant::now();
        let mut wheel: BoundedWheel<u64> = BoundedWheel::bounded(2, now);

        let h1 = wheel.try_schedule(now + ms(10), 1).unwrap();
        let h2 = wheel.try_schedule(now + ms(20), 2).unwrap();

        let err = wheel.try_schedule(now + ms(30), 3);
        assert!(err.is_err());
        let recovered = err.unwrap_err().into_inner();
        assert_eq!(recovered, 3);

        // Cancel one, should have room
        wheel.cancel(h1);
        let h3 = wheel.try_schedule(now + ms(30), 3).unwrap();

        // Clean up handles
        wheel.free(h2);
        wheel.free(h3);
    }

    #[test]
    fn bounded_schedule_forget_full() {
        let now = Instant::now();
        let mut wheel: BoundedWheel<u64> = BoundedWheel::bounded(1, now);

        wheel.try_schedule_forget(now + ms(10), 1).unwrap();
        let err = wheel.try_schedule_forget(now + ms(20), 2);
        assert!(err.is_err());
    }

    // -------------------------------------------------------------------------
    // Poll
    // -------------------------------------------------------------------------

    #[test]
    fn poll_respects_deadline() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(10), 1);
        wheel.schedule_forget(now + ms(50), 2);
        wheel.schedule_forget(now + ms(100), 3);

        let mut buf = Vec::new();

        // At 20ms: only timer 1 should fire
        let fired = wheel.poll(now + ms(20), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![1]);
        assert_eq!(wheel.len(), 2);

        // At 60ms: timer 2 fires
        buf.clear();
        let fired = wheel.poll(now + ms(60), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![2]);

        // At 200ms: timer 3 fires
        buf.clear();
        let fired = wheel.poll(now + ms(200), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![3]);

        assert!(wheel.is_empty());
    }

    #[test]
    fn poll_with_limit() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        for i in 0..10 {
            wheel.schedule_forget(now + ms(1), i);
        }

        let mut buf = Vec::new();

        // Fire 3 at a time
        let fired = wheel.poll_with_limit(now + ms(5), 3, &mut buf);
        assert_eq!(fired, 3);
        assert_eq!(wheel.len(), 7);

        let fired = wheel.poll_with_limit(now + ms(5), 3, &mut buf);
        assert_eq!(fired, 3);
        assert_eq!(wheel.len(), 4);

        // Fire remaining
        let fired = wheel.poll(now + ms(5), &mut buf);
        assert_eq!(fired, 4);
        assert!(wheel.is_empty());
        assert_eq!(buf.len(), 10);
    }

    // -------------------------------------------------------------------------
    // Multi-level
    // -------------------------------------------------------------------------

    #[test]
    fn timers_across_levels() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Level 0: 0-63ms
        wheel.schedule_forget(now + ms(5), 0);
        // Level 1: 64-511ms
        wheel.schedule_forget(now + ms(200), 1);
        // Level 2: 512-4095ms
        wheel.schedule_forget(now + ms(1000), 2);

        let mut buf = Vec::new();

        wheel.poll(now + ms(10), &mut buf);
        assert_eq!(buf, vec![0]);

        buf.clear();
        wheel.poll(now + ms(250), &mut buf);
        assert_eq!(buf, vec![1]);

        buf.clear();
        wheel.poll(now + ms(1500), &mut buf);
        assert_eq!(buf, vec![2]);

        assert!(wheel.is_empty());
    }

    // -------------------------------------------------------------------------
    // next_deadline
    // -------------------------------------------------------------------------

    #[test]
    fn next_deadline_empty() {
        let now = Instant::now();
        let wheel: Wheel<u64> = Wheel::unbounded(1024, now);
        assert!(wheel.next_deadline().is_none());
    }

    #[test]
    fn next_deadline_returns_earliest() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(100), 1);
        wheel.schedule_forget(now + ms(50), 2);
        wheel.schedule_forget(now + ms(200), 3);

        let next = wheel.next_deadline().unwrap();
        // Should be close to now + 50ms (within tick granularity)
        let delta = next.duration_since(now);
        assert!(delta >= ms(49) && delta <= ms(51));
    }

    #[test]
    fn next_deadline_cache_invalidates_on_cancel() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h1 = wheel.schedule(now + ms(50), 1);
        wheel.schedule_forget(now + ms(100), 2);
        wheel.schedule_forget(now + ms(200), 3);

        // Cached at 50ms
        let d1 = wheel.next_deadline().unwrap();
        assert!(d1.duration_since(now) >= ms(49) && d1.duration_since(now) <= ms(51));

        // Cancel the earliest — cache invalidated, should return ~100ms
        wheel.cancel(h1);
        let d2 = wheel.next_deadline().unwrap();
        assert!(d2.duration_since(now) >= ms(99) && d2.duration_since(now) <= ms(101));
    }

    #[test]
    fn next_deadline_cache_invalidates_on_fire() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(50), 1);
        wheel.schedule_forget(now + ms(100), 2);
        wheel.schedule_forget(now + ms(200), 3);

        // Prime cache
        let _ = wheel.next_deadline();

        // Fire earliest via poll
        let mut buf = Vec::new();
        wheel.poll(now + ms(60), &mut buf);
        assert_eq!(buf, vec![1]);

        // Cache invalidated, should return ~100ms
        let d = wheel.next_deadline().unwrap();
        assert!(d.duration_since(now) >= ms(99) && d.duration_since(now) <= ms(101));
    }

    #[test]
    fn next_deadline_cache_updates_on_insert() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(100), 1);
        let d1 = wheel.next_deadline().unwrap();
        assert!(d1.duration_since(now) >= ms(99) && d1.duration_since(now) <= ms(101));

        // Insert an earlier timer — cache should update
        wheel.schedule_forget(now + ms(30), 2);
        let d2 = wheel.next_deadline().unwrap();
        assert!(d2.duration_since(now) >= ms(29) && d2.duration_since(now) <= ms(31));
    }

    #[test]
    fn next_deadline_after_reschedule_later() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h_a = wheel.schedule(now + ms(50), 1);
        wheel.schedule_forget(now + ms(100), 2);

        let d1 = wheel.next_deadline().unwrap();
        assert!(d1.duration_since(now) >= ms(49) && d1.duration_since(now) <= ms(51));

        // Reschedule A later — B becomes earliest
        let h_a = wheel.reschedule(h_a, now + ms(200));
        let d2 = wheel.next_deadline().unwrap();
        assert!(d2.duration_since(now) >= ms(99) && d2.duration_since(now) <= ms(101));
        mem::forget(h_a);
    }

    #[test]
    fn next_deadline_after_reschedule_earlier() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h_a = wheel.schedule(now + ms(100), 1);
        wheel.schedule_forget(now + ms(50), 2);

        let d1 = wheel.next_deadline().unwrap();
        assert!(d1.duration_since(now) >= ms(49) && d1.duration_since(now) <= ms(51));

        // Reschedule A earlier — A becomes new earliest
        let h_a = wheel.reschedule(h_a, now + ms(25));
        let d2 = wheel.next_deadline().unwrap();
        assert!(d2.duration_since(now) >= ms(24) && d2.duration_since(now) <= ms(26));
        mem::forget(h_a);
    }

    #[test]
    fn next_deadline_repeated_calls_stable() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(50), 1);
        wheel.schedule_forget(now + ms(100), 2);
        wheel.schedule_forget(now + ms(200), 3);

        let d1 = wheel.next_deadline();
        let d2 = wheel.next_deadline();
        let d3 = wheel.next_deadline();
        assert_eq!(d1, d2);
        assert_eq!(d2, d3);
    }

    // -------------------------------------------------------------------------
    // Reciprocal precision
    // -------------------------------------------------------------------------

    #[test]
    fn reciprocal_instant_to_ticks_precision() {
        // Reciprocal multiply is at most 1 tick low vs true integer division.
        // Verify across multiple tick_ns values and multiples.
        let now = Instant::now();

        for &tick_ns in &[1_000_000u64, 1_000, 100, 999_999, 7_500_000] {
            let wheel: Wheel<u64> = WheelBuilder::default()
                .tick_duration(Duration::from_nanos(tick_ns))
                .unbounded(64)
                .build(now)
                .unwrap();

            for n in 0..500u64 {
                let nanos = n * tick_ns;
                let instant = now + Duration::from_nanos(nanos);
                let got = wheel.instant_to_ticks(instant);
                let exact = nanos / tick_ns;
                let diff = exact as i64 - got as i64;
                assert!(
                    diff >= 0 && diff <= 1,
                    "tick_ns={tick_ns}, n={n}: exact={exact}, got={got}, diff={diff}",
                );
            }
        }
    }

    // -------------------------------------------------------------------------
    // Deadline in the past
    // -------------------------------------------------------------------------

    #[test]
    fn deadline_in_the_past_fires_immediately() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Schedule at epoch (which is "now" at construction)
        wheel.schedule_forget(now, 42);

        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(1), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![42]);
    }

    // -------------------------------------------------------------------------
    // Deadline beyond max range — clamped
    // -------------------------------------------------------------------------

    #[test]
    fn deadline_beyond_max_range_clamped() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Way in the future — should clamp to highest level
        let h = wheel.schedule(now + Duration::from_secs(100_000), 99);
        assert_eq!(wheel.len(), 1);

        // Won't fire at any reasonable time but will fire when enough ticks pass
        let mut buf = Vec::new();
        wheel.poll(now + Duration::from_secs(100_001), &mut buf);
        assert_eq!(buf, vec![99]);

        // Note: handle was already consumed by the poll (fire-and-forget path won't
        // apply since refs=2). Actually the handle still exists. Let's clean up.
        // The timer already fired, so cancel returns None.
        // Actually buf got the value, which means it fired. But handle still needs cleanup.
        // We already pushed the value so we need to handle the zombie.
        // Wait — we used schedule (refs=2), poll fired it (refs 2→1 zombie), handle `h` exists.
        // Actually we consumed it with the poll — no we didn't, we still have `h`.

        // h is a zombie handle now
        let val = wheel.cancel(h);
        assert_eq!(val, None);
    }

    // -------------------------------------------------------------------------
    // Drop
    // -------------------------------------------------------------------------

    #[test]
    fn drop_cleans_up_active_entries() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(1024, now);

        for i in 0..100 {
            wheel.schedule_forget(now + ms(i * 10), format!("timer-{i}"));
        }

        assert_eq!(wheel.len(), 100);
        // Drop should free all entries without leaking
        drop(wheel);
    }

    #[test]
    fn drop_with_outstanding_handles() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Schedule but DON'T cancel — just free the handles
        let h1 = wheel.schedule(now + ms(10), 1);
        let h2 = wheel.schedule(now + ms(20), 2);

        // Free the handles (convert to fire-and-forget) so they don't debug_assert
        wheel.free(h1);
        wheel.free(h2);

        // Drop the wheel — should clean up the entries
        drop(wheel);
    }

    // -------------------------------------------------------------------------
    // Level selection
    // -------------------------------------------------------------------------

    #[test]
    fn level_selection_boundaries() {
        let now = Instant::now();
        let wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Level 0: delta < 64
        assert_eq!(wheel.select_level(0), 0);
        assert_eq!(wheel.select_level(63), 0);

        // Level 1: 64 <= delta < 512
        assert_eq!(wheel.select_level(64), 1);
        assert_eq!(wheel.select_level(511), 1);

        // Level 2: 512 <= delta < 4096
        assert_eq!(wheel.select_level(512), 2);
    }

    // -------------------------------------------------------------------------
    // Bug fix validation: cancel after time advance
    // -------------------------------------------------------------------------

    #[test]
    fn cancel_after_time_advance() {
        // The critical bug: schedule at T+500ms (level 2, delta=500 ticks),
        // poll at T+400ms (no fire, but current_ticks advances to 400),
        // cancel at T+400ms. Old code would recompute delta = 500-400 = 100
        // → level 1. But the entry is in level 2. Stored location fixes this.
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(500), 42);
        assert_eq!(wheel.len(), 1);

        // Advance time — timer doesn't fire (deadline is 500ms)
        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(400), &mut buf);
        assert_eq!(fired, 0);
        assert!(buf.is_empty());

        // Cancel after time advance — must find the entry in the correct slot
        let val = wheel.cancel(h);
        assert_eq!(val, Some(42));
        assert_eq!(wheel.len(), 0);
    }

    // -------------------------------------------------------------------------
    // Per-slot min: stale-low safety
    // -------------------------------------------------------------------------

    #[test]
    fn slot_min_stale_low_after_cancel_still_fires() {
        // Cancelling the earliest entry in a non-empty slot leaves that slot's
        // cached min stale-low (the per-slot minima are not recomputed on
        // remove). Poll must still fire the SURVIVORS at the right times — never
        // skip a due entry, never fire an early one.
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // 3000 / 3001 / 3002 ms all land in the same level-2 slot.
        let h0 = wheel.schedule(now + ms(3000), 0);
        wheel.schedule_forget(now + ms(3001), 1);
        wheel.schedule_forget(now + ms(3002), 2);

        // Cancel the earliest — the slot min now points at 3000 (gone): stale-low.
        assert_eq!(wheel.cancel(h0), Some(0));

        let mut buf = Vec::new();
        assert_eq!(wheel.poll(now + ms(3000), &mut buf), 0, "nothing due yet");
        assert!(buf.is_empty());

        let fired = wheel.poll(now + ms(3002), &mut buf);
        assert_eq!(fired, 2, "both survivors fire once due");
        buf.sort_unstable();
        assert_eq!(buf, vec![1, 2]);
    }

    #[test]
    fn slot_min_resets_on_drain_and_reinsert() {
        // A drained slot resets its min to u64::MAX; a later insert must set the
        // min fresh, not inherit a stale value.
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        wheel.schedule_forget(now + ms(3000), 0);
        let mut buf = Vec::new();
        assert_eq!(wheel.poll(now + ms(3000), &mut buf), 1);
        assert!(wheel.is_empty());
        assert!(wheel.next_deadline().is_none());

        // Re-insert (likely into the same drained slot).
        wheel.schedule_forget(now + ms(3000), 1);
        let nd = wheel.next_deadline().expect("non-empty");
        assert!(nd <= now + ms(3000)); // lower bound — never later than the true deadline
        buf.clear();
        assert_eq!(wheel.poll(now + ms(2999), &mut buf), 0);
        assert_eq!(wheel.poll(now + ms(3000), &mut buf), 1);
    }

    #[test]
    fn poll_refreshes_stale_low_cache() {
        // Cancelling the slot-min entry leaves the slot min — and, once read, the
        // global cache — stale-low, pointing at the cancelled deadline. A poll
        // that finds nothing due must refresh the cache off that stale value;
        // otherwise it stays <= now forever, defeating the early-exit and making
        // next_deadline() report a past instant.
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // 3000 / 3002 ms share a slot. Cancel the earlier one.
        let h0 = wheel.schedule(now + ms(3000), 0);
        wheel.schedule_forget(now + ms(3002), 1);
        assert_eq!(wheel.cancel(h0), Some(0));

        // Populate the (now stale-low) cache: it points at the cancelled 3000.
        let stale = wheel.next_deadline().expect("non-empty");
        assert!(stale <= now + ms(3000));

        // Poll past 3000 but before 3002 — nothing fires; the slot heals to 3002
        // and the cache is refreshed at the end of the poll.
        let mut buf = Vec::new();
        assert_eq!(wheel.poll(now + ms(3001), &mut buf), 0);

        // Regression: without the poll-end refresh this would still be the
        // cancelled ~3000 (in the past). It must now reflect the survivor —
        // compared against the captured stale value so tick-rounding is irrelevant.
        let refreshed = wheel.next_deadline().expect("non-empty");
        assert!(
            refreshed > stale,
            "cache must refresh past the stale-low value after a no-fire poll",
        );
    }

    // -------------------------------------------------------------------------
    // Same-slot entries
    // -------------------------------------------------------------------------

    #[test]
    fn multiple_entries_same_slot() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // All 5 timers at the same deadline → same slot
        let mut handles = Vec::new();
        for i in 0..5 {
            handles.push(wheel.schedule(now + ms(10), i));
        }
        assert_eq!(wheel.len(), 5);

        // Cancel the middle ones
        let v2 = wheel.cancel(handles.remove(2));
        assert_eq!(v2, Some(2));
        let v0 = wheel.cancel(handles.remove(0));
        assert_eq!(v0, Some(0));
        assert_eq!(wheel.len(), 3);

        // Poll — remaining 3 should fire
        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(20), &mut buf);
        assert_eq!(fired, 3);

        // Clean up zombie handles
        for h in handles {
            let val = wheel.cancel(h);
            assert_eq!(val, None); // already fired
        }
    }

    // -------------------------------------------------------------------------
    // Level boundary
    // -------------------------------------------------------------------------

    #[test]
    fn entry_at_level_boundary() {
        // Default config: level 0 range = 64 ticks (64ms).
        // A deadline at exactly tick 64 should go to level 1, not level 0.
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(64), 99);
        assert_eq!(wheel.len(), 1);

        // Should NOT fire at 63ms
        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(63), &mut buf);
        assert_eq!(fired, 0);

        // Should fire at 64ms
        let fired = wheel.poll(now + ms(65), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![99]);

        // Clean up zombie handle
        wheel.cancel(h);
    }

    // -------------------------------------------------------------------------
    // Bookmark/resumption with mixed expiry
    // -------------------------------------------------------------------------

    #[test]
    fn poll_with_limit_mixed_expiry() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // 3 expired at poll time, 2 not
        wheel.schedule_forget(now + ms(5), 1);
        wheel.schedule_forget(now + ms(5), 2);
        wheel.schedule_forget(now + ms(5), 3);
        wheel.schedule_forget(now + ms(500), 4); // not expired
        wheel.schedule_forget(now + ms(500), 5); // not expired
        assert_eq!(wheel.len(), 5);

        let mut buf = Vec::new();

        // Fire 2 of the 3 expired
        let fired = wheel.poll_with_limit(now + ms(10), 2, &mut buf);
        assert_eq!(fired, 2);
        assert_eq!(wheel.len(), 3);

        // Fire remaining expired (1 more)
        let fired = wheel.poll_with_limit(now + ms(10), 5, &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(wheel.len(), 2);

        // The 2 unexpired should still be there
        assert_eq!(buf.len(), 3);
    }

    // -------------------------------------------------------------------------
    // Re-add after drain
    // -------------------------------------------------------------------------

    #[test]
    fn reuse_after_full_drain() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Round 1: schedule and drain
        for i in 0..10 {
            wheel.schedule_forget(now + ms(1), i);
        }
        let mut buf = Vec::new();
        wheel.poll(now + ms(5), &mut buf);
        assert_eq!(buf.len(), 10);
        assert!(wheel.is_empty());

        // Round 2: schedule and drain again — wheel must work normally
        buf.clear();
        for i in 10..20 {
            wheel.schedule_forget(now + ms(100), i);
        }
        assert_eq!(wheel.len(), 10);

        wheel.poll(now + ms(200), &mut buf);
        assert_eq!(buf.len(), 10);
        assert!(wheel.is_empty());
    }

    // -------------------------------------------------------------------------
    // All levels active simultaneously
    // -------------------------------------------------------------------------

    #[test]
    fn all_levels_active() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        // Schedule one timer per level with increasing distances.
        // Level 0: <64ms, Level 1: 64-511ms, Level 2: 512-4095ms, etc.
        let distances = [10, 100, 1000, 5000, 40_000, 300_000, 3_000_000];
        let mut handles: Vec<TimerHandle<u64>> = Vec::new();
        for (i, &d) in distances.iter().enumerate() {
            handles.push(wheel.schedule(now + ms(d), i as u64));
        }
        assert_eq!(wheel.len(), 7);

        // Cancel in a shuffled order: 4, 1, 6, 0, 3, 5, 2
        let order = [4, 1, 6, 0, 3, 5, 2];
        // Take ownership by swapping with dummies — actually we need to
        // cancel by index. Let's use Option to track.
        let mut opt_handles: Vec<Option<TimerHandle<u64>>> =
            handles.into_iter().map(Some).collect();

        for &idx in &order {
            let h = opt_handles[idx].take().unwrap();
            let val = wheel.cancel(h);
            assert_eq!(val, Some(idx as u64));
        }
        assert!(wheel.is_empty());
    }

    // -------------------------------------------------------------------------
    // Poll values match
    // -------------------------------------------------------------------------

    #[test]
    fn poll_values_match() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let expected: Vec<u64> = (100..110).collect();
        for &v in &expected {
            wheel.schedule_forget(now + ms(5), v);
        }

        let mut buf = Vec::new();
        wheel.poll(now + ms(10), &mut buf);

        buf.sort_unstable();
        assert_eq!(buf, expected);
    }

    // -------------------------------------------------------------------------
    // Reschedule
    // -------------------------------------------------------------------------

    #[test]
    fn reschedule_moves_deadline() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(100), 42);
        assert_eq!(wheel.len(), 1);

        // Reschedule to earlier
        let h = wheel.reschedule(h, now + ms(50));
        assert_eq!(wheel.len(), 1);

        // Should NOT fire at 40ms
        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(40), &mut buf);
        assert_eq!(fired, 0);

        // Should fire at 50ms
        let fired = wheel.poll(now + ms(55), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![42]);

        // Clean up zombie
        wheel.cancel(h);
    }

    #[test]
    fn reschedule_to_later() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(50), 7);

        // Reschedule to later
        let h = wheel.reschedule(h, now + ms(200));

        // Should NOT fire at original deadline
        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(60), &mut buf);
        assert_eq!(fired, 0);

        // Should fire at new deadline
        let fired = wheel.poll(now + ms(210), &mut buf);
        assert_eq!(fired, 1);
        assert_eq!(buf, vec![7]);

        wheel.cancel(h);
    }

    #[test]
    #[should_panic(expected = "cannot reschedule a fired timer")]
    fn reschedule_panics_on_zombie() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

        let h = wheel.schedule(now + ms(10), 42);

        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);

        // h is now a zombie — reschedule should panic
        let _h = wheel.reschedule(h, now + ms(100));
    }

    // -------------------------------------------------------------------------
    // Non-default builder configurations (L13)
    // -------------------------------------------------------------------------

    #[test]
    fn custom_slots_per_level() {
        let now = Instant::now();
        // 32 slots/level instead of default 64
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .slots_per_level(32)
            .unbounded(256)
            .build(now)
            .unwrap();

        // Level 0 range = 32 ticks (32ms with 1ms tick)
        // Deadline at 20ms should go to level 0
        let h1 = wheel.schedule(now + ms(20), 1);
        // Deadline at 40ms should go to level 1 (>= 32 ticks)
        let h2 = wheel.schedule(now + ms(40), 2);

        let mut buf = Vec::new();
        wheel.poll(now + ms(25), &mut buf);
        assert_eq!(buf, vec![1]);

        buf.clear();
        wheel.poll(now + ms(50), &mut buf);
        assert_eq!(buf, vec![2]);

        wheel.cancel(h1);
        wheel.cancel(h2);
    }

    #[test]
    fn custom_clk_shift() {
        let now = Instant::now();
        // clk_shift=2 means 4x multiplier between levels (instead of 8x)
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .clk_shift(2)
            .unbounded(256)
            .build(now)
            .unwrap();

        // Level 0: 64 slots × 1ms = 64ms range
        // Level 1: 64 slots × 4ms = 256ms range (with 4x multiplier)
        let h1 = wheel.schedule(now + ms(50), 1); // level 0
        let h2 = wheel.schedule(now + ms(100), 2); // level 1 (>= 64 ticks, <256 ticks)

        let mut buf = Vec::new();
        wheel.poll(now + ms(55), &mut buf);
        assert_eq!(buf, vec![1]);

        buf.clear();
        wheel.poll(now + ms(110), &mut buf);
        assert_eq!(buf, vec![2]);

        wheel.cancel(h1);
        wheel.cancel(h2);
    }

    #[test]
    fn custom_num_levels() {
        let now = Instant::now();
        // Only 3 levels instead of 7
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .num_levels(3)
            .unbounded(256)
            .build(now)
            .unwrap();

        // Level 0: 64ms, Level 1: 512ms, Level 2: 4096ms
        // Max range is level 2 = 4096ms. Beyond that, clamped.
        let h = wheel.schedule(now + ms(3000), 42);
        assert_eq!(wheel.len(), 1);

        let mut buf = Vec::new();
        wheel.poll(now + ms(3100), &mut buf);
        assert_eq!(buf, vec![42]);

        wheel.cancel(h);
    }

    #[test]
    fn custom_tick_duration() {
        let now = Instant::now();
        // 100μs ticks instead of 1ms
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .tick_duration(Duration::from_micros(100))
            .unbounded(256)
            .build(now)
            .unwrap();

        // 1ms = 10 ticks, should be level 0 (< 64 ticks)
        wheel.schedule_forget(now + ms(1), 1);
        // 10ms = 100 ticks, should be level 1 (>= 64 ticks)
        wheel.schedule_forget(now + ms(10), 2);

        let mut buf = Vec::new();
        wheel.poll(now + ms(2), &mut buf);
        assert_eq!(buf, vec![1]);

        buf.clear();
        wheel.poll(now + ms(15), &mut buf);
        assert_eq!(buf, vec![2]);
    }

    #[test]
    fn bounded_custom_config() {
        let now = Instant::now();
        let mut wheel: BoundedWheel<u64> = WheelBuilder::default()
            .slots_per_level(16)
            .num_levels(4)
            .bounded(8)
            .build(now)
            .unwrap();

        // Fill to capacity
        let mut handles = Vec::new();
        for i in 0..8 {
            handles.push(wheel.try_schedule(now + ms(i * 10 + 10), i).unwrap());
        }
        assert!(wheel.try_schedule(now + ms(100), 99).is_err());

        // Cancel one, schedule another
        wheel.cancel(handles.remove(0));
        let h = wheel.try_schedule(now + ms(100), 99).unwrap();
        handles.push(h);

        // Clean up
        for h in handles {
            wheel.cancel(h);
        }
    }

    // -------------------------------------------------------------------------
    // Builder validation (L13)
    // -------------------------------------------------------------------------

    /// Asserts `result` is `Err(ConfigError::Invalid(_))` whose message contains
    /// `expect_substr`. Generic over the Ok type so it needs no `Debug` bound on
    /// the built wheel.
    #[track_caller]
    fn assert_invalid<T>(result: &Result<T, ConfigError>, expect_substr: &str) {
        match result {
            Err(ConfigError::Invalid(msg)) => assert!(
                msg.contains(expect_substr),
                "message {msg:?} does not contain {expect_substr:?}"
            ),
            Ok(_) => panic!("expected ConfigError::Invalid containing {expect_substr:?}, got Ok"),
        }
    }

    #[test]
    fn invalid_config_too_many_slots() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .slots_per_level(128)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "slots_per_level must be <= 64");
    }

    #[test]
    fn invalid_config_zero_levels() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .num_levels(0)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "num_levels must be > 0");
    }

    #[test]
    fn invalid_config_too_many_levels() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .num_levels(9)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "num_levels must be <= 8");
    }

    #[test]
    fn invalid_config_zero_shift() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .clk_shift(0)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "clk_shift must be > 0");
    }

    #[test]
    fn invalid_config_zero_tick() {
        let now = Instant::now();
        let result = WheelBuilder::default()
            .tick_duration(Duration::ZERO)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "tick_duration must be non-zero");
    }

    #[test]
    fn invalid_config_tick_too_large() {
        let now = Instant::now();
        // as_nanos() would exceed u64::MAX (~584 years), which would truncate on
        // the cast to u64 — must be rejected, not silently narrowed (a nonzero
        // multiple of 2^64 would truncate to 0 → divide-by-zero in build()).
        let result = WheelBuilder::default()
            .tick_duration(Duration::from_secs(20_000_000_000))
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "tick_duration must fit in u64 nanoseconds");
    }

    #[test]
    fn invalid_config_shift_overflow() {
        let now = Instant::now();
        // 8 levels × clk_shift=8 = 56 bits shift on level 7
        // Plus 64 slots (6 bits) = 62 bits, should be OK
        // But 8 levels × clk_shift=9 = 63 + 6 = 69 bits — overflow
        let result = WheelBuilder::default()
            .num_levels(8)
            .clk_shift(9)
            .unbounded(1024)
            .build::<u64>(now);
        assert_invalid(&result, "overflow");
    }

    #[test]
    fn invalid_config_rebalance_progress() {
        let now = Instant::now();
        // slots_per_level = 4 (2^2), clk_shift = 3 → 2^3 = 8 >= 4, so a not-due
        // entry could rebalance to the *same* level and poll would live-lock.
        // Must be rejected at build time.
        let result = WheelBuilder::default()
            .slots_per_level(4)
            .clk_shift(3)
            .num_levels(2)
            .unbounded(64)
            .build::<u64>(now);
        assert_invalid(&result, "strictly finer level");
    }

    // -------------------------------------------------------------------------
    // Rebalance tests (#668)
    // -------------------------------------------------------------------------

    #[test]
    fn rebalanced_entry_fires_at_its_deadline() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = WheelBuilder::default().unbounded(256).build(now).unwrap();

        // Both deadlines land in the same level-2 slot (46): 3000>>6 == 3005>>6.
        // At now=3000 the slot's min (3000) is due, so the slot is walked: 3000
        // is collected, and 3005 (not yet due) is rebalanced to a finer level
        // rather than being re-walked. It must still fire at its exact deadline.
        wheel.schedule_forget(now + ms(3000), 1);
        wheel.schedule_forget(now + ms(3005), 2);

        let mut buf = Vec::new();
        wheel.poll_and_rebalance(now + ms(3000), &mut buf);
        assert_eq!(buf, vec![1], "3000 collected, 3005 rebalanced");

        buf.clear();
        wheel.poll_and_rebalance(now + ms(3005), &mut buf);
        assert_eq!(buf, vec![2], "rebalanced entry fires at its exact deadline");
        assert!(wheel.is_empty());
    }

    #[test]
    fn cancel_after_rebalance() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = WheelBuilder::default().unbounded(256).build(now).unwrap();

        wheel.schedule_forget(now + ms(3000), 1);
        let h = wheel.schedule(now + ms(3005), 2); // rebalanced on the 3000 poll

        let mut buf = Vec::new();
        wheel.poll_and_rebalance(now + ms(3000), &mut buf);
        assert_eq!(buf, vec![1]);
        assert_eq!(wheel.len(), 1, "rebalanced entry still live");

        // cancel must find the entry at its new (finer) location and return it.
        assert_eq!(wheel.cancel(h), Some(2));
        assert_eq!(wheel.len(), 0);
    }

    #[test]
    fn bounded_rebalance_still_fires_everything_on_time() {
        let now = Instant::now();
        // Cap = 1 rebalance per poll — a herd of not-yet-due entries in one
        // coarse slot drains over many polls instead of all at once, but every
        // timer must still fire at its exact deadline.
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .max_rebalances_per_poll(1)
            .unbounded(256)
            .build(now)
            .unwrap();

        // 20 deadlines spread across one level-2 slot (all map to slot 46).
        let mut expected: Vec<u64> = Vec::new();
        for i in 0..20u64 {
            let d = 2950 + i * 2; // 2950, 2952, ... 2988 — all in level-2 slot 46
            wheel.schedule_forget(now + ms(d), d);
            expected.push(d);
        }

        let mut fired: Vec<u64> = Vec::new();
        let mut buf = Vec::new();
        for t in 0..=3000u64 {
            buf.clear();
            wheel.poll_and_rebalance(now + ms(t), &mut buf);
            for &v in &buf {
                assert!(v <= t, "timer {v} fired early at {t}");
                fired.push(v);
            }
        }
        fired.sort_unstable();
        assert_eq!(fired, expected, "every timer fires exactly once, on time");
        assert!(wheel.is_empty());
    }

    #[test]
    fn rebalance_cap_zero_is_collect_only() {
        let now = Instant::now();
        // Cap = 0: no rebalancing at all — entries never move levels and fire
        // from wherever they were placed (pure drip-fire). Must still be correct.
        let mut wheel: Wheel<u64> = WheelBuilder::default()
            .max_rebalances_per_poll(0)
            .unbounded(256)
            .build(now)
            .unwrap();

        wheel.schedule_forget(now + ms(3000), 1);
        wheel.schedule_forget(now + ms(3005), 2); // would rebalance if the cap allowed

        let mut buf = Vec::new();
        wheel.poll_and_rebalance(now + ms(3000), &mut buf);
        assert_eq!(buf, vec![1]); // 3000 collected; 3005 left in its coarse slot
        buf.clear();
        wheel.poll_and_rebalance(now + ms(3005), &mut buf);
        assert_eq!(buf, vec![2]); // fires on time from its original slot
        assert!(wheel.is_empty());
    }

    #[test]
    fn proactive_rebalance_moves_and_preserves_firing() {
        let now = Instant::now();
        let mut wheel: Wheel<u64> = WheelBuilder::default().unbounded(256).build(now).unwrap();

        // 10 deadlines at level 2 (delta ~3000 ∈ [512, 4096)).
        let mut expected = Vec::new();
        for i in 0..10u64 {
            let d = 3000 + i * 4;
            wheel.schedule_forget(now + ms(d), d);
            expected.push(d);
        }

        // Far from the deadlines, nothing is within a finer level's reach.
        assert_eq!(
            wheel.rebalance(now, usize::MAX),
            0,
            "nothing to pull down yet"
        );

        // Drive the timeline with proactive rebalance + collect-only poll. Every
        // timer must still fire exactly once, on time — and rebalance must have
        // actually pulled entries down as they approached.
        let mut fired = Vec::new();
        let mut buf = Vec::new();
        let mut total_moved = 0;
        for t in 0..=3040u64 {
            total_moved += wheel.rebalance(now + ms(t), usize::MAX);
            buf.clear();
            wheel.poll(now + ms(t), &mut buf);
            for &v in &buf {
                assert!(v <= t, "timer {v} fired early at {t}");
                fired.push(v);
            }
        }
        assert!(
            total_moved > 0,
            "rebalance pulled entries down as they neared"
        );
        fired.sort_unstable();
        assert_eq!(fired, expected, "every timer fires once, on time");
        assert!(wheel.is_empty());
    }

    // -------------------------------------------------------------------------
    // Miri-compatible tests (L12)
    // -------------------------------------------------------------------------
    // These tests exercise the raw pointer paths (DLL operations, entry
    // lifecycle, poll) with Drop types to catch UB under Miri.

    #[test]
    fn miri_schedule_cancel_drop_type() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        let h = wheel.schedule(now + ms(50), "hello".to_string());
        let val = wheel.cancel(h);
        assert_eq!(val, Some("hello".to_string()));
        assert!(wheel.is_empty());
    }

    #[test]
    fn miri_poll_fires_drop_type() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        wheel.schedule_forget(now + ms(10), "a".to_string());
        wheel.schedule_forget(now + ms(10), "b".to_string());
        wheel.schedule_forget(now + ms(10), "c".to_string());

        let mut buf = Vec::new();
        let fired = wheel.poll(now + ms(20), &mut buf);
        assert_eq!(fired, 3);
        assert_eq!(buf.len(), 3);
        assert!(wheel.is_empty());
    }

    #[test]
    fn miri_cancel_zombie_drop_type() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        let h = wheel.schedule(now + ms(10), "zombie".to_string());

        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);
        assert_eq!(buf, vec!["zombie".to_string()]);

        // h is now a zombie — cancel frees the entry
        let val = wheel.cancel(h);
        assert_eq!(val, None);
    }

    #[test]
    fn miri_free_active_and_zombie() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        // Active → fire-and-forget via free
        let h1 = wheel.schedule(now + ms(10), "active".to_string());
        wheel.free(h1);

        // Poll fires the fire-and-forget entry
        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);
        assert_eq!(buf, vec!["active".to_string()]);

        // Zombie → free
        let h2 = wheel.schedule(now + ms(10), "will-fire".to_string());
        buf.clear();
        wheel.poll(now + ms(20), &mut buf);
        wheel.free(h2); // zombie cleanup
    }

    #[test]
    fn miri_reschedule_drop_type() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        let h = wheel.schedule(now + ms(100), "moveme".to_string());
        let h = wheel.reschedule(h, now + ms(50));

        let mut buf = Vec::new();
        wheel.poll(now + ms(55), &mut buf);
        assert_eq!(buf, vec!["moveme".to_string()]);

        wheel.cancel(h);
    }

    #[test]
    fn miri_dll_multi_entry_same_slot() {
        // Multiple entries in same slot exercises DLL push/remove paths
        let now = Instant::now();
        let mut wheel: Wheel<Vec<u8>> = Wheel::unbounded(64, now);

        let mut handles = Vec::new();
        for i in 0..5 {
            handles.push(wheel.schedule(now + ms(10), vec![i; 32]));
        }

        // Cancel middle, then head, then tail
        let v2 = wheel.cancel(handles.remove(2));
        assert_eq!(v2.unwrap(), vec![2; 32]);

        let v0 = wheel.cancel(handles.remove(0));
        assert_eq!(v0.unwrap(), vec![0; 32]);

        // Poll remaining
        let mut buf = Vec::new();
        wheel.poll(now + ms(20), &mut buf);
        assert_eq!(buf.len(), 3);

        // Clean up zombie handles
        for h in handles {
            wheel.cancel(h);
        }
    }

    #[test]
    fn miri_drop_wheel_with_entries() {
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        // Schedule entries across multiple levels
        for i in 0..20 {
            wheel.schedule_forget(now + ms(i * 100), format!("entry-{i}"));
        }
        assert_eq!(wheel.len(), 20);

        // Drop with active entries — must not leak or UB
        drop(wheel);
    }

    #[test]
    fn miri_bounded_lifecycle() {
        let now = Instant::now();
        let mut wheel: BoundedWheel<String> = BoundedWheel::bounded(4, now);

        let h1 = wheel.try_schedule(now + ms(10), "a".to_string()).unwrap();
        let h2 = wheel.try_schedule(now + ms(20), "b".to_string()).unwrap();
        let h3 = wheel.try_schedule(now + ms(30), "c".to_string()).unwrap();
        let h4 = wheel.try_schedule(now + ms(40), "d".to_string()).unwrap();

        // Full
        let err = wheel.try_schedule(now + ms(50), "e".to_string());
        assert!(err.is_err());

        // Cancel and reuse
        wheel.cancel(h1);
        let h5 = wheel.try_schedule(now + ms(50), "e".to_string()).unwrap();

        // Poll fires some
        let mut buf = Vec::new();
        wheel.poll(now + ms(25), &mut buf);

        // Clean up all remaining handles
        wheel.cancel(h2);
        wheel.free(h3);
        wheel.free(h4);
        wheel.free(h5);
    }

    #[test]
    fn miri_rebalance_relocate_drop_type() {
        // Exercises the rebalance relocate path (insert_entry called while this
        // slot's `&WheelSlot` is held) with a Drop type, to catch any aliasing
        // UB in that hot-path borrow. Must use poll_and_rebalance — plain poll
        // never relocates, so it would not exercise the path.
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);

        // Same level-2 slot: 3000>>6 == 3005>>6. At now=3000 the "collected"
        // entry fires and the "rebalanced" entry relocates to a finer level.
        wheel.schedule_forget(now + ms(3000), "collected".to_string());
        wheel.schedule_forget(now + ms(3005), "rebalanced".to_string());

        let mut buf = Vec::new();
        wheel.poll_and_rebalance(now + ms(3000), &mut buf);
        assert_eq!(buf, vec!["collected".to_string()]);

        buf.clear();
        wheel.poll_and_rebalance(now + ms(3005), &mut buf);
        assert_eq!(buf, vec!["rebalanced".to_string()]);
        assert!(wheel.is_empty());
    }

    #[test]
    fn miri_rebalance_method_drop_type() {
        // Standalone rebalance() uses the same insert_entry-while-slot-borrowed
        // pattern as poll_and_rebalance; exercise it with a Drop type.
        let now = Instant::now();
        let mut wheel: Wheel<String> = Wheel::unbounded(64, now);
        wheel.schedule_forget(now + ms(3000), "a".to_string());
        wheel.schedule_forget(now + ms(3004), "b".to_string());

        // Advance so both are within a finer level's reach, then rebalance.
        let moved = wheel.rebalance(now + ms(2960), usize::MAX);
        assert!(moved >= 1);

        let mut buf = Vec::new();
        wheel.poll(now + ms(3004), &mut buf);
        buf.sort();
        assert_eq!(buf, vec!["a".to_string(), "b".to_string()]);
        assert!(wheel.is_empty());
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;
    use std::collections::HashSet;
    use std::mem;
    use std::time::{Duration, Instant};

    /// Operation in a schedule/cancel interleaving.
    #[derive(Debug, Clone)]
    enum Op {
        /// Schedule a timer at `deadline_ms` milliseconds from epoch.
        Schedule { deadline_ms: u64 },
        /// Cancel the timer at the given index (modulo outstanding handles).
        Cancel { idx: usize },
    }

    fn op_strategy() -> impl Strategy<Value = Op> {
        prop_oneof![
            // Schedule with deadlines from 1ms to 10_000ms
            (1u64..10_000).prop_map(|deadline_ms| Op::Schedule { deadline_ms }),
            // Cancel at random index
            any::<usize>().prop_map(|idx| Op::Cancel { idx }),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(500))]

        /// Fuzz schedule/cancel interleaving.
        ///
        /// Random sequence of schedule and cancel operations. Invariants:
        /// - `len` always matches outstanding active timers
        /// - cancel on active handle returns `Some`
        /// - poll collects all un-cancelled values
        #[test]
        fn fuzz_schedule_cancel_interleaving(ops in proptest::collection::vec(op_strategy(), 1..200)) {
            let now = Instant::now();
            let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

            let mut handles: Vec<TimerHandle<u64>> = Vec::new();
            let mut active_values: HashSet<u64> = HashSet::new();
            let mut next_id: u64 = 0;

            for op in &ops {
                match op {
                    Op::Schedule { deadline_ms } => {
                        let id = next_id;
                        next_id += 1;
                        let h = wheel.schedule(now + Duration::from_millis(*deadline_ms), id);
                        handles.push(h);
                        active_values.insert(id);
                    }
                    Op::Cancel { idx } => {
                        if !handles.is_empty() {
                            let i = idx % handles.len();
                            let h = handles.swap_remove(i);
                            let val = wheel.cancel(h);
                            // Value should be Some (all handles are for active timers)
                            let v = val.unwrap();
                            assert!(active_values.remove(&v));
                        }
                    }
                }
                // len must match active values
                prop_assert_eq!(wheel.len(), active_values.len());
            }

            // Poll everything — should collect exactly the remaining active values
            let mut buf = Vec::new();
            // Use a far-future time to fire everything
            wheel.poll(now + Duration::from_secs(100_000), &mut buf);

            // Clean up zombie handles (poll fired them, handles still exist)
            for h in handles {
                mem::forget(h);
            }

            let fired_set: HashSet<u64> = buf.into_iter().collect();
            prop_assert_eq!(fired_set, active_values);
            prop_assert!(wheel.is_empty());
        }

        /// Fuzz poll timing.
        ///
        /// Schedule N timers with random deadlines. Poll at random increasing
        /// times. Assert every timer fires exactly once, fired deadlines are
        /// all <= poll time, unfired deadlines are all > poll time.
        #[test]
        fn fuzz_poll_timing(
            deadlines in proptest::collection::vec(1u64..5000, 1..100),
            poll_times in proptest::collection::vec(1u64..10_000, 1..20),
        ) {
            let now = Instant::now();
            let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);

            // Schedule all timers (fire-and-forget)
            for (i, &d) in deadlines.iter().enumerate() {
                wheel.schedule_forget(now + Duration::from_millis(d), i as u64);
            }

            // Sort poll times to be monotonically increasing
            let mut sorted_times: Vec<u64> = poll_times;
            sorted_times.sort_unstable();
            sorted_times.dedup();

            let mut all_fired: Vec<u64> = Vec::new();

            for &t in &sorted_times {
                let mut buf = Vec::new();
                wheel.poll(now + Duration::from_millis(t), &mut buf);

                // Every fired entry should have deadline_ms <= t
                for &id in &buf {
                    let deadline_ms = deadlines[id as usize];
                    prop_assert!(deadline_ms <= t,
                        "Timer {} with deadline {}ms fired at {}ms", id, deadline_ms, t);
                }

                all_fired.extend(buf);
            }

            // Fire everything remaining
            let mut final_buf = Vec::new();
            wheel.poll(now + Duration::from_secs(100_000), &mut final_buf);
            all_fired.extend(final_buf);

            // Every timer should have fired exactly once
            all_fired.sort_unstable();
            let expected: Vec<u64> = (0..deadlines.len() as u64).collect();
            prop_assert_eq!(all_fired, expected, "Not all timers fired exactly once");
            prop_assert!(wheel.is_empty());
        }

        /// Fuzz next_deadline cache correctness.
        ///
        /// Random sequence of schedule, schedule_forget, cancel, reschedule,
        /// and poll operations. After each operation, verifies the cached
        /// `next_deadline()` matches the uncached full walk.
        #[test]
        fn fuzz_next_deadline_cache(
            ops in proptest::collection::vec(deadline_op_strategy(), 1..300),
        ) {
            let now = Instant::now();
            let mut wheel: Wheel<u64> = Wheel::unbounded(1024, now);
            let mut handles: Vec<(TimerHandle<u64>, u64)> = Vec::new();
            let mut next_id: u64 = 0;

            for op in &ops {
                match op {
                    DeadlineOp::Schedule { deadline_ms } => {
                        let h = wheel.schedule(now + Duration::from_millis(*deadline_ms), next_id);
                        handles.push((h, *deadline_ms));
                        next_id += 1;
                    }
                    DeadlineOp::ScheduleForget { deadline_ms } => {
                        wheel.schedule_forget(now + Duration::from_millis(*deadline_ms), next_id);
                        next_id += 1;
                    }
                    DeadlineOp::Cancel { idx } => {
                        if !handles.is_empty() {
                            let i = idx % handles.len();
                            let (h, _) = handles.swap_remove(i);
                            wheel.cancel(h);
                        }
                    }
                    DeadlineOp::Reschedule { idx, new_deadline_ms } => {
                        if !handles.is_empty() {
                            let i = idx % handles.len();
                            let (h, _) = handles.swap_remove(i);
                            let new_h = wheel.reschedule(h, now + Duration::from_millis(*new_deadline_ms));
                            handles.push((new_h, *new_deadline_ms));
                        }
                    }
                    DeadlineOp::Poll { at_ms } => {
                        let mut buf = Vec::new();
                        wheel.poll(now + Duration::from_millis(*at_ms), &mut buf);
                        // Free zombie handles whose timers just fired.
                        // A handle is a zombie if its deadline_ms <= at_ms.
                        let at = *at_ms;
                        let mut i = 0;
                        while i < handles.len() {
                            if handles[i].1 <= at {
                                let (h, _) = handles.swap_remove(i);
                                wheel.free(h);
                            } else {
                                i += 1;
                            }
                        }
                    }
                }

                // Contract: `next_deadline()` is a LOWER BOUND — the per-slot
                // minima are stale-low after removal, so it may report earlier
                // than the true next fire, never later. Assert it never exceeds
                // the exact minimum, and that emptiness agrees.
                let cached = wheel.next_deadline();
                let exact = wheel.next_deadline_uncached();
                prop_assert_eq!(
                    cached.is_none(),
                    exact.is_none(),
                    "emptiness disagrees after {:?}",
                    op
                );
                if let (Some(c), Some(e)) = (cached, exact) {
                    prop_assert!(
                        c <= e,
                        "next_deadline {:?} exceeded exact {:?} after {:?}",
                        c,
                        e,
                        op
                    );
                }
            }

            for (h, _) in handles {
                mem::forget(h);
            }
        }
    }

    #[derive(Debug, Clone)]
    enum DeadlineOp {
        Schedule { deadline_ms: u64 },
        ScheduleForget { deadline_ms: u64 },
        Cancel { idx: usize },
        Reschedule { idx: usize, new_deadline_ms: u64 },
        Poll { at_ms: u64 },
    }

    fn deadline_op_strategy() -> impl Strategy<Value = DeadlineOp> {
        prop_oneof![
            (1u64..10_000).prop_map(|deadline_ms| DeadlineOp::Schedule { deadline_ms }),
            (1u64..10_000).prop_map(|deadline_ms| DeadlineOp::ScheduleForget { deadline_ms }),
            any::<usize>().prop_map(|idx| DeadlineOp::Cancel { idx }),
            (any::<usize>(), 1u64..10_000).prop_map(|(idx, new_deadline_ms)| {
                DeadlineOp::Reschedule {
                    idx,
                    new_deadline_ms,
                }
            }),
            (1u64..10_000).prop_map(|at_ms| DeadlineOp::Poll { at_ms }),
        ]
    }
}