Skip to main content

ntex_rt/time/
mod.rs

1//! Hierarchical timer wheel backing ntex timers.
2//!
3//! [`TimerHandle`] and [`CallbackHandle`] register timers with the wheel of
4//! the current thread, the timer futures of `ntex-util` are built on top of
5//! them.
6//!
7//! The design follows the Linux kernel timer wheel (`kernel/time/timer.c`).
8//!
9//! # Clock
10//!
11//! The wheel counts time in *units* of `1 << units` milliseconds. The unit
12//! is 16 milliseconds by default, see
13//! [`Builder::timer_resolution`](crate::Builder::timer_resolution). Each
14//! thread reads the resolution of its system when the first timer is armed
15//! and keeps it until the wheel is stopped. The wheel clock `elapsed` is the
16//! unit of the last processed expiry, and `elapsed_time` is the [`Instant`]
17//! that corresponds to it. Timer deadlines are converted to units relative to
18//! this pair.
19//!
20//! # Levels
21//!
22//! The wheel has `LVL_DEPTH` (8) levels of `LVL_SIZE` (64) buckets. Each level
23//! is 8 times coarser than the previous one, a timer is placed on the first
24//! level that can represent its delay. With the default 16 ms unit:
25//!
26//! | Level | Granularity | Range            |
27//! |-------|-------------|------------------|
28//! | 0     | 16 ms       | 0 .. ~1 s        |
29//! | 1     | 128 ms      | ~1 s .. ~8 s     |
30//! | 2     | ~1 s        | ~8 s .. ~64 s    |
31//! | 3     | ~8 s        | ~64 s .. ~8.6 m  |
32//! | 4     | ~65 s       | ~8.6 m .. ~69 m  |
33//! | 5     | ~8.7 m      | ~69 m .. ~9.2 h  |
34//! | 6     | ~70 m       | ~9.2 h .. ~3 d   |
35//! | 7     | ~9.3 h      | ~3 d .. ~24.5 d  |
36//!
37//! A smaller unit scales the granularity and the range of every level by the
38//! same factor, with a 2 ms unit level 0 covers ~126 ms and the wheel ~3 d.
39//!
40//! Longer delays are clamped to the capacity of the wheel. The expiry is
41//! rounded up to the granularity of the level and the delay is measured from
42//! [`Instant::now()`], so a timer never fires early but may fire up to one
43//! granularity late. Timers are not cascaded to finer
44//! levels, which keeps insertion and removal `O(1)`.
45//!
46//! A bitmap per level tracks occupied buckets, the next expiry is found by
47//! scanning the bitmaps instead of the buckets.
48//!
49//! # Native runtime
50//!
51//! Each native [`Runtime`] owns a wheel. `Runtime::poll`
52//! expires due buckets before running tasks and reports the time until the
53//! next occupied bucket in `PollResult::Pending`, so the driver waits for
54//! I/O and timers in a single call. No driver tasks are spawned. The cached
55//! [`system_time()`] is refreshed when it is older than 150 milliseconds.
56//! The resolution is read from the current system when the first timer is
57//! armed, or set with `RuntimeBuilder::timer_resolution`.
58//!
59//! Handles carry the id of their wheel. A handle used outside the runtime
60//! that created it, or after that runtime is dropped, is stale: it reports
61//! elapsed, and reset and drop do nothing. Dropping the runtime stops its
62//! wheel and wakes all pending timers.
63//!
64//! # Drivers
65//!
66//! With the `tokio` and `compio` runtimes the wheel is per thread and two
67//! tasks are spawned lazily on the current thread:
68//!
69//! * `TimerDriver` sleeps until the next occupied bucket expires and wakes
70//!   the timers stored in it. The clock advances to the scheduled time of the
71//!   bucket, not to the time the driver woke up, so a late wakeup does not
72//!   delay later timers. Buckets that are overdue are processed at once.
73//!   Wakers are invoked in place while the wheel is held; timer operations
74//!   are not reentrant. Callback timers are queued separately and invoked
75//!   after releasing the wheel.
76//! * `LowresTimerDriver` invalidates the cached [`system_time()`] value
77//!   every 150 milliseconds.
78//!
79//! A native runtime expires its timers when it polls and needs no driver
80//! task. Otherwise the driver tasks sleep with the Tokio timer on the `tokio`
81//! runtime, so the Tokio runtime must have timers enabled, with the compio
82//! timer on `compio`, and with `futures-timer` without either feature.
83//!
84//! Dropping the timer driver, i.e. when the runtime stops, stops the wheel and
85//! marks all timers as elapsed. Dropping the lowres driver invalidates the
86//! cached system time.
87//!
88//! A runtime does not always drop its pending tasks when it stops, the timer
89//! is also reset once the arbiter storage of the stopped system is cleared,
90//! so that the next runtime on the thread starts its own drivers. Drivers of
91//! an older generation exit without touching the state.
92//!
93//! Registrations retain owned [`crate::LocalWaker`] handles, specializing
94//! native owner-thread wakes without allocating wrappers or growing entries.
95//! Standard wakers are still accepted at polling boundaries.
96#![allow(
97    clippy::cast_possible_truncation,
98    clippy::cast_sign_loss,
99    clippy::cast_possible_wrap
100)]
101use std::sync::atomic::{AtomicU32, Ordering};
102use std::time::{Duration, Instant, SystemTime};
103use std::{cell::Cell, cmp, fmt, mem, rc::Rc, task, task::Poll};
104use std::{marker::PhantomData, num::NonZeroU64};
105
106use slab::Slab;
107
108use crate::rt::Runtime;
109
110mod callbacks;
111mod driver;
112
113pub use self::callbacks::CallbackHandle;
114use self::callbacks::{CallbackTicket, Callbacks};
115use self::driver::{LowresTimerDriver, TimerDriver};
116
117/// Default resolution of the wheel clock, a unit is `1 << units` milliseconds.
118const DEFAULT_UNITS: u8 = 4;
119
120/// Each level is `LVL_CLK_DIV` times coarser than the previous one.
121const LVL_CLK_SHIFT: u64 = 3;
122const LVL_CLK_DIV: u64 = 1 << LVL_CLK_SHIFT;
123const LVL_CLK_MASK: u64 = LVL_CLK_DIV - 1;
124
125/// Number of buckets per level.
126const LVL_BITS: u64 = 6;
127const LVL_SIZE: u64 = 1 << LVL_BITS;
128const LVL_MASK: u64 = LVL_SIZE - 1;
129
130/// Number of levels.
131const LVL_DEPTH: u64 = 8;
132
133/// Total number of buckets.
134const WHEEL_SIZE: usize = (LVL_SIZE * LVL_DEPTH) as usize;
135
136/// Delays at or above the cutoff are clamped to `WHEEL_TIMEOUT_MAX`.
137const WHEEL_TIMEOUT_CUTOFF: u64 = lvl_start(LVL_DEPTH);
138const WHEEL_TIMEOUT_MAX: u64 = WHEEL_TIMEOUT_CUTOFF - lvl_gran(LVL_DEPTH - 1);
139
140/// Refresh interval of the cached time.
141const LOWRES_RESOLUTION: Duration = Duration::from_millis(150);
142
143/// Shift of the level clock relative to the wheel clock.
144const fn lvl_shift(lvl: u64) -> u64 {
145    lvl * LVL_CLK_SHIFT
146}
147
148/// Granularity of a level in units.
149const fn lvl_gran(lvl: u64) -> u64 {
150    1 << lvl_shift(lvl)
151}
152
153/// Smallest delay in units that is stored on level `lvl`, `lvl` must be at
154/// least 1.
155const fn lvl_start(lvl: u64) -> u64 {
156    (LVL_SIZE - 1) << ((lvl - 1) * LVL_CLK_SHIFT)
157}
158
159const fn to_units(millis: u64, units: u8) -> u64 {
160    millis >> units
161}
162
163const fn to_millis(val: u64, units: u8) -> u64 {
164    val << units
165}
166
167/// Resolution of the current system, `DEFAULT_UNITS` without a system.
168fn system_units() -> u8 {
169    crate::System::try_current().map_or(DEFAULT_UNITS, |sys| {
170        sys.timer_resolution().trailing_zeros() as u8
171    })
172}
173
174const fn as_millis(dur: Duration) -> u64 {
175    dur.as_secs() * 1_000 + (dur.subsec_millis() as u64)
176}
177
178/// Returns a cached approximation of the current system time.
179///
180/// The cached value is refreshed at roughly 150 millisecond intervals.
181#[inline]
182pub fn system_time() -> SystemTime {
183    if Runtime::has_current() {
184        Runtime::with_current(|rt| rt.timer.native_system_time(rt.now()))
185    } else {
186        TIMER.with(Timer::system_time)
187    }
188}
189
190/// Calls `f` with the wheel of the current native runtime, or with the
191/// thread-local wheel outside of a native runtime.
192fn with_timer<R>(f: impl FnOnce(&Rc<Timer>) -> R) -> R {
193    if Runtime::has_current() {
194        Runtime::with_current(|rt| f(&rt.timer))
195    } else {
196        TIMER.with(f)
197    }
198}
199
200/// Calls `f` with the wheel that issued `hnd` and the slot of the handle.
201///
202/// Returns `None` for a stale handle, whose wheel is not reachable from the
203/// current context, for example after its runtime has been dropped.
204fn with_slot<R>(hnd: NonZeroU64, f: impl FnOnce(&Rc<Timer>, usize) -> R) -> Option<R> {
205    let mut f = Some(f);
206    if Runtime::has_current()
207        && let Some(res) = Runtime::with_current(|rt| {
208            rt.timer
209                .slot(hnd)
210                .map(|slot| (f.take().unwrap())(&rt.timer, slot))
211        })
212    {
213        return Some(res);
214    }
215    // the wheel is already destroyed if the handle is dropped by another
216    // thread-local destructor
217    TIMER
218        .try_with(|t| t.slot(hnd).map(|slot| (f.take().unwrap())(t, slot)))
219        .ok()
220        .flatten()
221}
222
223#[derive(Debug)]
224/// Handle to a timer registered with ntex's local timer wheel.
225///
226/// Dropping the handle cancels the timer. A handle may be reset and reused
227/// after it has elapsed.
228///
229/// Timer operations are not reentrant. Registered wakers must not synchronously
230/// access the timer wheel when cloned, woken or dropped.
231///
232/// The handle refers to a slot in the current thread's wheel, so it is neither
233/// `Send` nor `Sync`, and neither are the timer futures that hold it. To run a
234/// timer on another thread, send a future that creates it there instead of
235/// one that already holds it.
236///
237/// Inside a native [`Runtime`] the timer is registered
238/// with the wheel of that runtime. Once the runtime is dropped, or while it
239/// is not active on the thread, the handle is stale: it reports the timer as
240/// elapsed and ignores other operations.
241pub struct TimerHandle(NonZeroU64, PhantomData<*const ()>);
242
243impl TimerHandle {
244    /// Registers a timer that elapses after `millis`.
245    pub fn new(millis: u64) -> Self {
246        with_timer(|t| t.add_timer(millis))
247    }
248
249    /// Restarts the timer with a new delay in milliseconds.
250    pub fn reset(&self, millis: u64) {
251        with_slot(self.0, |t, slot| t.update_timer(slot, millis));
252    }
253
254    /// Restarts the timer and returns the instant the wheel expires it.
255    ///
256    /// The wheel rounds the expiry up to its granularity, so the deadline is
257    /// at least `millis` from now. Returns `None` for a stale handle.
258    pub(crate) fn reset_deadline(&self, millis: u64) -> Option<Instant> {
259        with_slot(self.0, |t, slot| t.update_timer(slot, millis))
260    }
261
262    /// Completes the timer immediately and wakes its registered task.
263    pub fn elapse(&self) {
264        with_slot(self.0, |t, slot| t.remove_timer(slot));
265    }
266
267    /// Returns `true` if this timer has elapsed.
268    pub fn is_elapsed(&self) -> bool {
269        with_slot(self.0, |t, slot| {
270            t.with_wheel(|w| w.timers[slot].bucket.is_none())
271        })
272        .unwrap_or(true)
273    }
274
275    /// Polls until this timer has elapsed.
276    ///
277    /// The timer stores one waker: a pending poll replaces the previously
278    /// registered one, so only the most recent waiter is woken.
279    pub fn poll_elapsed(&self, cx: &mut task::Context<'_>) -> Poll<()> {
280        with_slot(self.0, |t, slot| {
281            t.with_wheel(|w| {
282                let entry = &mut w.timers[slot];
283                if entry.bucket.is_none() {
284                    Poll::Ready(())
285                } else {
286                    if entry.task.as_ref().is_none_or(|w| !w.will_wake(cx.waker())) {
287                        entry.task = Some(crate::LocalWaker::from_waker(cx.waker()));
288                    }
289                    Poll::Pending
290                }
291            })
292        })
293        .unwrap_or(Poll::Ready(()))
294    }
295}
296
297impl Drop for TimerHandle {
298    fn drop(&mut self) {
299        with_slot(self.0, |t, slot| {
300            t.with_wheel(|w| {
301                w.unlink(slot);
302                w.timers.remove(slot);
303            });
304        });
305    }
306}
307
308/// Waker slot of a driver task.
309#[derive(Default)]
310struct DriverWaker(Cell<Option<crate::LocalWaker>>);
311
312impl DriverWaker {
313    fn register(&self, waker: &task::Waker) {
314        let prev = self.0.take();
315        let same = prev.as_ref().is_some_and(|prev| prev.will_wake(waker));
316        self.0.set(prev);
317        if !same {
318            // Keep the old registration until cloning succeeds, then publish
319            // before dropping it, waker callbacks may reenter the slot.
320            let next = crate::LocalWaker::from_waker(waker);
321            drop(self.0.replace(Some(next)));
322        }
323    }
324
325    fn wake(&self) {
326        if let Some(waker) = self.0.take() {
327            waker.wake();
328        }
329    }
330
331    fn take_local(&self) -> Option<crate::LocalWaker> {
332        self.0.take()
333    }
334
335    #[cfg(test)]
336    fn is_set(&self) -> bool {
337        let waker = self.0.take();
338        let set = waker.is_some();
339        self.0.set(waker);
340        set
341    }
342}
343
344bitflags::bitflags! {
345    #[derive(Copy, Clone, Debug, Eq, PartialEq)]
346    struct Flags: u8 {
347        /// The timer driver task is spawned.
348        const DRIVER_STARTED = 0b0000_0001;
349        /// The cached time is populated and its refresh sleep is armed.
350        const LOWRES_TIMER   = 0b0000_1000;
351        /// The lowres driver task is spawned.
352        const LOWRES_DRIVER  = 0b0001_0000;
353        /// A timer was scheduled, `system_time()` caches the time.
354        const RUNNING        = 0b0010_0000;
355        /// The wheel belongs to a native runtime, which expires its timers
356        /// in `Runtime::poll`, no driver tasks are spawned.
357        const NATIVE         = 0b0100_0000;
358    }
359}
360
361/// Last issued wheel id, ids identify the wheel that issued a handle.
362static NEXT_ID: AtomicU32 = AtomicU32::new(0);
363
364thread_local! {
365    static TIMER: Rc<Timer> = Rc::new(Timer::new(None));
366}
367
368/// Timer state shared by the timer handles and the driver tasks, per thread
369/// or per native runtime.
370pub(crate) struct Timer {
371    /// Wheel id, the upper half of every handle.
372    id: u32,
373    /// Resolution of the wheel clock, overrides the system resolution.
374    resolution: Option<u8>,
375    /// Wheel clock in units, the expiry that was processed last.
376    elapsed: Cell<u64>,
377    /// Instant that corresponds to `elapsed`, the scheduled time of the last
378    /// processed expiry. Set lazily when the wheel is idle.
379    elapsed_time: Cell<Option<Instant>>,
380    /// Expiry of the earliest occupied bucket, `u64::MAX` if the wheel is empty.
381    next_expiry: Cell<u64>,
382    flags: Cell<Flags>,
383    /// Incremented on reset, drivers of an older generation are stale.
384    generation: Cell<u64>,
385    /// Resolution of the wheel clock, a unit is `1 << units` milliseconds.
386    /// Read from the current system when the first timer is armed, `None`
387    /// while the wheel is stopped.
388    units: Cell<Option<u8>>,
389    driver: DriverWaker,
390    lowres_stime: Cell<Option<SystemTime>>,
391    /// Instant the cached time of a native runtime was taken at.
392    lowres_stamp: Cell<Option<Instant>>,
393    lowres_driver: DriverWaker,
394    /// Taken out of the cell for the duration of an operation.
395    wheel: Cell<Option<Box<Wheel>>>,
396}
397
398impl fmt::Debug for Timer {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        f.debug_struct("Timer")
401            .field("id", &self.id)
402            .finish_non_exhaustive()
403    }
404}
405
406/// Outcome of expiring the due buckets.
407pub(super) enum Processed {
408    /// The wheel is empty.
409    Idle,
410    /// The next bucket is due at the instant.
411    Next(Instant),
412    /// A callback stopped the wheel generation that was processed.
413    Stopped,
414}
415
416/// Timer storage.
417struct Wheel {
418    /// Timer entries indexed by handle, slot 0 is reserved so handles are
419    /// non-zero.
420    timers: Slab<TimerEntry>,
421    /// Handles of the timers stored in each bucket, `lvl * LVL_SIZE + offset`.
422    buckets: Box<[Slab<usize>]>,
423    /// Occupied buckets of each level, bit `n` is set if bucket `n` has timers.
424    occupied: [u64; LVL_DEPTH as usize],
425    /// Allocated only for callbacks, keeping ordinary entries waker-sized.
426    callbacks: Option<Box<Callbacks>>,
427}
428
429struct WheelGuard<'a> {
430    slot: &'a Cell<Option<Box<Wheel>>>,
431    wheel: Option<Box<Wheel>>,
432}
433
434impl Drop for WheelGuard<'_> {
435    fn drop(&mut self) {
436        self.slot.set(self.wheel.take());
437    }
438}
439
440#[derive(Debug)]
441struct TimerEntry {
442    /// Bucket index, `None` once the timer has elapsed.
443    bucket: Option<u16>,
444    /// Key of the entry in the bucket.
445    bucket_entry: usize,
446    callback: bool,
447    task: Option<crate::LocalWaker>,
448}
449
450#[cfg(target_pointer_width = "64")]
451const _: () = assert!(mem::size_of::<TimerEntry>() == 32);
452
453struct ExpiredTimers<'a> {
454    timers: &'a mut Slab<TimerEntry>,
455    entries: slab::Drain<'a, usize>,
456}
457
458impl Drop for ExpiredTimers<'_> {
459    fn drop(&mut self) {
460        // A panicking wake must not leave entries pointing into a drained bucket.
461        for no in self.entries.by_ref() {
462            self.timers[no].bucket = None;
463        }
464    }
465}
466
467impl Timer {
468    /// Creates a wheel with a new id, `resolution` overrides the system
469    /// resolution, in units.
470    fn new(resolution: Option<u8>) -> Self {
471        let mut timers = Slab::default();
472        timers.insert(TimerEntry {
473            bucket: None,
474            bucket_entry: 0,
475            callback: false,
476            task: None,
477        });
478
479        // ids are never zero, so handles are non-zero
480        let id = NEXT_ID
481            .fetch_add(1, Ordering::Relaxed)
482            .wrapping_add(1)
483            .max(1);
484
485        Timer {
486            id,
487            resolution,
488            elapsed: Cell::new(0),
489            elapsed_time: Cell::new(None),
490            next_expiry: Cell::new(u64::MAX),
491            flags: Cell::new(Flags::empty()),
492            generation: Cell::new(0),
493            units: Cell::new(None),
494            driver: DriverWaker::default(),
495            lowres_stime: Cell::new(None),
496            lowres_stamp: Cell::new(None),
497            lowres_driver: DriverWaker::default(),
498            wheel: Cell::new(Some(Box::new(Wheel {
499                timers,
500                buckets: (0..WHEEL_SIZE).map(|_| Slab::new()).collect(),
501                occupied: [0; LVL_DEPTH as usize],
502                callbacks: None,
503            }))),
504        }
505    }
506
507    /// Creates the wheel of a native runtime, `resolution_ms` overrides the
508    /// resolution of the system.
509    pub(crate) fn new_native(resolution_ms: Option<u8>) -> Rc<Self> {
510        let timer = Timer::new(resolution_ms.map(|ms| ms.trailing_zeros() as u8));
511        timer.insert_flags(Flags::NATIVE);
512        Rc::new(timer)
513    }
514
515    /// Returns the handle of `slot`.
516    fn handle(&self, slot: usize) -> NonZeroU64 {
517        let slot = u32::try_from(slot).expect("timer slots are exhausted");
518        NonZeroU64::new((u64::from(self.id) << 32) | u64::from(slot)).unwrap()
519    }
520
521    /// Returns the slot of `hnd`, `None` if another wheel issued it.
522    fn slot(&self, hnd: NonZeroU64) -> Option<usize> {
523        let hnd = hnd.get();
524        if (hnd >> 32) as u32 == self.id {
525            Some((hnd & u64::from(u32::MAX)) as usize)
526        } else {
527            None
528        }
529    }
530
531    fn with_wheel<F, R>(&self, f: F) -> R
532    where
533        F: FnOnce(&mut Wheel) -> R,
534    {
535        let mut guard = WheelGuard {
536            slot: &self.wheel,
537            wheel: Some(
538                self.wheel
539                    .take()
540                    .expect("timer wheel operations are not reentrant"),
541            ),
542        };
543        f(guard.wheel.as_deref_mut().unwrap())
544    }
545
546    fn insert_flags(&self, flags: Flags) -> Flags {
547        let mut f = self.flags.get();
548        f.insert(flags);
549        self.flags.set(f);
550        f
551    }
552
553    /// Returns the cached system time, the cache is populated only while the
554    /// wheel is running.
555    fn system_time(self: &Rc<Self>) -> SystemTime {
556        if let Some(cur) = self.lowres_stime.get() {
557            cur
558        } else {
559            let now = SystemTime::now();
560            if self.flags.get().contains(Flags::RUNNING) {
561                self.lowres_stime.set(Some(now));
562                self.refresh_lowres();
563            }
564            now
565        }
566    }
567
568    /// Arms the invalidation of the cached time.
569    fn refresh_lowres(self: &Rc<Self>) {
570        if self.flags.get().contains(Flags::LOWRES_DRIVER) {
571            self.lowres_driver.wake();
572        } else {
573            LowresTimerDriver::start(self);
574        }
575    }
576
577    /// Returns the cached system time of a native runtime, refreshed once it
578    /// is `LOWRES_RESOLUTION` older than `now`.
579    pub(crate) fn native_system_time(&self, now: Instant) -> SystemTime {
580        if let (Some(cur), Some(stamp)) = (self.lowres_stime.get(), self.lowres_stamp.get())
581            && now.saturating_duration_since(stamp) < LOWRES_RESOLUTION
582        {
583            cur
584        } else {
585            let cur = SystemTime::now();
586            self.lowres_stime.set(Some(cur));
587            self.lowres_stamp.set(Some(now));
588            cur
589        }
590    }
591
592    /// Expires the due buckets of a native runtime and runs their callbacks.
593    pub(crate) fn run_due(&self) {
594        if self.next_expiry.get() != u64::MAX {
595            // generation changes only when the runtime is dropped
596            let _ = self.process(Instant::now(), self.generation.get());
597        }
598    }
599
600    /// Returns the instant the next bucket is due, `None` if the wheel is empty.
601    pub(crate) fn next_deadline(&self) -> Option<Instant> {
602        let expiry = self.next_expiry.get();
603        if expiry == u64::MAX {
604            None
605        } else {
606            Some(self.expiry_time(expiry))
607        }
608    }
609
610    /// Elapses all timers without waking their tasks, called when the native
611    /// runtime is dropped.
612    pub(crate) fn shutdown(&self) {
613        self.generation.set(self.generation.get().wrapping_add(1));
614        self.stop_wheel();
615    }
616
617    /// Expires the buckets that are due at `now` and runs their callbacks.
618    ///
619    /// Returns `Stopped` if a callback stopped `generation`.
620    pub(super) fn process(&self, mut now: Instant, generation: u64) -> Processed {
621        loop {
622            let expiry = self.next_expiry.get();
623            if expiry == u64::MAX {
624                return Processed::Idle;
625            }
626
627            let deadline = self.expiry_time(expiry);
628            if deadline > now {
629                return Processed::Next(deadline);
630            }
631
632            if let Some(callbacks) = self.expire(expiry, deadline) {
633                if !self.run_callbacks(callbacks, generation) {
634                    return Processed::Stopped;
635                }
636                now = Instant::now();
637            }
638        }
639    }
640
641    /// Expires the bucket due at `expiry`, waking its tasks.
642    ///
643    /// Returns the callbacks that are ready to run.
644    fn expire(&self, expiry: u64, deadline: Instant) -> Option<Vec<CallbackTicket>> {
645        // Advance the clock to the scheduled time of the bucket, a late
646        // wakeup must not shift the timers that expire later
647        self.elapsed.set(expiry);
648        self.elapsed_time.set(Some(deadline));
649
650        let (next, callbacks) = self.with_wheel(|w| {
651            w.execute_expired_timers(expiry);
652            let callbacks = w.callbacks.as_mut().and_then(|callbacks| {
653                if callbacks.ready.is_empty() {
654                    None
655                } else {
656                    Some(mem::take(&mut callbacks.ready))
657                }
658            });
659            (self.next_pending_bucket(w), callbacks)
660        });
661
662        if let Some(next) = next {
663            self.next_expiry.set(next);
664        } else {
665            self.next_expiry.set(u64::MAX);
666            self.elapsed_time.set(None);
667        }
668        callbacks
669    }
670
671    /// Runs the ready callbacks, returns `false` if a callback stopped
672    /// `generation`.
673    fn run_callbacks(&self, mut callbacks: Vec<CallbackTicket>, generation: u64) -> bool {
674        for ticket in callbacks.drain(..) {
675            if self.generation.get() != generation {
676                return false;
677            }
678            if ticket.generation == generation
679                && let Some(state) = ticket.state.upgrade()
680                && state.arm.get() == ticket.arm
681                && state.pending.replace(false)
682            {
683                (state.callback)();
684            }
685        }
686        // A callback or its captures may have stopped this runtime.
687        if self.generation.get() != generation {
688            return false;
689        }
690        // keep the allocation for the next batch
691        self.with_wheel(|wheel| wheel.callbacks.as_mut().unwrap().ready = callbacks);
692        true
693    }
694
695    /// Instant that corresponds to the wheel clock.
696    fn elapsed_time(&self) -> Instant {
697        if let Some(elapsed_time) = self.elapsed_time.get() {
698            elapsed_time
699        } else {
700            let elapsed_time = Instant::now();
701            self.elapsed_time.set(Some(elapsed_time));
702            elapsed_time
703        }
704    }
705
706    fn add_timer(self: &Rc<Self>, millis: u64) -> TimerHandle {
707        let no = if millis == 0 {
708            // elapsed immediately
709            self.with_wheel(|w| {
710                w.timers.insert(TimerEntry {
711                    bucket: None,
712                    bucket_entry: 0,
713                    callback: false,
714                    task: None,
715                })
716            })
717        } else {
718            let (idx, expiry) = self.calc_bucket(millis);
719            let no = self.with_wheel(|w| {
720                let no = w.timers.insert(TimerEntry {
721                    bucket: None,
722                    bucket_entry: 0,
723                    callback: false,
724                    task: None,
725                });
726                w.link(no, idx);
727                no
728            });
729            self.update_next_expiry(expiry);
730            no
731        };
732
733        TimerHandle(self.handle(no), PhantomData)
734    }
735
736    /// Moves the timer to a new bucket, a zero delay elapses it and wakes its
737    /// task.
738    ///
739    /// Returns the instant the timer expires.
740    fn update_timer(self: &Rc<Self>, hnd: usize, millis: u64) -> Instant {
741        if millis == 0 {
742            self.remove_timer(hnd);
743            Instant::now()
744        } else {
745            let (idx, expiry) = self.calc_bucket(millis);
746            self.with_wheel(|w| w.relink(hnd, idx));
747            self.update_next_expiry(expiry);
748            self.expiry_time(expiry)
749        }
750    }
751
752    /// Elapses the timer and wakes its task.
753    fn remove_timer(&self, hnd: usize) {
754        self.with_wheel(|w| {
755            if w.unlink(hnd)
756                && let Some(task) = w.timers[hnd].task.take()
757            {
758                task.wake();
759            }
760        });
761    }
762
763    /// Returns the bucket index and the bucket expiry for a delay starting now.
764    fn calc_bucket(self: &Rc<Self>, millis: u64) -> (usize, u64) {
765        self.insert_flags(Flags::RUNNING);
766
767        // The delay is measured from the wheel clock. The cached time is not
768        // used, it goes stale while the thread is blocked and the timer would
769        // fire early by its age
770        let units = if let Some(units) = self.units.get() {
771            units
772        } else {
773            // the wheel is stopped, it is empty and its clock is at zero
774            let units = self.resolution.unwrap_or_else(system_units);
775            self.units.set(Some(units));
776            units
777        };
778
779        let since = Instant::now().saturating_duration_since(self.elapsed_time());
780        let delta = to_units(as_millis(since) + millis, units);
781        self.calc_wheel_index(self.elapsed.get().wrapping_add(delta), delta)
782    }
783
784    /// Selects the level for a timer that expires at `expires`, `delta` units
785    /// from now.
786    fn calc_wheel_index(&self, expires: u64, delta: u64) -> (usize, u64) {
787        for lvl in 0..LVL_DEPTH {
788            if delta < lvl_start(lvl + 1) {
789                return Self::calc_index(expires, lvl);
790            }
791        }
792        // expire larger delays at the capacity limit of the wheel
793        Self::calc_index(
794            self.elapsed.get().wrapping_add(WHEEL_TIMEOUT_MAX),
795            LVL_DEPTH - 1,
796        )
797    }
798
799    /// Returns the bucket index and the bucket expiry on level `lvl`.
800    fn calc_index(expires: u64, lvl: u64) -> (usize, u64) {
801        // The timer must not fire early. Early expiry can happen because the
802        // timer is armed at the edge of a tick, or because the expiry is
803        // truncated to the level granularity, round up to prevent it.
804        let expires = (expires + lvl_gran(lvl)) >> lvl_shift(lvl);
805        (
806            (lvl * LVL_SIZE + (expires & LVL_MASK)) as usize,
807            expires << lvl_shift(lvl),
808        )
809    }
810
811    /// Wakes the driver if the new bucket expires before the current deadline.
812    ///
813    /// A native runtime reads the deadline when its poll finishes.
814    fn update_next_expiry(self: &Rc<Self>, expiry: u64) {
815        if expiry < self.next_expiry.get() {
816            self.next_expiry.set(expiry);
817            let flags = self.flags.get();
818            // a native runtime expires its timers in `Runtime::poll`
819            if flags.contains(Flags::NATIVE) {
820                return;
821            }
822            if flags.contains(Flags::DRIVER_STARTED) {
823                self.driver.wake();
824            } else {
825                TimerDriver::start(self);
826            }
827        }
828    }
829
830    /// Instant at which the bucket expiring at `expiry` is due.
831    fn expiry_time(&self, expiry: u64) -> Instant {
832        let units = self.units.get().unwrap_or(DEFAULT_UNITS);
833        self.elapsed_time()
834            + Duration::from_millis(to_millis(expiry.saturating_sub(self.elapsed.get()), units))
835    }
836
837    /// Returns the expiry of the earliest occupied bucket.
838    fn next_pending_bucket(&self, wheel: &Wheel) -> Option<u64> {
839        let mut clk = self.elapsed.get();
840        let mut next = u64::MAX;
841
842        for lvl in 0..LVL_DEPTH {
843            let lvl_clk = clk & LVL_CLK_MASK;
844            let occupied = wheel.occupied[lvl as usize];
845
846            if occupied != 0 {
847                // distance to the next occupied bucket, wrapping around the level
848                let pos = u64::from(
849                    occupied
850                        .rotate_right((clk & LVL_MASK) as u32)
851                        .trailing_zeros(),
852                );
853                next = cmp::min(next, (clk + pos) << lvl_shift(lvl));
854
855                // The next level is reached once the clock of this level wraps
856                // to a multiple of `LVL_CLK_DIV`, an earlier bucket here cannot
857                // be preceded by one of the next level.
858                if pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK) {
859                    break;
860                }
861            }
862
863            // Clock of the next level. A partially elapsed tick of this level
864            // is rounded up, as the next level bucket it belongs to was already
865            // processed.
866            clk >>= LVL_CLK_SHIFT;
867            clk += u64::from(lvl_clk != 0);
868        }
869
870        if next < u64::MAX { Some(next) } else { None }
871    }
872
873    /// Removes `flags`, and `RUNNING` so the cached time is not populated and
874    /// no driver is spawned after the runtime stopped.
875    fn remove_flags(&self, flags: Flags) {
876        let mut f = self.flags.get();
877        f.remove(flags | Flags::RUNNING);
878        self.flags.set(f);
879    }
880
881    /// Invalidates the cached time, called when the lowres driver is dropped.
882    fn stop_lowres(&self) {
883        self.remove_flags(Flags::LOWRES_DRIVER | Flags::LOWRES_TIMER);
884        self.lowres_stime.set(None);
885    }
886
887    /// Stops the drivers of the current generation, called when the system
888    /// that runs them has stopped.
889    fn reset(&self) {
890        self.generation.set(self.generation.get().wrapping_add(1));
891        self.stop_wheel();
892        self.stop_lowres();
893        self.driver.take_local();
894        self.lowres_driver.take_local();
895    }
896
897    /// Marks all timers as elapsed and resets the wheel, called when the timer
898    /// driver is dropped. Tasks are not woken, the runtime is stopping.
899    fn stop_wheel(&self) {
900        self.remove_flags(Flags::DRIVER_STARTED);
901
902        self.with_wheel(|wheel| {
903            let Wheel {
904                timers,
905                buckets,
906                occupied,
907                callbacks,
908            } = wheel;
909            for bucket in buckets.iter_mut() {
910                for no in bucket.drain() {
911                    timers[no].bucket = None;
912                }
913            }
914            *occupied = [0; LVL_DEPTH as usize];
915            if let Some(callbacks) = callbacks {
916                callbacks.ready.clear();
917                for ticket in callbacks.entries.values() {
918                    if let Some(state) = ticket.state.upgrade() {
919                        state.pending.set(false);
920                    }
921                }
922            }
923
924            self.next_expiry.set(u64::MAX);
925            self.elapsed.set(0);
926            self.elapsed_time.set(None);
927            self.units.set(None);
928        });
929    }
930}
931
932impl Wheel {
933    /// Level and occupied bit of a bucket.
934    fn bucket_bit(idx: usize) -> (usize, u64) {
935        (idx / LVL_SIZE as usize, 1 << (idx % LVL_SIZE as usize))
936    }
937
938    /// Stores the timer in bucket `idx`.
939    fn link(&mut self, hnd: usize, idx: usize) {
940        let entry = &mut self.timers[hnd];
941        entry.bucket = Some(idx as u16);
942        entry.bucket_entry = self.buckets[idx].insert(hnd);
943
944        let (lvl, bit) = Self::bucket_bit(idx);
945        self.occupied[lvl] |= bit;
946    }
947
948    /// Removes the timer from its bucket and marks it as elapsed.
949    ///
950    /// Returns `false` if the timer has already elapsed.
951    fn unlink(&mut self, hnd: usize) -> bool {
952        let entry = &mut self.timers[hnd];
953        if let Some(idx) = entry.bucket.take() {
954            let idx = idx as usize;
955            let bucket = &mut self.buckets[idx];
956            bucket.remove(entry.bucket_entry);
957            if bucket.is_empty() {
958                let (lvl, bit) = Self::bucket_bit(idx);
959                self.occupied[lvl] &= !bit;
960            }
961            true
962        } else {
963            false
964        }
965    }
966
967    /// Moves the timer to bucket `idx`.
968    fn relink(&mut self, hnd: usize, idx: usize) {
969        if self.timers[hnd].bucket != Some(idx as u16) {
970            self.unlink(hnd);
971            self.link(hnd, idx);
972        }
973    }
974
975    /// Marks timers elapsed, waking tasks in place and queueing only callbacks.
976    fn execute_expired_timers(&mut self, mut clk: u64) {
977        for lvl in 0..LVL_DEPTH {
978            let idx = ((clk & LVL_MASK) + lvl * LVL_SIZE) as usize;
979            let bucket = &mut self.buckets[idx];
980            if !bucket.is_empty() {
981                let (lvl, bit) = Self::bucket_bit(idx);
982                self.occupied[lvl] &= !bit;
983                let mut expired = ExpiredTimers {
984                    timers: &mut self.timers,
985                    entries: bucket.drain(),
986                };
987                for no in expired.entries.by_ref() {
988                    let entry = &mut expired.timers[no];
989                    entry.bucket = None;
990                    if entry.callback {
991                        let callbacks = self.callbacks.as_mut().unwrap();
992                        callbacks.ready.push(callbacks.entries[&no].clone());
993                    } else if let Some(task) = entry.task.take() {
994                        task.wake();
995                    }
996                }
997            }
998
999            // The next level expires only when the clock is a multiple of its
1000            // granularity
1001            if (clk & LVL_CLK_MASK) != 0 {
1002                break;
1003            }
1004            clk >>= LVL_CLK_SHIFT;
1005        }
1006    }
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use std::cell::RefCell;
1012    use std::panic::{AssertUnwindSafe, catch_unwind};
1013    use std::sync::Arc;
1014    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1015    use std::task::{Context, RawWaker, RawWakerVTable, Wake, Waker};
1016    use std::{future::Future, pin::Pin};
1017
1018    use super::driver::Sleep;
1019
1020    /// Returns the wheel slot of `hnd`.
1021    fn slot(hnd: NonZeroU64) -> usize {
1022        (hnd.get() & u64::from(u32::MAX)) as usize
1023    }
1024
1025    use super::*;
1026    use crate::testing::TestRunner;
1027
1028    /// Completes after `millis`, like the `Sleep` future of `ntex-util`.
1029    fn sleep(millis: u64) -> impl Future<Output = ()> {
1030        let hnd = TimerHandle::new(cmp::max(millis, 1));
1031        std::future::poll_fn(move |cx| hnd.poll_elapsed(cx))
1032    }
1033
1034    fn block_on(fut: impl Future<Output = ()> + 'static) {
1035        crate::System::build().build(TestRunner).block_on(fut);
1036    }
1037
1038    struct OnDropFn<F: FnOnce()>(Option<F>);
1039
1040    impl<F: FnOnce()> OnDropFn<F> {
1041        fn new(f: F) -> Self {
1042            Self(Some(f))
1043        }
1044    }
1045
1046    impl<F: FnOnce()> Drop for OnDropFn<F> {
1047        fn drop(&mut self) {
1048            if let Some(f) = self.0.take() {
1049                f();
1050            }
1051        }
1052    }
1053
1054    #[derive(Default)]
1055    struct InPlaceWaker {
1056        wakes: AtomicUsize,
1057        delay: Duration,
1058        panic_on_wake: bool,
1059    }
1060
1061    impl Wake for InPlaceWaker {
1062        fn wake(self: Arc<Self>) {
1063            TIMER.with(|timer| {
1064                let wheel = timer.wheel.take();
1065                let held = wheel.is_none();
1066                timer.wheel.set(wheel);
1067                assert!(held, "waker must run in place while the wheel is held");
1068            });
1069            let previous = self.wakes.fetch_add(1, Ordering::Relaxed);
1070            assert!(!self.panic_on_wake, "notification");
1071            if previous == 0 && !self.delay.is_zero() {
1072                std::thread::sleep(self.delay);
1073            }
1074        }
1075    }
1076
1077    fn timer_state() -> Rc<Timer> {
1078        TIMER.with(|timer| {
1079            timer.reset();
1080            // These tests drive expiry manually, without an executor.
1081            timer.insert_flags(Flags::DRIVER_STARTED);
1082            timer.clone()
1083        })
1084    }
1085
1086    /// STATEMENT: Callback timer diagnostics expose the handle without borrowing the wheel or invoking callbacks.
1087    ///
1088    /// HOW:
1089    /// - Format an armed timer while the wheel is borrowed, then cancel and format it again.
1090    /// - Check the same handle is reported and the captured callback has not run.
1091    #[test]
1092    fn debug_callback_timer() {
1093        let timer = timer_state();
1094        let calls = Rc::new(Cell::new(0));
1095        let captured = calls.clone();
1096        let callback = CallbackHandle::new(10_000, move || {
1097            captured.set(captured.get() + 1);
1098        });
1099        let expected = format!("CallbackHandle {{ handle: {}, .. }}", callback.hnd);
1100        timer.with_wheel(|_| assert_eq!(format!("{callback:?}"), expected));
1101        assert!(!callback.is_elapsed());
1102        callback.cancel();
1103        assert_eq!(format!("{callback:?}"), expected);
1104        assert!(callback.is_elapsed());
1105        assert_eq!(calls.get(), 0);
1106    }
1107
1108    /// STATEMENT: `Timer` diagnostics report the wheel id without borrowing the wheel.
1109    ///
1110    /// HOW:
1111    /// - Format the timer while the wheel is taken out by `with_wheel`.
1112    /// - Check the output names the wheel id that forms the upper half of a timer handle.
1113    #[test]
1114    fn debug_timer() {
1115        let timer = timer_state();
1116        let callback = CallbackHandle::new(10_000, || {});
1117        let expected = format!("Timer {{ id: {}, .. }}", callback.hnd.get() >> 32);
1118        timer.with_wheel(|_| assert_eq!(format!("{timer:?}"), expected));
1119        assert_eq!(format!("{timer:?}"), expected);
1120    }
1121
1122    fn timer_driver(timer: &Rc<Timer>) -> TimerDriver {
1123        TimerDriver {
1124            timer: timer.clone(),
1125            generation: timer.generation.get(),
1126            sleep: Sleep::new(Instant::now()),
1127            armed: None,
1128        }
1129    }
1130
1131    /// Polls `driver` once with a no-op waker.
1132    ///
1133    /// With the `tokio` or `compio` feature the driver sleep needs a runtime
1134    /// context; the runtime is not driven, so the sleep never fires here.
1135    fn poll_driver(driver: &mut TimerDriver) -> Poll<()> {
1136        let poll = || Pin::new(driver).poll(&mut Context::from_waker(Waker::noop()));
1137
1138        #[cfg(feature = "tokio")]
1139        {
1140            static RT: std::sync::LazyLock<tok_io::runtime::Runtime> =
1141                std::sync::LazyLock::new(|| {
1142                    tok_io::runtime::Builder::new_current_thread()
1143                        .enable_time()
1144                        .build()
1145                        .unwrap()
1146                });
1147            let _guard = RT.enter();
1148            poll()
1149        }
1150        #[cfg(all(feature = "compio", not(feature = "tokio")))]
1151        {
1152            thread_local! {
1153                static RT: compio_runtime::Runtime = compio_runtime::Runtime::new().unwrap();
1154            }
1155            RT.with(|rt| rt.enter(poll))
1156        }
1157        #[cfg(all(not(feature = "tokio"), not(feature = "compio")))]
1158        poll()
1159    }
1160
1161    fn make_due(timer: &Timer) {
1162        timer.elapsed_time.set(Some(
1163            Instant::now().checked_sub(Duration::from_secs(1)).unwrap(),
1164        ));
1165    }
1166
1167    #[derive(Debug)]
1168    struct NoopNotify;
1169
1170    impl crate::Notify for NoopNotify {
1171        fn notify(&self) -> std::io::Result<()> {
1172            Ok(())
1173        }
1174    }
1175
1176    /// STATEMENT: Timer waker registration avoids redundant clones and survives replacement panics.
1177    ///
1178    /// HOW:
1179    /// - Count raw-waker clones and references while re-registering, resetting, and replacing.
1180    /// - Catch a clone panic, then verify expiry wakes only the replacement and drop releases it.
1181    #[test]
1182    fn test_local_waker_registration() {
1183        struct Registration {
1184            inner: Waker,
1185            clones: AtomicUsize,
1186            panic_on_clone: AtomicBool,
1187        }
1188
1189        // Keep clone identity stable without relying on generic vtable deduplication.
1190        static VTABLE: RawWakerVTable = RawWakerVTable::new(
1191            |data| {
1192                // SAFETY: Each waker holds a live `Arc<Registration>` count; cloning adds one for the new waker.
1193                unsafe {
1194                    let state = &*data.cast::<Registration>();
1195                    assert!(!state.panic_on_clone.load(Ordering::Relaxed), "clone");
1196                    state.clones.fetch_add(1, Ordering::Relaxed);
1197                    Arc::increment_strong_count(data.cast::<Registration>());
1198                    RawWaker::new(data, &VTABLE)
1199                }
1200            },
1201            |data| {
1202                // SAFETY: Consuming this waker transfers its one raw `Arc` count into the temporary owner.
1203                unsafe {
1204                    Arc::from_raw(data.cast::<Registration>())
1205                        .inner
1206                        .wake_by_ref();
1207                }
1208            },
1209            |data| {
1210                // SAFETY: The borrowed waker keeps the `Arc<Registration>` allocation live for this call.
1211                unsafe {
1212                    (*data.cast::<Registration>()).inner.wake_by_ref();
1213                }
1214            },
1215            |data| {
1216                // SAFETY: Dropping this waker releases exactly the raw `Arc` count it owns.
1217                unsafe {
1218                    drop(Arc::from_raw(data.cast::<Registration>()));
1219                }
1220            },
1221        );
1222
1223        let wrap = |task: &Arc<InPlaceWaker>| {
1224            let state = Arc::new(Registration {
1225                inner: Waker::from(task.clone()),
1226                clones: AtomicUsize::new(0),
1227                panic_on_clone: AtomicBool::new(false),
1228            });
1229            // SAFETY: The vtable manages the transferred `Arc` count and accesses only thread-safe state.
1230            let waker = unsafe {
1231                Waker::from_raw(RawWaker::new(Arc::into_raw(state.clone()).cast(), &VTABLE))
1232            };
1233            (state, waker)
1234        };
1235
1236        let timer = timer_state();
1237        let handle = TimerHandle::new(10_000);
1238        let old_task = Arc::new(InPlaceWaker::default());
1239        let new_task = Arc::new(InPlaceWaker::default());
1240        let (old, old_waker) = wrap(&old_task);
1241        let (new, new_waker) = wrap(&new_task);
1242        let mut old_cx = Context::from_waker(&old_waker);
1243        let mut new_cx = Context::from_waker(&new_waker);
1244
1245        assert!(handle.poll_elapsed(&mut old_cx).is_pending());
1246        handle.reset(20_000);
1247        assert!(handle.poll_elapsed(&mut old_cx).is_pending());
1248        assert_eq!(old.clones.load(Ordering::Relaxed), 1);
1249        assert_eq!(Arc::strong_count(&old), 3);
1250
1251        new.panic_on_clone.store(true, Ordering::Relaxed);
1252        assert!(catch_unwind(AssertUnwindSafe(|| handle.poll_elapsed(&mut new_cx))).is_err());
1253        timer.with_wheel(|wheel| {
1254            assert!(
1255                wheel.timers[slot(handle.0)]
1256                    .task
1257                    .as_ref()
1258                    .unwrap()
1259                    .will_wake(&old_waker)
1260            );
1261        });
1262        assert_eq!(Arc::strong_count(&old), 3);
1263        assert_eq!(Arc::strong_count(&new), 2);
1264
1265        new.panic_on_clone.store(false, Ordering::Relaxed);
1266        assert!(handle.poll_elapsed(&mut new_cx).is_pending());
1267        assert!(handle.poll_elapsed(&mut new_cx).is_pending());
1268        assert_eq!(new.clones.load(Ordering::Relaxed), 1);
1269        assert_eq!(Arc::strong_count(&old), 2);
1270        assert_eq!(Arc::strong_count(&new), 3);
1271
1272        timer.with_wheel(|wheel| {
1273            wheel.relink(slot(handle.0), 3);
1274            wheel.execute_expired_timers(3);
1275        });
1276        assert!(handle.poll_elapsed(&mut new_cx).is_ready());
1277        assert_eq!(new.clones.load(Ordering::Relaxed), 1);
1278        assert_eq!(new_task.wakes.load(Ordering::Relaxed), 1);
1279        assert_eq!(old_task.wakes.load(Ordering::Relaxed), 0);
1280        assert_eq!(Arc::strong_count(&new), 2);
1281
1282        handle.reset(10_000);
1283        assert!(handle.poll_elapsed(&mut old_cx).is_pending());
1284        handle.reset(0);
1285        assert!(handle.is_elapsed());
1286        assert_eq!(old_task.wakes.load(Ordering::Relaxed), 1);
1287        assert_eq!(Arc::strong_count(&old), 2);
1288
1289        handle.reset(10_000);
1290        assert!(handle.poll_elapsed(&mut old_cx).is_pending());
1291        drop(handle);
1292        assert_eq!(old_task.wakes.load(Ordering::Relaxed), 1);
1293        assert_eq!(old.clones.load(Ordering::Relaxed), 3);
1294        assert_eq!(Arc::strong_count(&old), 2);
1295    }
1296
1297    /// STATEMENT: A timer wakes the most recently registered native task and supports later reuse.
1298    ///
1299    /// HOW:
1300    /// - Register two runtime tasks on one handle and expire it, checking only the second finishes.
1301    /// - Rearm for the first task, expire again, and wake its saved waker after runtime shutdown.
1302    #[test]
1303    fn test_local_waker_native_replacement() {
1304        let timer = timer_state();
1305        let rt = crate::Runtime::new(Box::new(NoopNotify));
1306        let handle = Rc::new(TimerHandle::new(10_000));
1307        let first_waker = Rc::new(Cell::new(None));
1308        let (first_handle, saved) = (handle.clone(), first_waker.clone());
1309        let first = rt.spawn(std::future::poll_fn(move |cx| {
1310            saved.set(Some(cx.waker().clone()));
1311            first_handle.poll_elapsed(cx)
1312        }));
1313        rt.poll();
1314
1315        let second_handle = handle.clone();
1316        let second = rt.spawn(std::future::poll_fn(move |cx| {
1317            second_handle.poll_elapsed(cx)
1318        }));
1319        rt.poll();
1320        timer.with_wheel(|wheel| {
1321            wheel.relink(slot(handle.0), 3);
1322            wheel.execute_expired_timers(3);
1323        });
1324        rt.poll();
1325        assert!(!first.is_finished());
1326        assert!(second.is_finished());
1327
1328        handle.reset(10_000);
1329        first_waker.take().unwrap().wake();
1330        rt.poll();
1331        assert!(!first.is_finished());
1332        handle.reset(0);
1333        rt.poll();
1334        assert!(first.is_finished());
1335        assert_eq!(Rc::strong_count(&handle), 1);
1336        drop(rt);
1337        first_waker.take().unwrap().wake();
1338    }
1339
1340    /// STATEMENT: Timer handles safely retain stale task wakers across runtime shutdown and reuse.
1341    ///
1342    /// HOW:
1343    /// - Register timer and driver wakers, drop the runtime, and reset timer state.
1344    /// - Check released task references and driver slots, then optionally reuse the handle in a new runtime.
1345    #[test]
1346    fn test_local_waker_runtime_shutdown() {
1347        for reuse in [false, true] {
1348            let timer = timer_state();
1349            let rt = crate::Runtime::new(Box::new(NoopNotify));
1350            let handle = Rc::new(TimerHandle::new(10_000));
1351            let (task_timer, task_handle) = (timer.clone(), handle.clone());
1352            let task = rt.spawn(std::future::poll_fn(move |cx| {
1353                task_timer.driver.register(cx.waker());
1354                task_timer.lowres_driver.register(cx.waker());
1355                task_handle.poll_elapsed(cx)
1356            }));
1357            rt.poll();
1358            drop(rt);
1359            assert!(task.is_finished());
1360            assert_eq!(Rc::strong_count(&handle), 1);
1361            drop(task);
1362
1363            timer.reset();
1364            assert!(handle.is_elapsed());
1365            assert!(!timer.driver.is_set());
1366            assert!(!timer.lowres_driver.is_set());
1367            timer.with_wheel(|wheel| {
1368                assert!(wheel.timers[slot(handle.0)].task.is_some());
1369            });
1370
1371            if reuse {
1372                timer.insert_flags(Flags::DRIVER_STARTED);
1373                handle.reset(10_000);
1374                let rt = crate::Runtime::new(Box::new(NoopNotify));
1375                let task_handle = handle.clone();
1376                let task = rt.spawn(std::future::poll_fn(move |cx| task_handle.poll_elapsed(cx)));
1377                rt.poll();
1378                assert!(!task.is_finished());
1379                handle.elapse();
1380                rt.poll();
1381                assert!(task.is_finished());
1382                assert_eq!(Rc::strong_count(&handle), 1);
1383            }
1384            drop(handle);
1385            timer.with_wheel(|wheel| assert_eq!(wheel.timers.len(), 1));
1386        }
1387    }
1388
1389    /// STATEMENT: Timer wakers can be replaced across successive systems on the same thread.
1390    ///
1391    /// HOW:
1392    /// - Reuse one handle across three systems with alternating native and wrapped wakers.
1393    /// - Reset and expire it in each system and check wrapped notification counts after shutdown.
1394    // a native runtime owns its wheel, handles do not outlive it
1395    #[cfg(any(feature = "tokio", feature = "compio"))]
1396    #[test]
1397    fn test_local_waker_in_next_system() {
1398        struct Wrapped {
1399            inner: Waker,
1400            wakes: Arc<AtomicUsize>,
1401        }
1402
1403        impl Wake for Wrapped {
1404            fn wake(self: Arc<Self>) {
1405                self.wakes.fetch_add(1, Ordering::Relaxed);
1406                self.inner.wake_by_ref();
1407            }
1408        }
1409
1410        std::thread::spawn(|| {
1411            let mut handle = None::<TimerHandle>;
1412            for wrapped in [false, true, false] {
1413                let notifications = Arc::new(AtomicUsize::new(0));
1414                let count = notifications.clone();
1415                handle = Some(
1416                    crate::System::build()
1417                        .build(TestRunner)
1418                        .block_on(async move {
1419                            let handle = if let Some(handle) = handle {
1420                                assert!(handle.is_elapsed());
1421                                handle.reset(10_000);
1422                                handle
1423                            } else {
1424                                TimerHandle::new(10_000)
1425                            };
1426                            std::future::poll_fn(|cx| {
1427                                let waker = if wrapped {
1428                                    Waker::from(Arc::new(Wrapped {
1429                                        inner: cx.waker().clone(),
1430                                        wakes: count.clone(),
1431                                    }))
1432                                } else {
1433                                    cx.waker().clone()
1434                                };
1435                                let cx = &mut Context::from_waker(&waker);
1436                                assert!(handle.poll_elapsed(cx).is_pending());
1437                                handle.reset(0);
1438                                assert!(handle.poll_elapsed(cx).is_ready());
1439                                handle.reset(10_000);
1440                                assert!(handle.poll_elapsed(cx).is_pending());
1441                                Poll::Ready(())
1442                            })
1443                            .await;
1444                            handle
1445                        }),
1446                );
1447                assert!(handle.as_ref().unwrap().is_elapsed());
1448                assert_eq!(notifications.load(Ordering::Relaxed), usize::from(wrapped));
1449            }
1450        })
1451        .join()
1452        .unwrap();
1453    }
1454
1455    /// STATEMENT: Callback timers can be canceled and repeatedly rearmed for one delivery each.
1456    ///
1457    /// HOW:
1458    /// - Cancel a reset timer and verify no callback runs after waiting.
1459    /// - Rearm with zero delay twice and check elapsed state and one additional call per expiry.
1460    #[test]
1461    fn test_callback_timer() {
1462        block_on(async {
1463            let calls = Rc::new(Cell::new(0));
1464            let count = calls.clone();
1465            let callback = CallbackHandle::new(0, move || {
1466                count.set(count.get() + 1);
1467            });
1468            assert!(!callback.is_elapsed());
1469            assert_eq!(calls.get(), 0);
1470            callback.reset(10_000);
1471            callback.cancel();
1472            assert!(callback.is_elapsed());
1473            sleep(50).await;
1474            assert_eq!(calls.get(), 0);
1475
1476            for expected in 1..=2 {
1477                callback.reset(0);
1478                assert!(!callback.is_elapsed());
1479                sleep(50).await;
1480                assert!(callback.is_elapsed());
1481                assert_eq!(calls.get(), expected);
1482            }
1483        });
1484    }
1485
1486    /// STATEMENT: Stale callback tickets cannot invoke canceled, reset, dropped, or reused entries.
1487    ///
1488    /// HOW:
1489    /// - Queue expired callbacks, then cancel, reset, and drop them before driver delivery.
1490    /// - Reuse the freed slot, verify captures were released, and check only new deadlines fire once.
1491    #[test]
1492    fn test_callback_stale_tickets() {
1493        let timer = timer_state();
1494        let calls = Rc::new(Cell::new(0));
1495        let count = calls.clone();
1496        let cancelled = CallbackHandle::new(1, move || count.set(count.get() + 1));
1497        let count = calls.clone();
1498        let reset = CallbackHandle::new(1, move || count.set(count.get() + 1));
1499        let capture = Rc::new(Cell::new(0));
1500        let weak = Rc::downgrade(&capture);
1501        let dropped = CallbackHandle::new(1, move || capture.set(1));
1502        let old_slot = dropped.hnd;
1503        timer.with_wheel(|wheel| {
1504            for handle in [&cancelled, &reset, &dropped] {
1505                wheel.relink(slot(handle.hnd), 3);
1506            }
1507            wheel.execute_expired_timers(3);
1508        });
1509        assert!(cancelled.is_elapsed());
1510        assert!(reset.is_elapsed());
1511        assert!(dropped.is_elapsed());
1512        assert_eq!(calls.get(), 0);
1513        cancelled.cancel();
1514        reset.reset(10_000);
1515        drop(dropped);
1516        assert!(
1517            weak.upgrade().is_none(),
1518            "queued tickets must not retain captures"
1519        );
1520        let count = calls.clone();
1521        let replacement = CallbackHandle::new(10_000, move || count.set(count.get() + 100));
1522        assert_eq!(replacement.hnd, old_slot);
1523
1524        make_due(&timer);
1525        let mut driver = timer_driver(&timer);
1526        assert!(poll_driver(&mut driver).is_pending());
1527        assert_eq!(calls.get(), 0);
1528        assert!(!reset.is_elapsed());
1529        assert!(!replacement.is_elapsed());
1530        timer.elapsed_time.set(Some(
1531            Instant::now().checked_sub(Duration::from_secs(20)).unwrap(),
1532        ));
1533        for _ in 0..2 {
1534            assert!(poll_driver(&mut driver).is_pending());
1535            assert_eq!(calls.get(), 101);
1536        }
1537    }
1538
1539    /// STATEMENT: A callback can rearm itself and cancel another callback already due for delivery.
1540    ///
1541    /// HOW:
1542    /// - Expire two callbacks that each cancel their peer and reset themselves.
1543    /// - Verify only one runs initially and its rearmed deadline produces one further call.
1544    #[test]
1545    fn test_callback_self_rearm_and_cross_cancel() {
1546        let timer = timer_state();
1547        let calls = Rc::new(Cell::new(0));
1548        let handles = Rc::new(RefCell::new(Vec::<CallbackHandle>::new()));
1549        for index in 0..2 {
1550            let count = calls.clone();
1551            let weak = Rc::downgrade(&handles);
1552            let callback = CallbackHandle::new(1, move || {
1553                count.set(count.get() + 1);
1554                let handles = weak.upgrade().unwrap();
1555                let handles = handles.borrow();
1556                assert!(handles[index].is_elapsed());
1557                handles[1 - index].cancel();
1558                handles[index].reset(10_000);
1559            });
1560            handles.borrow_mut().push(callback);
1561        }
1562        timer.with_wheel(|wheel| {
1563            for handle in handles.borrow().iter() {
1564                wheel.relink(slot(handle.hnd), 1);
1565            }
1566        });
1567        make_due(&timer);
1568        let mut driver = timer_driver(&timer);
1569        assert!(poll_driver(&mut driver).is_pending());
1570        assert_eq!(calls.get(), 1);
1571        assert_eq!(
1572            handles.borrow().iter().filter(|h| !h.is_elapsed()).count(),
1573            1
1574        );
1575        timer.elapsed_time.set(Some(
1576            Instant::now().checked_sub(Duration::from_secs(20)).unwrap(),
1577        ));
1578        for _ in 0..2 {
1579            assert!(poll_driver(&mut driver).is_pending());
1580            assert_eq!(calls.get(), 2);
1581        }
1582    }
1583
1584    /// STATEMENT: Dropping callback captures can safely create, reset, and cancel timers.
1585    ///
1586    /// HOW:
1587    /// - Drop queued and actively executing callbacks whose capture destructors manipulate timers.
1588    /// - Check deferred capture release, slot reuse, cancellation, and exactly-once later delivery.
1589    #[test]
1590    fn test_callback_capture_drop_schedules_timers() {
1591        for active in [false, true] {
1592            let timer = timer_state();
1593            let released = Rc::new(Cell::new(false));
1594            let finished = Rc::new(Cell::new(false));
1595            let reset_calls = Rc::new(Cell::new(0));
1596            let new_calls = Rc::new(Cell::new(0));
1597            let count = reset_calls.clone();
1598            let reset = Rc::new(CallbackHandle::new(20_000, move || {
1599                count.set(count.get() + 1);
1600            }));
1601            let cancelled = Rc::new(CallbackHandle::new(20_000, || {
1602                panic!("cancelled callback");
1603            }));
1604            let replacement = Rc::new(RefCell::new(None::<CallbackHandle>));
1605            let capture = {
1606                let reset = reset.clone();
1607                let cancelled = cancelled.clone();
1608                let replacement = replacement.clone();
1609                let new_calls = new_calls.clone();
1610                let released = released.clone();
1611                let finished = finished.clone();
1612                OnDropFn::new(move || {
1613                    assert!(!active || finished.get());
1614                    let ordinary = TimerHandle::new(10_000);
1615                    ordinary.reset(0);
1616                    drop(ordinary);
1617                    cancelled.cancel();
1618                    reset.reset(10_000);
1619                    *replacement.borrow_mut() = Some(CallbackHandle::new(10_000, move || {
1620                        new_calls.set(new_calls.get() + 1);
1621                    }));
1622                    released.set(true);
1623                })
1624            };
1625            let handle = Rc::new(RefCell::new(None::<CallbackHandle>));
1626            let weak = Rc::downgrade(&handle);
1627            let was_released = released.clone();
1628            *handle.borrow_mut() = Some(CallbackHandle::new(1, move || {
1629                let _capture = &capture;
1630                assert!(active, "dropped queued callback must not run");
1631                drop(weak.upgrade().unwrap().borrow_mut().take());
1632                assert!(!was_released.get());
1633                finished.set(true);
1634            }));
1635            let old_slot = handle.borrow().as_ref().unwrap().hnd;
1636            if !active {
1637                timer.with_wheel(|wheel| {
1638                    wheel.relink(slot(old_slot), 1);
1639                    wheel.execute_expired_timers(1);
1640                });
1641                drop(handle.borrow_mut().take());
1642                assert!(released.get());
1643            }
1644            make_due(&timer);
1645            let mut driver = timer_driver(&timer);
1646            assert!(poll_driver(&mut driver).is_pending());
1647            assert!(released.get());
1648            assert!(handle.borrow().is_none());
1649            assert!(cancelled.is_elapsed());
1650            assert!(!reset.is_elapsed());
1651            assert_eq!(replacement.borrow().as_ref().unwrap().hnd, old_slot);
1652            assert!(!replacement.borrow().as_ref().unwrap().is_elapsed());
1653            assert_eq!((reset_calls.get(), new_calls.get()), (0, 0));
1654
1655            timer.elapsed_time.set(Some(
1656                Instant::now().checked_sub(Duration::from_secs(20)).unwrap(),
1657            ));
1658            for _ in 0..2 {
1659                assert!(poll_driver(&mut driver).is_pending());
1660                assert_eq!((reset_calls.get(), new_calls.get()), (1, 1));
1661            }
1662        }
1663    }
1664
1665    /// STATEMENT: A callback capture can reset the runtime without the old driver consuming new work.
1666    ///
1667    /// HOW:
1668    /// - Drop a callback during delivery and reset timer state from its capture destructor.
1669    /// - Queue a replacement, verify the old driver exits, and deliver it once with a new driver.
1670    #[test]
1671    fn test_callback_capture_drop_resets_runtime() {
1672        let timer = timer_state();
1673        let new_calls = Rc::new(Cell::new(0));
1674        let replacement = Rc::new(RefCell::new(None::<CallbackHandle>));
1675        let capture = {
1676            let timer = timer.clone();
1677            let new_calls = new_calls.clone();
1678            let replacement = replacement.clone();
1679            OnDropFn::new(move || {
1680                timer.reset();
1681                timer.insert_flags(Flags::DRIVER_STARTED);
1682                let callback = CallbackHandle::new(1, move || {
1683                    new_calls.set(new_calls.get() + 1);
1684                });
1685                timer.with_wheel(|wheel| {
1686                    wheel.relink(slot(callback.hnd), 1);
1687                    wheel.execute_expired_timers(1);
1688                });
1689                *replacement.borrow_mut() = Some(callback);
1690            })
1691        };
1692        let handle = Rc::new(RefCell::new(None::<CallbackHandle>));
1693        let weak = Rc::downgrade(&handle);
1694        *handle.borrow_mut() = Some(CallbackHandle::new(1, move || {
1695            let _capture = &capture;
1696            drop(weak.upgrade().unwrap().borrow_mut().take());
1697        }));
1698        make_due(&timer);
1699        let mut old_driver = timer_driver(&timer);
1700        assert!(poll_driver(&mut old_driver).is_ready());
1701        assert!(handle.borrow().is_none());
1702        assert!(replacement.borrow().as_ref().unwrap().is_elapsed());
1703        assert_eq!(new_calls.get(), 0);
1704        drop(old_driver);
1705
1706        make_due(&timer);
1707        let mut driver = timer_driver(&timer);
1708        for _ in 0..2 {
1709            assert!(poll_driver(&mut driver).is_pending());
1710            assert_eq!(new_calls.get(), 1);
1711        }
1712    }
1713
1714    /// STATEMENT: Callback delivery refreshes time after a slow callback.
1715    ///
1716    /// HOW:
1717    /// - Schedule two deadlines and make the first callback block past the second.
1718    /// - Poll the driver once and verify both callbacks ran and both timers elapsed.
1719    #[test]
1720    fn test_callback_refreshes_time() {
1721        let timer = timer_state();
1722        let calls = Rc::new(Cell::new(0));
1723        let handles = [1, 32].map(|millis| {
1724            let calls = calls.clone();
1725            CallbackHandle::new(millis, move || {
1726                let previous = calls.replace(calls.get() + 1);
1727                if previous == 0 {
1728                    std::thread::sleep(Duration::from_millis(64));
1729                }
1730            })
1731        });
1732        timer.with_wheel(|wheel| {
1733            wheel.relink(slot(handles[0].hnd), 1);
1734            wheel.relink(slot(handles[1].hnd), 3);
1735        });
1736        timer.elapsed_time.set(Some(
1737            Instant::now()
1738                .checked_sub(Duration::from_millis(32))
1739                .unwrap(),
1740        ));
1741        let mut driver = timer_driver(&timer);
1742        assert!(poll_driver(&mut driver).is_pending());
1743        assert_eq!(calls.get(), 2);
1744        assert!(handles.iter().all(CallbackHandle::is_elapsed));
1745    }
1746
1747    /// STATEMENT: Dropping a panicked driver cleans callbacks rearmed before the panic.
1748    ///
1749    /// HOW:
1750    /// - Run a callback that rearms itself and panics while other timers remain pending.
1751    /// - Drop the driver and verify elapsed handles, cleared callback flags, and empty wheel queues.
1752    #[test]
1753    fn test_callback_panic_after_rearm_cleanup() {
1754        let timer = timer_state();
1755        let callback = Rc::new_cyclic(|weak: &std::rc::Weak<CallbackHandle>| {
1756            let weak = weak.clone();
1757            CallbackHandle::new(1, move || {
1758                let callback = weak.upgrade().unwrap();
1759                callback.reset(10_000);
1760                panic!("callback");
1761            })
1762        });
1763        let later = CallbackHandle::new(10_000, || panic!("not due"));
1764        let ordinary = TimerHandle::new(10_000);
1765        make_due(&timer);
1766        let mut driver = timer_driver(&timer);
1767        assert!(
1768            catch_unwind(AssertUnwindSafe(|| {
1769                let _ = poll_driver(&mut driver);
1770            }))
1771            .is_err()
1772        );
1773        assert!(!callback.is_elapsed());
1774        drop(driver);
1775        assert!(callback.is_elapsed());
1776        assert!(!callback.state.pending.get());
1777        assert!(later.is_elapsed());
1778        assert!(ordinary.is_elapsed());
1779        assert!(!later.state.pending.get());
1780        timer.with_wheel(|wheel| {
1781            assert!(wheel.buckets.iter().all(Slab::is_empty));
1782            assert_eq!(wheel.occupied, [0; LVL_DEPTH as usize]);
1783            assert!(wheel.callbacks.as_ref().unwrap().ready.is_empty());
1784        });
1785    }
1786
1787    /// STATEMENT: Resetting timer state during callback delivery stops the old generation safely.
1788    ///
1789    /// HOW:
1790    /// - Queue two callbacks that reset runtime state and create a replacement.
1791    /// - Verify only one old callback runs and the replacement survives old-driver drop for later delivery.
1792    #[test]
1793    fn test_callback_runtime_reset_during_delivery() {
1794        let timer = timer_state();
1795        let calls = Rc::new(Cell::new(0));
1796        let new_calls = Rc::new(Cell::new(0));
1797        let replacement = Rc::new(RefCell::new(None::<CallbackHandle>));
1798        let handles = [0, 1].map(|_| {
1799            let timer = timer.clone();
1800            let calls = calls.clone();
1801            let new_calls = new_calls.clone();
1802            let replacement = replacement.clone();
1803            CallbackHandle::new(1, move || {
1804                calls.set(calls.get() + 1);
1805                timer.reset();
1806                timer.insert_flags(Flags::DRIVER_STARTED);
1807                let new_calls = new_calls.clone();
1808                *replacement.borrow_mut() = Some(CallbackHandle::new(1, move || {
1809                    new_calls.set(new_calls.get() + 1);
1810                }));
1811            })
1812        });
1813        timer.with_wheel(|wheel| {
1814            for handle in &handles {
1815                wheel.relink(slot(handle.hnd), 1);
1816            }
1817        });
1818        make_due(&timer);
1819        let mut old_driver = timer_driver(&timer);
1820        assert!(poll_driver(&mut old_driver).is_ready());
1821        assert_eq!(calls.get(), 1);
1822        assert!(handles.iter().all(CallbackHandle::is_elapsed));
1823        drop(old_driver);
1824        assert!(!replacement.borrow().as_ref().unwrap().is_elapsed());
1825        make_due(&timer);
1826        let mut driver = timer_driver(&timer);
1827        assert!(poll_driver(&mut driver).is_pending());
1828        assert_eq!(new_calls.get(), 1);
1829    }
1830
1831    /// STATEMENT: A waker panic in a mixed timer bucket leaves callback state recoverable.
1832    ///
1833    /// HOW:
1834    /// - Place a panicking waker at each position among two callback entries and catch driver unwind.
1835    /// - Check bucket and pending-ticket cleanup, then rearm a callback and verify one delivery.
1836    #[test]
1837    fn test_callback_mixed_bucket_waker_panic() {
1838        for panic_position in 0..3 {
1839            let timer = timer_state();
1840            let calls = Rc::new(Cell::new(0));
1841            let callbacks = [0, 1].map(|_| {
1842                let calls = calls.clone();
1843                CallbackHandle::new(10_000, move || calls.set(calls.get() + 1))
1844            });
1845            let ordinary = TimerHandle::new(10_000);
1846            let task = Arc::new(InPlaceWaker {
1847                panic_on_wake: true,
1848                ..InPlaceWaker::default()
1849            });
1850            let waker = Waker::from(task.clone());
1851            assert!(
1852                ordinary
1853                    .poll_elapsed(&mut Context::from_waker(&waker))
1854                    .is_pending()
1855            );
1856            timer.with_wheel(|wheel| {
1857                // Control slab drain positions, not public callback delivery order.
1858                let mut entries = [
1859                    slot(callbacks[0].hnd),
1860                    slot(ordinary.0),
1861                    slot(callbacks[1].hnd),
1862                ];
1863                entries.swap(1, panic_position);
1864                for no in entries {
1865                    wheel.unlink(no);
1866                }
1867                wheel.buckets[3] = Slab::new();
1868                for no in entries {
1869                    wheel.link(no, 3);
1870                }
1871            });
1872            timer.next_expiry.set(3);
1873            make_due(&timer);
1874            let mut driver = timer_driver(&timer);
1875            assert!(
1876                catch_unwind(AssertUnwindSafe(|| {
1877                    let _ = poll_driver(&mut driver);
1878                }))
1879                .is_err()
1880            );
1881            assert_eq!(task.wakes.load(Ordering::Relaxed), 1);
1882            assert_eq!(calls.get(), 0);
1883            assert!(ordinary.is_elapsed());
1884            assert!(callbacks.iter().all(CallbackHandle::is_elapsed));
1885            timer.with_wheel(|wheel| {
1886                assert!(wheel.buckets.iter().all(Slab::is_empty));
1887                assert_eq!(wheel.occupied, [0; LVL_DEPTH as usize]);
1888                assert_eq!(
1889                    wheel.callbacks.as_ref().unwrap().ready.len(),
1890                    panic_position
1891                );
1892            });
1893            drop(driver);
1894            assert!(
1895                callbacks
1896                    .iter()
1897                    .all(|callback| !callback.state.pending.get())
1898            );
1899            timer.with_wheel(|wheel| {
1900                assert!(wheel.callbacks.as_ref().unwrap().ready.is_empty());
1901            });
1902
1903            timer.insert_flags(Flags::DRIVER_STARTED);
1904            callbacks[0].reset(0);
1905            make_due(&timer);
1906            let mut driver = timer_driver(&timer);
1907            for _ in 0..2 {
1908                assert!(poll_driver(&mut driver).is_pending());
1909                assert_eq!(calls.get(), 1);
1910            }
1911        }
1912    }
1913
1914    /// STATEMENT: A callback timer can be rearmed in a later system without stale delivery.
1915    ///
1916    /// HOW:
1917    /// - Carry one callback handle across two systems on a dedicated thread.
1918    /// - Verify shutdown elapses it, no callback runs before rearming, and each reset delivers once.
1919    // a native runtime owns its wheel, handles do not outlive it
1920    #[cfg(any(feature = "tokio", feature = "compio"))]
1921    #[test]
1922    fn test_callback_reuse_in_next_system() {
1923        std::thread::spawn(|| {
1924            let calls = Rc::new(Cell::new(0));
1925            let mut callback = None::<CallbackHandle>;
1926            for expected in 1..=2 {
1927                let calls = calls.clone();
1928                callback = Some(
1929                    crate::System::build()
1930                        .build(TestRunner)
1931                        .block_on(async move {
1932                            let callback = if let Some(callback) = callback {
1933                                assert!(callback.is_elapsed());
1934                                sleep(50).await;
1935                                assert_eq!(calls.get(), expected - 1);
1936                                callback.reset(0);
1937                                callback
1938                            } else {
1939                                let calls = calls.clone();
1940                                CallbackHandle::new(0, move || {
1941                                    calls.set(calls.get() + 1);
1942                                })
1943                            };
1944                            sleep(50).await;
1945                            assert_eq!(calls.get(), expected);
1946                            callback.reset(10_000);
1947                            callback
1948                        }),
1949                );
1950                assert!(callback.as_ref().unwrap().is_elapsed());
1951            }
1952        })
1953        .join()
1954        .unwrap();
1955    }
1956
1957    /// STATEMENT: Wheel access is restored after an operation panics.
1958    ///
1959    /// HOW:
1960    /// - Insert an entry inside `with_wheel`, panic, and catch the unwind.
1961    /// - Access the wheel again and verify the inserted entry remains.
1962    #[test]
1963    fn test_wheel_access_restored_on_unwind() {
1964        let timer = Timer::new(None);
1965        assert!(
1966            catch_unwind(AssertUnwindSafe(|| {
1967                timer.with_wheel(|wheel| {
1968                    wheel.timers.insert(entry());
1969                    panic!("wheel operation");
1970                });
1971            }))
1972            .is_err()
1973        );
1974        timer.with_wheel(|wheel| assert_eq!(wheel.timers.len(), 2));
1975    }
1976
1977    /// STATEMENT: Manual and driven expiry wake registered tasks while wheel access is held.
1978    ///
1979    /// HOW:
1980    /// - Register a waker that asserts wheel ownership and expire handles by reset, elapse, and dispatch.
1981    /// - Check all four wakes, elapsed handles, and released waker references.
1982    #[test]
1983    fn test_wake_in_place() {
1984        let timer = timer_state();
1985        let task = Arc::new(InPlaceWaker::default());
1986        let waker = Waker::from(task.clone());
1987        let mut cx = Context::from_waker(&waker);
1988        for reset in [false, true] {
1989            let handle = TimerHandle::new(10_000);
1990            assert!(handle.poll_elapsed(&mut cx).is_pending());
1991            if reset {
1992                handle.reset(0);
1993            } else {
1994                handle.elapse();
1995            }
1996            assert!(handle.is_elapsed());
1997        }
1998        let handles = [TimerHandle::new(1), TimerHandle::new(1)];
1999        for handle in &handles {
2000            assert!(handle.poll_elapsed(&mut cx).is_pending());
2001        }
2002        timer.elapsed_time.set(Some(
2003            Instant::now().checked_sub(Duration::from_secs(20)).unwrap(),
2004        ));
2005        let mut driver = timer_driver(&timer);
2006        assert!(poll_driver(&mut driver).is_pending());
2007        assert!(handles.iter().all(TimerHandle::is_elapsed));
2008        assert_eq!(task.wakes.load(Ordering::Relaxed), 4);
2009        assert_eq!(Arc::strong_count(&task), 2);
2010    }
2011
2012    /// STATEMENT: Waker dispatch uses one time sample even if a wake callback blocks.
2013    ///
2014    /// HOW:
2015    /// - Schedule two deadlines and block inside the first wake past the second deadline.
2016    /// - Verify processing one time sample expires only one timer and a later sample
2017    ///   expires the other.
2018    #[test]
2019    fn test_dispatch_uses_one_time_sample_for_wakers() {
2020        let timer = timer_state();
2021        let handles = [TimerHandle::new(1), TimerHandle::new(32)];
2022        timer.with_wheel(|wheel| wheel.relink(slot(handles[1].0), 3));
2023        let task = Arc::new(InPlaceWaker {
2024            delay: Duration::from_millis(64),
2025            ..InPlaceWaker::default()
2026        });
2027        let waker = Waker::from(task.clone());
2028        for handle in &handles {
2029            assert!(
2030                handle
2031                    .poll_elapsed(&mut Context::from_waker(&waker))
2032                    .is_pending()
2033            );
2034        }
2035        timer.elapsed_time.set(Some(
2036            Instant::now()
2037                .checked_sub(Duration::from_millis(32))
2038                .unwrap(),
2039        ));
2040        let generation = timer.generation.get();
2041        assert!(matches!(
2042            timer.process(Instant::now(), generation),
2043            Processed::Next(_)
2044        ));
2045        assert!(handles[0].is_elapsed());
2046        assert!(!handles[1].is_elapsed());
2047        assert_eq!(task.wakes.load(Ordering::Relaxed), 1);
2048        assert!(matches!(
2049            timer.process(Instant::now(), generation),
2050            Processed::Idle
2051        ));
2052        assert!(handles[1].is_elapsed());
2053        assert_eq!(task.wakes.load(Ordering::Relaxed), 2);
2054    }
2055
2056    /// STATEMENT: A wake panic clears its expired bucket and leaves driver cleanup safe.
2057    ///
2058    /// HOW:
2059    /// - Expire two same-bucket timers with a panicking waker and inspect bucket occupancy.
2060    /// - Rearm both handles, drop the driver, and verify both elapse and the driver flag clears.
2061    #[test]
2062    fn test_dispatch_panic_cleans_expired_bucket() {
2063        let timer = timer_state();
2064        let handles = [TimerHandle::new(1), TimerHandle::new(1)];
2065        timer.with_wheel(|wheel| {
2066            let bucket = wheel.timers[slot(handles[0].0)].bucket.unwrap();
2067            wheel.relink(slot(handles[1].0), usize::from(bucket));
2068        });
2069        let task = Arc::new(InPlaceWaker {
2070            panic_on_wake: true,
2071            ..InPlaceWaker::default()
2072        });
2073        let waker = Waker::from(task.clone());
2074        for handle in &handles {
2075            assert!(
2076                handle
2077                    .poll_elapsed(&mut Context::from_waker(&waker))
2078                    .is_pending()
2079            );
2080        }
2081        timer.elapsed_time.set(Some(
2082            Instant::now()
2083                .checked_sub(Duration::from_millis(64))
2084                .unwrap(),
2085        ));
2086        let mut driver = timer_driver(&timer);
2087        assert!(
2088            catch_unwind(AssertUnwindSafe(|| {
2089                let _ = poll_driver(&mut driver);
2090            }))
2091            .is_err()
2092        );
2093        assert_eq!(task.wakes.load(Ordering::Relaxed), 1);
2094        assert!(handles.iter().all(TimerHandle::is_elapsed));
2095        timer.with_wheel(|wheel| {
2096            assert!(wheel.buckets.iter().all(Slab::is_empty));
2097            assert_eq!(wheel.occupied, [0; LVL_DEPTH as usize]);
2098        });
2099        for handle in &handles {
2100            handle.reset(10_000);
2101            assert!(!handle.is_elapsed());
2102        }
2103        drop(driver);
2104        assert!(handles.iter().all(TimerHandle::is_elapsed));
2105        assert!(!timer.flags.get().contains(Flags::DRIVER_STARTED));
2106    }
2107
2108    /// STATEMENT: A timer handle can be dropped after its thread-local wheel is destroyed.
2109    ///
2110    /// HOW:
2111    /// - Register handle storage before timer storage so its destructor runs last.
2112    /// - Leave a registered handle in that storage and verify the thread exits without panic.
2113    #[test]
2114    fn test_drop_handle_after_wheel_destroyed() {
2115        use std::cell::RefCell;
2116
2117        thread_local! {
2118            static HOLDER: RefCell<Option<TimerHandle>> = const { RefCell::new(None) };
2119        }
2120
2121        let res = std::thread::spawn(|| {
2122            // register the holder destructor first, the wheel is destroyed
2123            // before it, destructors run in reverse registration order
2124            HOLDER.with(|h| h.borrow_mut().take());
2125            crate::System::build().build(TestRunner).block_on(async {
2126                let hnd = TimerHandle::new(1000);
2127                std::future::poll_fn(|cx| {
2128                    assert!(hnd.poll_elapsed(cx).is_pending());
2129                    Poll::Ready(())
2130                })
2131                .await;
2132                HOLDER.with(|h| *h.borrow_mut() = Some(hnd));
2133            });
2134        })
2135        .join();
2136        assert!(res.is_ok());
2137    }
2138
2139    /// STATEMENT: Callback captures are released once even when their timer outlives wheel storage.
2140    ///
2141    /// HOW:
2142    /// - Store a callback in earlier-registered thread-local storage with a counted drop capture.
2143    /// - Exit the thread and verify capture destruction occurred after wheel destruction exactly once.
2144    // a native runtime owns its wheel, handles do not outlive it
2145    #[cfg(any(feature = "tokio", feature = "compio"))]
2146    #[test]
2147    fn test_drop_callback_after_wheel_destroyed() {
2148        thread_local! {
2149            static HOLDER: RefCell<Option<CallbackHandle>> = const { RefCell::new(None) };
2150        }
2151
2152        let drops = Arc::new(AtomicUsize::new(0));
2153        let destroyed = Arc::new(AtomicBool::new(false));
2154        let count = drops.clone();
2155        let was_destroyed = destroyed.clone();
2156        std::thread::spawn(move || {
2157            // Register this destructor before the timer's thread-local storage.
2158            HOLDER.with(|holder| holder.borrow_mut().take());
2159            crate::System::build()
2160                .build(TestRunner)
2161                .block_on(async move {
2162                    let ordinary = TimerHandle::new(10_000);
2163                    let capture = OnDropFn::new(move || {
2164                        was_destroyed.store(TIMER.try_with(|_| ()).is_err(), Ordering::Relaxed);
2165                        drop(ordinary);
2166                        count.fetch_add(1, Ordering::Relaxed);
2167                    });
2168                    let callback = CallbackHandle::new(10_000, move || {
2169                        let _capture = &capture;
2170                        panic!("callback after shutdown");
2171                    });
2172                    HOLDER.with(|holder| *holder.borrow_mut() = Some(callback));
2173                });
2174        })
2175        .join()
2176        .unwrap();
2177        assert!(destroyed.load(Ordering::Relaxed));
2178        assert_eq!(drops.load(Ordering::Relaxed), 1);
2179    }
2180
2181    /// STATEMENT: Successive systems on one thread start working timers despite prior pending tasks.
2182    ///
2183    /// HOW:
2184    /// - Start three systems, complete a short sleep, and leave long sleeps pending in each.
2185    /// - Check per-system elapsed bounds and thread completion within an overall deadline.
2186    #[test]
2187    fn test_timer_in_next_system() {
2188        let res = std::thread::spawn(|| {
2189            for _ in 0..3 {
2190                let start = Instant::now();
2191                crate::System::build().build(TestRunner).block_on(async {
2192                    sleep(10).await;
2193                    let _ = crate::now();
2194                    // pending timer of the stopped system
2195                    let _hnd = sleep(10_000);
2196                    crate::spawn(async { sleep(10_000).await });
2197                });
2198                assert!(start.elapsed() < Duration::from_secs(5));
2199            }
2200        });
2201        let (tx, rx) = std::sync::mpsc::channel();
2202        std::thread::spawn(move || tx.send(res.join().is_ok()));
2203        assert_eq!(rx.recv_timeout(Duration::from_secs(10)), Ok(true));
2204    }
2205
2206    /// STATEMENT: Each system run on a thread arms timers with its own configured resolution.
2207    ///
2208    /// HOW:
2209    /// - Run systems with 2 ms, default and 1 ms resolutions on one thread.
2210    /// - In each, complete a sleep and check the latched `units` shift and the
2211    ///   level of a 200 ms timer, level 1 at 1-2 ms and level 0 at 16 ms. The
2212    ///   delay stays well inside level 1 (63..504 ticks) at 1 ms, so it
2213    ///   tolerates about 300 ms of wheel lag on a slow host.
2214    /// - After each run, check `units` is cleared for the next system.
2215    #[test]
2216    fn test_timer_resolution_per_system() {
2217        std::thread::spawn(|| {
2218            for (resolution, units, level) in [(Some(2), 1, 1), (None, 4, 0), (Some(1), 0, 1)] {
2219                let mut builder = crate::System::build();
2220                if let Some(resolution) = resolution {
2221                    builder = builder.timer_resolution(resolution);
2222                }
2223                builder.build(TestRunner).block_on(async move {
2224                    sleep(1).await;
2225                    let hnd = TimerHandle::new(200);
2226                    with_timer(|timer| {
2227                        assert_eq!(timer.units.get(), Some(units));
2228                        let bucket = timer.with_wheel(|w| w.timers[slot(hnd.0)].bucket).unwrap();
2229                        assert_eq!(u64::from(bucket) / LVL_SIZE, level);
2230                    });
2231                });
2232                assert_eq!(TIMER.with(|timer| timer.units.get()), None);
2233            }
2234        })
2235        .join()
2236        .unwrap();
2237    }
2238
2239    /// STATEMENT: Timers armed without a running system use the default 16 ms resolution.
2240    ///
2241    /// HOW:
2242    /// - Reset the thread's timer state and check `units` is unset.
2243    /// - Arm a timer outside of any system and check `units` is `DEFAULT_UNITS`.
2244    #[test]
2245    fn test_timer_resolution_without_system() {
2246        let timer = timer_state();
2247        assert_eq!(timer.units.get(), None);
2248        let _hnd = TimerHandle::new(10);
2249        assert_eq!(timer.units.get(), Some(DEFAULT_UNITS));
2250    }
2251
2252    /// STATEMENT: Dropping stale drivers does not clear a newer generation's running flags.
2253    ///
2254    /// HOW:
2255    /// - Reset timer state, mark the new generation running, and drop both old driver types.
2256    /// - Verify all new-generation driver flags remain set.
2257    #[test]
2258    fn test_stale_driver_drop() {
2259        let timer = Rc::new(Timer::new(None));
2260        timer.insert_flags(Flags::RUNNING | Flags::DRIVER_STARTED | Flags::LOWRES_DRIVER);
2261        timer.reset();
2262        assert_eq!(timer.flags.get(), Flags::empty());
2263
2264        timer.insert_flags(Flags::RUNNING | Flags::DRIVER_STARTED | Flags::LOWRES_DRIVER);
2265        drop(TimerDriver {
2266            timer: timer.clone(),
2267            generation: 0,
2268            sleep: Sleep::new(Instant::now()),
2269            armed: None,
2270        });
2271        drop(LowresTimerDriver {
2272            timer: timer.clone(),
2273            generation: 0,
2274            sleep: Sleep::new(Instant::now()),
2275        });
2276        assert_eq!(
2277            timer.flags.get(),
2278            Flags::RUNNING | Flags::DRIVER_STARTED | Flags::LOWRES_DRIVER
2279        );
2280    }
2281
2282    fn entry() -> TimerEntry {
2283        TimerEntry {
2284            bucket: None,
2285            bucket_entry: 0,
2286            callback: false,
2287            task: None,
2288        }
2289    }
2290
2291    /// STATEMENT: Bucket placement never expires early and stays within its level's granularity.
2292    ///
2293    /// HOW:
2294    /// - Calculate buckets for varied elapsed times and exponentially increasing delays.
2295    /// - Check expiry bounds, alignment, bucket indices, and clamping beyond wheel capacity.
2296    #[test]
2297    fn test_bucket_expiry_bounds() {
2298        let timer = Timer::new(None);
2299        for elapsed in [0, 1, 7, 8, 63, 64, 511, 12_345, 1 << 30] {
2300            timer.elapsed.set(elapsed);
2301            let mut delta = 0;
2302            while delta < WHEEL_TIMEOUT_CUTOFF {
2303                let (idx, expiry) = timer.calc_wheel_index(elapsed + delta, delta);
2304                let lvl = (idx / LVL_SIZE as usize) as u64;
2305                assert!(expiry > elapsed + delta, "{elapsed} {delta} {expiry}");
2306                assert!(
2307                    expiry <= elapsed + delta + lvl_gran(lvl),
2308                    "{elapsed} {delta} {expiry}"
2309                );
2310                assert_eq!(expiry % lvl_gran(lvl), 0);
2311                assert_eq!(
2312                    ((expiry >> lvl_shift(lvl)) & LVL_MASK) as usize,
2313                    idx % LVL_SIZE as usize
2314                );
2315                delta = delta * 2 + 1;
2316            }
2317
2318            // clamped to the capacity of the wheel
2319            let (_, expiry) =
2320                timer.calc_wheel_index(elapsed + u64::from(u32::MAX), u64::from(u32::MAX));
2321            assert!(expiry <= elapsed + WHEEL_TIMEOUT_CUTOFF);
2322        }
2323    }
2324
2325    /// STATEMENT: Next-bucket selection visits occupied buckets in increasing expiry order.
2326    ///
2327    /// HOW:
2328    /// - Insert timers with unsorted delays and compute their expected sorted expiries.
2329    /// - Expire each selected bucket and verify its entry unlinks and the final occupancy is empty.
2330    #[test]
2331    fn test_next_pending_bucket() {
2332        let timer = Timer::new(None);
2333        timer.elapsed.set(1000);
2334
2335        timer.with_wheel(|w| {
2336            assert_eq!(timer.next_pending_bucket(w), None);
2337
2338            let mut expected = Vec::new();
2339            for delta in [5000, 30, 700, 100_000] {
2340                let (idx, expiry) = timer.calc_wheel_index(1000 + delta, delta);
2341                let no = w.timers.insert(entry());
2342                w.link(no, idx);
2343                expected.push((expiry, no));
2344            }
2345            expected.sort_unstable();
2346
2347            for (expiry, no) in expected {
2348                assert_eq!(timer.next_pending_bucket(w), Some(expiry));
2349                timer.elapsed.set(expiry);
2350                w.execute_expired_timers(expiry);
2351                assert!(w.timers[no].bucket.is_none());
2352            }
2353            assert_eq!(timer.next_pending_bucket(w), None);
2354            assert_eq!(w.occupied, [0; LVL_DEPTH as usize]);
2355        });
2356    }
2357
2358    /// STATEMENT: Linking, unlinking, and relinking keep bucket membership and occupancy consistent.
2359    ///
2360    /// HOW:
2361    /// - Link two entries to one bucket, remove one twice, and move the other to another level.
2362    /// - Check occupancy bits and membership after each step and after the final removal.
2363    #[test]
2364    fn test_unlink_relink() {
2365        let timer = Timer::new(None);
2366        timer.with_wheel(|w| {
2367            let a = w.timers.insert(entry());
2368            let b = w.timers.insert(entry());
2369            w.link(a, 3);
2370            w.link(b, 3);
2371            assert_eq!(w.occupied[0], 1 << 3);
2372
2373            assert!(w.unlink(a));
2374            assert!(!w.unlink(a));
2375            assert_eq!(w.occupied[0], 1 << 3);
2376
2377            w.relink(b, LVL_SIZE as usize + 5);
2378            assert_eq!(w.occupied[0], 0);
2379            assert_eq!(w.occupied[1], 1 << 5);
2380            assert_eq!(w.timers[b].bucket, Some(LVL_SIZE as u16 + 5));
2381
2382            assert!(w.unlink(b));
2383            assert_eq!(w.occupied, [0; LVL_DEPTH as usize]);
2384        });
2385    }
2386
2387    /// STATEMENT: Resetting a timer to zero promptly wakes its waiting task.
2388    ///
2389    /// HOW:
2390    /// - Reset a shared long timer from another task while selecting against a fallback sleep.
2391    /// - Require completion well before the fallback deadline.
2392    #[test]
2393    fn test_reset_zero_wakes_task() {
2394        block_on(async {
2395            let hnd = Rc::new(TimerHandle::new(10_000));
2396            let hnd2 = hnd.clone();
2397            crate::spawn(async move { hnd2.reset(0) });
2398
2399            // the sleep wakes the task if `reset(0)` does not
2400            let start = Instant::now();
2401            let mut fallback = std::pin::pin!(sleep(500));
2402            std::future::poll_fn(|cx| {
2403                if hnd.poll_elapsed(cx).is_ready() || fallback.as_mut().poll(cx).is_ready() {
2404                    Poll::Ready(())
2405                } else {
2406                    Poll::Pending
2407                }
2408            })
2409            .await;
2410            let elapsed = start.elapsed();
2411            assert!(elapsed < Duration::from_millis(100), "elapsed: {elapsed:?}");
2412        });
2413    }
2414
2415    /// STATEMENT: Dropping a timer driver preserves the other driver's state.
2416    ///
2417    /// HOW:
2418    /// - Drop the low-resolution driver and verify regular timer occupancy and flags remain.
2419    /// - Drop the regular driver and verify its timers clear while the low-resolution flag remains.
2420    #[test]
2421    fn test_driver_drop_keeps_other_driver() {
2422        let timer = Rc::new(Timer::new(None));
2423        let no = timer.with_wheel(|w| {
2424            let no = w.timers.insert(entry());
2425            w.link(no, 3);
2426            no
2427        });
2428        timer.next_expiry.set(3);
2429        timer.lowres_stime.set(Some(SystemTime::now()));
2430        timer.insert_flags(
2431            Flags::RUNNING | Flags::DRIVER_STARTED | Flags::LOWRES_DRIVER | Flags::LOWRES_TIMER,
2432        );
2433
2434        drop(LowresTimerDriver {
2435            timer: timer.clone(),
2436            generation: 0,
2437            sleep: Sleep::new(Instant::now()),
2438        });
2439        assert_eq!(timer.flags.get(), Flags::DRIVER_STARTED);
2440        assert!(timer.lowres_stime.get().is_none());
2441        // timers are still pending
2442        assert_eq!(timer.next_expiry.get(), 3);
2443        timer.with_wheel(|w| assert_eq!(w.timers[no].bucket, Some(3)));
2444
2445        timer.insert_flags(Flags::RUNNING | Flags::LOWRES_DRIVER);
2446        drop(TimerDriver {
2447            timer: timer.clone(),
2448            generation: 0,
2449            sleep: Sleep::new(Instant::now()),
2450            armed: None,
2451        });
2452        assert_eq!(timer.flags.get(), Flags::LOWRES_DRIVER);
2453        assert_eq!(timer.next_expiry.get(), u64::MAX);
2454        timer.with_wheel(|w| {
2455            assert!(w.timers[no].bucket.is_none());
2456            assert_eq!(w.occupied, [0; LVL_DEPTH as usize]);
2457        });
2458    }
2459
2460    /// STATEMENT: A new short timer uses current time after the runtime thread was blocked.
2461    ///
2462    /// HOW:
2463    /// - Populate the time cache, block the thread, then start a short sleep.
2464    /// - Measure with `Instant` and verify the sleep lasts at least its requested duration.
2465    #[test]
2466    fn test_short_timer_after_blocking() {
2467        block_on(async {
2468            let _hnd = sleep(10_000);
2469            let _ = crate::now();
2470
2471            // the lowres driver cannot run, the cached time goes stale
2472            std::thread::sleep(Duration::from_millis(100));
2473
2474            let start = Instant::now();
2475            sleep(50).await;
2476            let elapsed = start.elapsed();
2477            assert!(elapsed >= Duration::from_millis(50), "elapsed: {elapsed:?}");
2478        });
2479    }
2480
2481    /// STATEMENT: Cached `crate::now()` expires even when the timer wheel becomes idle.
2482    ///
2483    /// HOW:
2484    /// - Let existing timers finish, then wait for a channel message from a sleeping thread.
2485    /// - Compare `crate::now()` with the real clock and require less than 300 milliseconds of staleness.
2486    #[test]
2487    fn test_driver_cached_time_expires() {
2488        block_on(async {
2489            // the lowres timer of the cache populated at start fires first
2490            sleep(400).await;
2491
2492            // the wheel is idle, the thread waits for a non-timer event
2493            let (tx, rx) = async_channel::bounded(1);
2494            std::thread::spawn(move || {
2495                std::thread::sleep(Duration::from_millis(600));
2496                let _ = tx.send_blocking(());
2497            });
2498            rx.recv().await.unwrap();
2499
2500            let stale = Instant::now().saturating_duration_since(crate::now());
2501            assert!(stale < Duration::from_millis(300), "stale: {stale:?}");
2502        });
2503    }
2504
2505    /// STATEMENT: A delayed driver wake does not shift later timers by the same delay.
2506    ///
2507    /// HOW:
2508    /// - Start short and long sleeps, then block the thread past the short deadline.
2509    /// - Await both and check total elapsed time stays near the long timer's original deadline.
2510    #[test]
2511    fn test_late_wakeup_does_not_drift() {
2512        block_on(async {
2513            let start = Instant::now();
2514            let fut1 = sleep(50);
2515            let fut2 = sleep(600);
2516
2517            // block the thread, the driver wakes up ~450ms late for `fut1`.
2518            // `fut2` expires at ~620ms, with drift it would expire ~550ms after
2519            // the late wakeup, i.e. after ~1050ms. The bound leaves room for
2520            // scheduling latency on loaded machines.
2521            std::thread::sleep(Duration::from_millis(500));
2522            fut1.await;
2523            fut2.await;
2524
2525            let elapsed = start.elapsed();
2526            assert!(
2527                elapsed >= Duration::from_millis(600) && elapsed < Duration::from_millis(900),
2528                "elapsed: {elapsed:?}"
2529            );
2530        });
2531    }
2532
2533    /// STATEMENT: `TimerHandle` and `CallbackHandle` are neither `Send` nor `Sync`,
2534    /// so they cannot reach another thread's wheel.
2535    ///
2536    /// HOW:
2537    /// - Define a trait with a blanket impl for all types and a second impl for
2538    ///   `Send` (or `Sync`) types.
2539    /// - Resolve the trait item with an inferred parameter for `TimerHandle` and
2540    ///   `CallbackHandle`; it compiles only if exactly one impl applies, i.e. the
2541    ///   type is not `Send` (or `Sync`).
2542    #[test]
2543    fn timer_handle_is_thread_local() {
2544        trait NotSend<A> {
2545            fn check() {}
2546        }
2547        impl<T: ?Sized> NotSend<()> for T {}
2548        impl<T: ?Sized + Send> NotSend<u8> for T {}
2549        trait NotSync<A> {
2550            fn check() {}
2551        }
2552        impl<T: ?Sized> NotSync<()> for T {}
2553        impl<T: ?Sized + Sync> NotSync<u8> for T {}
2554
2555        <TimerHandle as NotSend<_>>::check();
2556        <TimerHandle as NotSync<_>>::check();
2557        <CallbackHandle as NotSend<_>>::check();
2558        <CallbackHandle as NotSync<_>>::check();
2559    }
2560
2561    /// STATEMENT: A native runtime caches the system time until it is `LOWRES_RESOLUTION` old.
2562    ///
2563    /// HOW:
2564    /// - Read the time of a native wheel, then read it again just before the cache expires.
2565    /// - Check both reads match and a read at `LOWRES_RESOLUTION` takes a new time.
2566    #[test]
2567    fn test_native_system_time_refresh() {
2568        let timer = Timer::new_native(None);
2569        let now = Instant::now();
2570        let first = timer.native_system_time(now);
2571        std::thread::sleep(Duration::from_millis(2));
2572        let almost = now + (LOWRES_RESOLUTION.saturating_sub(Duration::from_millis(1)));
2573        assert_eq!(timer.native_system_time(almost), first);
2574        let fresh = timer.native_system_time(now + LOWRES_RESOLUTION);
2575        assert!(fresh > first);
2576        assert_eq!(timer.native_system_time(now + LOWRES_RESOLUTION), fresh);
2577    }
2578
2579    /// STATEMENT: `reset_deadline` returns the instant the wheel actually expires the timer.
2580    ///
2581    /// HOW:
2582    /// - Reset a timer to 100ms and check the deadline is rounded up by at most one wheel unit.
2583    /// - Process the wheel just before the deadline and confirm the timer is pending.
2584    /// - Process it at the deadline and confirm the timer elapsed.
2585    #[test]
2586    fn test_reset_deadline() {
2587        let timer = timer_state();
2588        let handle = TimerHandle::new(0);
2589        let start = Instant::now();
2590        let deadline = handle.reset_deadline(100).unwrap();
2591        let unit = Duration::from_millis(to_millis(1, timer.units.get().unwrap()));
2592        assert!(deadline > start + Duration::from_millis(100));
2593        assert!(deadline <= Instant::now() + Duration::from_millis(100) + unit);
2594
2595        let generation = timer.generation.get();
2596        let _ = timer.process(
2597            deadline.checked_sub(Duration::from_nanos(1)).unwrap(),
2598            generation,
2599        );
2600        assert!(!handle.is_elapsed());
2601        let _ = timer.process(deadline, generation);
2602        assert!(handle.is_elapsed());
2603    }
2604}