moduvex-runtime 1.0.0

Custom async runtime for the Moduvex framework — epoll/kqueue/IOCP, hybrid threading
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Hierarchical timer wheel — O(1) insert/cancel, O(levels) tick.
//!
//! # Design
//! 6 levels × 64 slots. Each level covers a range of deadlines:
//!
//! | Level | Slot width | Total range |
//! |-------|-----------|-------------|
//! | 0     | 1 ms      | 64 ms       |
//! | 1     | 64 ms     | ~4 s        |
//! | 2     | ~4 s      | ~4 min      |
//! | 3     | ~4 min    | ~4.5 h      |
//! | 4     | ~4.5 h    | ~12 d       |
//! | 5     | ~12 d     | ~2 yr       |
//!
//! Timers beyond level 5 are clamped into the last slot of level 5.
//!
//! # Cascade
//! When the executor's "current tick" advances past a slot boundary at level N,
//! all timers in that slot are re-inserted at level N-1 (standard wheel cascade).

use std::collections::HashMap;
use std::task::Waker;
use std::time::Instant;

/// Number of slots per wheel level (must be a power of 2).
const SLOTS: usize = 64;
const SLOTS_MASK: u64 = (SLOTS - 1) as u64;

/// Number of wheel levels.
const LEVELS: usize = 6;

/// Width of level 0 in milliseconds (1 ms per slot).
const LEVEL0_MS: u64 = 1;

/// Width of each slot at level N = LEVEL0_MS * SLOTS^N.
fn slot_width_ms(level: usize) -> u64 {
    LEVEL0_MS * (SLOTS as u64).pow(level as u32)
}

// ── Timer entry ───────────────────────────────────────────────────────────────

/// A single pending timer.
#[derive(Debug)]
pub(crate) struct TimerEntry {
    /// Unique timer identifier (for cancellation).
    pub id: u64,
    /// Absolute deadline.
    pub deadline: Instant,
    /// Waker to call when the deadline passes.
    pub waker: Waker,
}

// ── TimerId ───────────────────────────────────────────────────────────────────

/// Opaque handle returned by `TimerWheel::insert`. Used to cancel a timer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimerId(u64);

// ── TimerWheel ────────────────────────────────────────────────────────────────

/// Hierarchical timer wheel.
///
/// All operations are relative to a monotonic millisecond counter derived from
/// an `Instant` origin captured at construction time.
pub struct TimerWheel {
    /// The `Instant` corresponding to tick 0.
    origin: Instant,
    /// `wheel[level][slot]` → list of timer entries.
    wheel: Vec<Vec<Vec<TimerEntry>>>,
    /// Index (slot, level) of each active timer for O(1) lookup on cancel.
    /// Maps timer id → (level, slot).
    index: HashMap<u64, (usize, usize)>,
    /// Monotonically increasing ID counter.
    next_id: u64,
    /// Last processed tick (milliseconds since origin).
    last_tick_ms: u64,
}

impl TimerWheel {
    /// Create a new timer wheel with `origin` as the zero point.
    pub(crate) fn new(origin: Instant) -> Self {
        // wheel[level][slot] = vec of entries
        let wheel = (0..LEVELS)
            .map(|_| (0..SLOTS).map(|_| Vec::new()).collect())
            .collect();
        Self {
            origin,
            wheel,
            index: HashMap::new(),
            next_id: 1,
            last_tick_ms: 0,
        }
    }

    /// Convert an `Instant` to milliseconds since origin, saturating at 0.
    fn instant_to_ms(&self, t: Instant) -> u64 {
        t.saturating_duration_since(self.origin)
            .as_millis()
            .try_into()
            .unwrap_or(u64::MAX)
    }

    /// Insert a timer that fires at `deadline`. Returns a `TimerId` for
    /// cancellation. The `waker` is called when the deadline passes.
    pub(crate) fn insert(&mut self, deadline: Instant, waker: Waker) -> TimerId {
        let id = self.next_id;
        self.next_id += 1;

        let deadline_ms = self.instant_to_ms(deadline);
        // Fire immediately if deadline already passed.
        let effective_ms = deadline_ms.max(self.last_tick_ms);

        let (level, slot) = self.level_slot(effective_ms);
        self.wheel[level][slot].push(TimerEntry {
            id,
            deadline,
            waker,
        });
        self.index.insert(id, (level, slot));

        TimerId(id)
    }

    /// Cancel the timer identified by `id`. Returns `true` if the timer was
    /// found and removed, `false` if it had already fired or was not found.
    pub(crate) fn cancel(&mut self, id: TimerId) -> bool {
        let Some((level, slot)) = self.index.remove(&id.0) else {
            return false;
        };
        let bucket = &mut self.wheel[level][slot];
        let before = bucket.len();
        bucket.retain(|e| e.id != id.0);
        bucket.len() < before
    }

    /// Advance the wheel to `now`, returning all wakers whose timers have
    /// expired. Callers must call `wake()` on each returned `Waker`.
    ///
    /// # Performance
    /// For large time jumps (e.g. 10 seconds), this method drains the range of
    /// level-0 slots in one pass rather than iterating ms-by-ms. Higher levels
    /// are cascaded only at their slot boundaries within the range. This keeps
    /// the cost proportional to the number of distinct slots crossed (O(slots))
    /// rather than elapsed milliseconds (O(ms)).
    pub(crate) fn tick(&mut self, now: Instant) -> Vec<Waker> {
        let now_ms = self.instant_to_ms(now);
        let mut fired: Vec<Waker> = Vec::new();

        let from = self.last_tick_ms;
        let to = now_ms;

        if to < from {
            return fired;
        }

        // ── Optimised path: drain all expired slots without ms-by-ms iteration ──
        //
        // Level 0 wraps every 64 slots (64 ms per revolution). If the jump
        // spans more than 64 ms we drain *all* level-0 slots (full revolution).
        // Otherwise we drain just the range [from_slot0..=to_slot0].
        let from_slot0 = (from & SLOTS_MASK) as usize;
        let to_slot0 = (to & SLOTS_MASK) as usize;
        let span = to.saturating_sub(from);

        if span >= SLOTS as u64 {
            // Full revolution or more — drain every level-0 slot.
            for slot in 0..SLOTS {
                self.drain_slot(0, slot, to, &mut fired);
            }
        } else if from_slot0 <= to_slot0 {
            // No wrap-around within this revolution.
            for slot in from_slot0..=to_slot0 {
                self.drain_slot(0, slot, to, &mut fired);
            }
        } else {
            // Wrap-around: drain [from_slot0..SLOTS) then [0..=to_slot0].
            for slot in from_slot0..SLOTS {
                self.drain_slot(0, slot, to, &mut fired);
            }
            for slot in 0..=to_slot0 {
                self.drain_slot(0, slot, to, &mut fired);
            }
        }

        // ── Cascade higher levels at their slot boundaries within [from, to] ──
        for level in 1..LEVELS {
            let width = slot_width_ms(level);
            // First boundary at or after `from`.
            let first_boundary = if from % width == 0 {
                from
            } else {
                (from / width + 1) * width
            };
            let mut boundary = first_boundary;
            while boundary <= to {
                let slot = ((boundary / width) & SLOTS_MASK) as usize;
                self.drain_slot(level, slot, to, &mut fired);
                boundary = match boundary.checked_add(width) {
                    Some(b) => b,
                    None => break,
                };
            }
        }

        self.last_tick_ms = to;
        fired
    }

    /// Drain all entries from `wheel[level][slot]`.
    ///
    /// Entries whose deadline has passed (≤ `now_ms`) are fired immediately.
    /// Entries still in the future are re-inserted at the correct wheel position.
    fn drain_slot(&mut self, level: usize, slot: usize, now_ms: u64, fired: &mut Vec<Waker>) {
        let entries = std::mem::take(&mut self.wheel[level][slot]);
        for entry in entries {
            self.index.remove(&entry.id);
            if self.instant_to_ms(entry.deadline) <= now_ms {
                fired.push(entry.waker);
            } else {
                self.insert_raw(entry);
            }
        }
    }

    /// Return the nearest deadline across all wheel slots, if any timers are pending.
    pub(crate) fn next_deadline(&self) -> Option<Instant> {
        let mut earliest: Option<Instant> = None;
        for level in &self.wheel {
            for slot in level {
                for entry in slot {
                    earliest = Some(match earliest {
                        None => entry.deadline,
                        Some(e) => e.min(entry.deadline),
                    });
                }
            }
        }
        earliest
    }

    /// Internal: insert a pre-existing `TimerEntry` into the correct bucket.
    fn insert_raw(&mut self, entry: TimerEntry) {
        let deadline_ms = self.instant_to_ms(entry.deadline);
        let effective_ms = deadline_ms.max(self.last_tick_ms);
        let (level, slot) = self.level_slot(effective_ms);
        self.index.insert(entry.id, (level, slot));
        self.wheel[level][slot].push(entry);
    }

    /// Compute the (level, slot) for a timer with deadline at `deadline_ms`.
    fn level_slot(&self, deadline_ms: u64) -> (usize, usize) {
        let delta = deadline_ms.saturating_sub(self.last_tick_ms);

        for level in 0..LEVELS {
            let width = slot_width_ms(level);
            let range = width * SLOTS as u64;
            if delta < range || level == LEVELS - 1 {
                // Compute absolute slot at this level.
                let slot = ((deadline_ms / width) & SLOTS_MASK) as usize;
                return (level, slot);
            }
        }
        // Unreachable: loop handles all cases.
        (LEVELS - 1, 0)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};
    use std::task::{RawWaker, RawWakerVTable};
    use std::time::Duration;

    fn make_flag_waker(flag: Arc<Mutex<bool>>) -> Waker {
        let data = Arc::into_raw(flag) as *const ();

        unsafe fn clone_w(p: *const ()) -> RawWaker {
            Arc::increment_strong_count(p as *const Mutex<bool>);
            RawWaker::new(p, &VT)
        }
        unsafe fn wake(p: *const ()) {
            *Arc::from_raw(p as *const Mutex<bool>).lock().unwrap() = true;
        }
        unsafe fn wake_ref(p: *const ()) {
            *(*(&p as *const *const () as *const Arc<Mutex<bool>>))
                .lock()
                .unwrap() = true;
        }
        unsafe fn drop_w(p: *const ()) {
            drop(Arc::from_raw(p as *const Mutex<bool>));
        }
        static VT: RawWakerVTable = RawWakerVTable::new(clone_w, wake, wake_ref, drop_w);

        // SAFETY: vtable satisfies the RawWaker contract.
        unsafe { Waker::from_raw(RawWaker::new(data, &VT)) }
    }

    #[test]
    fn insert_and_tick_fires_waker() {
        let flag = Arc::new(Mutex::new(false));
        let waker = make_flag_waker(Arc::clone(&flag));

        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);

        let deadline = origin + Duration::from_millis(50);
        wheel.insert(deadline, waker);

        // Tick before deadline — should not fire.
        let wakers = wheel.tick(origin + Duration::from_millis(30));
        assert!(wakers.is_empty());

        // Tick at/after deadline — should fire.
        let wakers = wheel.tick(origin + Duration::from_millis(60));
        assert_eq!(wakers.len(), 1);
        for w in wakers {
            w.wake();
        }
        assert!(*flag.lock().unwrap(), "waker must have fired");
    }

    #[test]
    fn cancel_prevents_firing() {
        let flag = Arc::new(Mutex::new(false));
        let waker = make_flag_waker(Arc::clone(&flag));

        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);

        let deadline = origin + Duration::from_millis(50);
        let id = wheel.insert(deadline, waker);
        let removed = wheel.cancel(id);
        assert!(removed, "cancel must return true for existing timer");

        // Tick past deadline — must not fire.
        let wakers = wheel.tick(origin + Duration::from_millis(100));
        assert!(wakers.is_empty(), "cancelled timer must not fire");
        assert!(!*flag.lock().unwrap());
    }

    #[test]
    fn zero_deadline_fires_on_next_tick() {
        let flag = Arc::new(Mutex::new(false));
        let waker = make_flag_waker(Arc::clone(&flag));

        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);

        // Deadline in the past (or now) → fires immediately on next tick.
        wheel.insert(origin, waker);
        let wakers = wheel.tick(origin + Duration::from_millis(1));
        assert_eq!(wakers.len(), 1);
        for w in wakers {
            w.wake();
        }
        assert!(*flag.lock().unwrap());
    }

    #[test]
    fn multiple_timers_fire_in_order() {
        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);
        let results = Arc::new(Mutex::new(Vec::<u32>::new()));

        for i in 0u32..5 {
            let r = Arc::clone(&results);
            let flag = Arc::new(Mutex::new(false));
            let _waker = make_flag_waker(Arc::clone(&flag));
            let _ = flag; // waker owns it now
                          // Re-build a waker that records the index.
            let data = Box::into_raw(Box::new((i, r))) as *const ();
            type Payload = (u32, Arc<Mutex<Vec<u32>>>);
            unsafe fn clone_p(p: *const ()) -> RawWaker {
                let b = Box::from_raw(p as *mut Payload);
                let cloned = Box::new((b.0, Arc::clone(&b.1)));
                std::mem::forget(b);
                RawWaker::new(Box::into_raw(cloned) as *const (), &PVT)
            }
            unsafe fn wake_p(p: *const ()) {
                let b = Box::from_raw(p as *mut Payload);
                b.1.lock().unwrap().push(b.0);
            }
            unsafe fn wake_p_ref(p: *const ()) {
                let b = Box::from_raw(p as *mut Payload);
                b.1.lock().unwrap().push(b.0);
                std::mem::forget(b);
            }
            unsafe fn drop_p(p: *const ()) {
                drop(Box::from_raw(p as *mut Payload));
            }
            static PVT: RawWakerVTable = RawWakerVTable::new(clone_p, wake_p, wake_p_ref, drop_p);
            // SAFETY: PVT satisfies the RawWaker contract; payload is Box-allocated.
            let waker2 = unsafe { Waker::from_raw(RawWaker::new(data, &PVT)) };

            wheel.insert(origin + Duration::from_millis((i as u64 + 1) * 10), waker2);
        }

        // Single tick past all deadlines.
        let wakers = wheel.tick(origin + Duration::from_millis(60));
        assert_eq!(wakers.len(), 5);
        for w in wakers {
            w.wake();
        }
        let v = results.lock().unwrap();
        assert_eq!(v.len(), 5);
    }

    #[test]
    fn next_deadline_returns_earliest() {
        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);

        let d1 = origin + Duration::from_millis(200);
        let d2 = origin + Duration::from_millis(50);

        let f1 = Arc::new(Mutex::new(false));
        let f2 = Arc::new(Mutex::new(false));
        wheel.insert(d1, make_flag_waker(Arc::clone(&f1)));
        wheel.insert(d2, make_flag_waker(Arc::clone(&f2)));

        let earliest = wheel.next_deadline().expect("should have a deadline");
        assert_eq!(earliest, d2, "next_deadline must return earliest");
    }

    #[test]
    fn large_time_jump_fires_timer_quickly() {
        // Regression test: a 10-second jump should not cause O(10_000) ms iterations.
        // We verify correctness; the performance gain is implicit (test must complete fast).
        let flag = Arc::new(Mutex::new(false));
        let waker = make_flag_waker(Arc::clone(&flag));

        let origin = Instant::now();
        let mut wheel = TimerWheel::new(origin);

        let deadline = origin + Duration::from_millis(50);
        wheel.insert(deadline, waker);

        // Jump 10 seconds ahead in a single tick call.
        let start = std::time::Instant::now();
        let wakers = wheel.tick(origin + Duration::from_secs(10));
        let elapsed = start.elapsed();

        assert_eq!(wakers.len(), 1, "timer must fire on 10s jump");
        for w in wakers {
            w.wake();
        }
        assert!(*flag.lock().unwrap(), "waker must have been called");
        // 10s ms-by-ms would take >10ms; optimised slot-drain takes <1ms.
        assert!(
            elapsed < Duration::from_millis(10),
            "10s tick must complete in <10ms, took {:?}",
            elapsed
        );
    }

    // ── Additional timer wheel tests ───────────────────────────────────────

    #[test]
    fn wheel_cancel_nonexistent_returns_false() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let fake_id = TimerId(9999);
        assert!(!w.cancel(fake_id));
    }

    #[test]
    fn wheel_cancel_already_fired_returns_false() {
        let flag = Arc::new(Mutex::new(false));
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let waker = make_flag_waker(Arc::clone(&flag));
        let id = w.insert(origin + Duration::from_millis(5), waker);
        let _ = w.tick(origin + Duration::from_millis(10)); // fires it
        assert!(!w.cancel(id)); // already gone from index
    }

    #[test]
    fn wheel_tick_backwards_is_noop() {
        let flag = Arc::new(Mutex::new(false));
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let waker = make_flag_waker(Arc::clone(&flag));
        w.insert(origin + Duration::from_millis(50), waker);
        let _ = w.tick(origin + Duration::from_millis(100)); // advance past
        // Now tick backwards — must not panic or double-fire
        let wakers = w.tick(origin + Duration::from_millis(10));
        assert!(wakers.is_empty());
    }

    #[test]
    fn wheel_multiple_timers_same_slot() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        for _ in 0..5 {
            let flag = Arc::new(Mutex::new(false));
            let waker = make_flag_waker(Arc::clone(&flag));
            w.insert(origin + Duration::from_millis(10), waker);
        }
        let wakers = w.tick(origin + Duration::from_millis(20));
        assert_eq!(wakers.len(), 5);
    }

    #[test]
    fn wheel_1000_timers_all_fire() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        for i in 0..1000u64 {
            let flag = Arc::new(Mutex::new(false));
            let waker = make_flag_waker(Arc::clone(&flag));
            w.insert(origin + Duration::from_millis(i % 100), waker);
        }
        let wakers = w.tick(origin + Duration::from_millis(200));
        assert_eq!(wakers.len(), 1000);
    }

    #[test]
    fn wheel_next_deadline_empty_returns_none() {
        let origin = Instant::now();
        let w = TimerWheel::new(origin);
        assert!(w.next_deadline().is_none());
    }

    #[test]
    fn wheel_next_deadline_after_cancel_updates() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let f1 = Arc::new(Mutex::new(false));
        let f2 = Arc::new(Mutex::new(false));
        let d1 = origin + Duration::from_millis(100);
        let d2 = origin + Duration::from_millis(200);
        let id1 = w.insert(d1, make_flag_waker(Arc::clone(&f1)));
        let _id2 = w.insert(d2, make_flag_waker(Arc::clone(&f2)));
        assert_eq!(w.next_deadline().unwrap(), d1);
        w.cancel(id1);
        assert_eq!(w.next_deadline().unwrap(), d2);
    }

    #[test]
    fn wheel_partial_tick_does_not_fire_future_timers() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let flag = Arc::new(Mutex::new(false));
        w.insert(
            origin + Duration::from_millis(100),
            make_flag_waker(Arc::clone(&flag)),
        );
        let wakers = w.tick(origin + Duration::from_millis(50));
        assert!(wakers.is_empty());
        assert!(!*flag.lock().unwrap());
    }

    #[test]
    fn wheel_level_boundary_cascades_correctly() {
        // A timer at 65ms should cascade from level 1 to level 0 during tick.
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let flag = Arc::new(Mutex::new(false));
        w.insert(
            origin + Duration::from_millis(65),
            make_flag_waker(Arc::clone(&flag)),
        );
        let wakers = w.tick(origin + Duration::from_millis(70));
        assert_eq!(wakers.len(), 1);
    }

    #[test]
    fn wheel_insert_past_deadline_fires_on_first_tick() {
        // Insert a timer with deadline in the past — should fire on next tick.
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let flag = Arc::new(Mutex::new(false));
        let past_deadline = origin; // zero deadline
        w.insert(past_deadline, make_flag_waker(Arc::clone(&flag)));
        let wakers = w.tick(origin + Duration::from_millis(1));
        assert!(!wakers.is_empty());
    }

    #[test]
    fn wheel_two_timers_different_deadlines_only_earlier_fires() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let f1 = Arc::new(Mutex::new(false));
        let f2 = Arc::new(Mutex::new(false));
        w.insert(
            origin + Duration::from_millis(10),
            make_flag_waker(Arc::clone(&f1)),
        );
        w.insert(
            origin + Duration::from_millis(50),
            make_flag_waker(Arc::clone(&f2)),
        );
        let wakers = w.tick(origin + Duration::from_millis(20));
        // Only the 10ms timer should fire
        assert_eq!(wakers.len(), 1);
        assert!(!*f2.lock().unwrap());
    }

    #[test]
    fn wheel_cancel_all_removes_from_index() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let mut ids = Vec::new();
        for i in 1..=5u64 {
            let flag = Arc::new(Mutex::new(false));
            let id = w.insert(origin + Duration::from_millis(i * 10), make_flag_waker(flag));
            ids.push(id);
        }
        // Cancel all
        for id in ids {
            assert!(w.cancel(id));
        }
        // No wakers should fire
        let wakers = w.tick(origin + Duration::from_millis(100));
        assert!(wakers.is_empty());
    }

    #[test]
    fn wheel_many_deadlines_at_different_levels() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        // Level 0: 1ms
        let f1 = Arc::new(Mutex::new(false));
        w.insert(origin + Duration::from_millis(1), make_flag_waker(Arc::clone(&f1)));
        // Level 1: 100ms
        let f2 = Arc::new(Mutex::new(false));
        w.insert(origin + Duration::from_millis(100), make_flag_waker(Arc::clone(&f2)));
        // Level 2: 5000ms (5s)
        let f3 = Arc::new(Mutex::new(false));
        w.insert(origin + Duration::from_millis(5000), make_flag_waker(Arc::clone(&f3)));

        // Tick to 200ms: first 2 should fire
        let wakers = w.tick(origin + Duration::from_millis(200));
        assert_eq!(wakers.len(), 2);
        // f3 should not have fired yet
        assert!(!*f3.lock().unwrap());

        // Tick to 6000ms: f3 should fire
        let wakers2 = w.tick(origin + Duration::from_millis(6000));
        assert_eq!(wakers2.len(), 1);
    }

    #[test]
    fn wheel_empty_tick_returns_empty_vec() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        // No timers inserted — tick should always return empty
        let wakers = w.tick(origin + Duration::from_millis(1000));
        assert!(wakers.is_empty());
    }

    #[test]
    fn wheel_same_tick_twice_second_empty() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let flag = Arc::new(Mutex::new(false));
        w.insert(origin + Duration::from_millis(10), make_flag_waker(Arc::clone(&flag)));
        let wakers1 = w.tick(origin + Duration::from_millis(20));
        assert_eq!(wakers1.len(), 1);
        // Same tick again — timer already fired
        let wakers2 = w.tick(origin + Duration::from_millis(20));
        assert!(wakers2.is_empty());
    }

    #[test]
    fn wheel_timer_id_uniqueness() {
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        let mut ids = std::collections::HashSet::new();
        for i in 0..10u64 {
            let flag = Arc::new(Mutex::new(false));
            let id = w.insert(origin + Duration::from_millis(i * 5 + 1), make_flag_waker(flag));
            // Each TimerId must be unique
            assert!(ids.insert(id));
        }
    }

    #[test]
    fn wheel_tick_advances_last_tick_ms() {
        // After ticking, the wheel should correctly handle subsequent ticks
        let origin = Instant::now();
        let mut w = TimerWheel::new(origin);
        // Insert at 200ms
        let flag = Arc::new(Mutex::new(false));
        w.insert(origin + Duration::from_millis(200), make_flag_waker(Arc::clone(&flag)));
        // Partial tick to 100ms — should not fire
        let wakers1 = w.tick(origin + Duration::from_millis(100));
        assert!(wakers1.is_empty());
        // Full tick to 250ms — should fire
        let wakers2 = w.tick(origin + Duration::from_millis(250));
        assert_eq!(wakers2.len(), 1);
    }
}