Skip to main content

nautilus_common/
timer.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Real-time and virtual timers for use with `Clock` implementations.
17//!
18//! Defines [`TimeEvent`] values, callback and handler types, heap scheduling order, and the
19//! deterministic [`VirtualTimer`] iterator. The event and callback primitives are shared by virtual and
20//! live clock implementations.
21
22use std::{
23    cmp::Ordering,
24    fmt::{Debug, Display},
25    num::NonZeroU64,
26    rc::Rc,
27    sync::{
28        Arc,
29        atomic::{AtomicBool, Ordering as AtomicOrdering},
30    },
31};
32
33use nautilus_core::{
34    DurationNanos, UUID4, UnixNanos,
35    correctness::{FAILED, check_valid_string_utf8},
36};
37#[cfg(feature = "python")]
38use pyo3::{Py, PyAny, Python};
39use ustr::Ustr;
40
41/// Returns a positive nanosecond interval, coercing zero to one nanosecond.
42#[must_use]
43pub fn create_valid_interval(interval_ns: DurationNanos) -> NonZeroU64 {
44    NonZeroU64::new(interval_ns.as_u64()).unwrap_or(NonZeroU64::MIN)
45}
46
47/// Supplies UTC deadlines for a recurring timer independently of its delivery mechanism.
48///
49/// Implementations are immutable and may be shared between timers. Each timer owns its own
50/// occurrence index. Live timers can skip missed occurrences, while virtual timers replay each
51/// deadline. The deadline calculation must not invoke callbacks or alter clock state.
52pub trait TimerSchedule: Debug + Send + Sync {
53    /// Returns the nominal start timestamp, including an explicit UNIX epoch start.
54    fn start_time_ns(&self) -> UnixNanos;
55
56    /// Returns the first deadline strictly after `time_ns`, updating the occurrence index.
57    ///
58    /// `index` is a hint from the preceding calculation, initially zero. A fresh hint must also
59    /// work after a timer restart. Returns `None` when no later deadline is representable.
60    fn next_after(&self, time_ns: UnixNanos, index: &mut u64) -> Option<UnixNanos>;
61}
62
63/// The spacing or deadline source for consecutive events of a recurring timer.
64#[derive(Debug, Clone)]
65pub enum TimerInterval {
66    /// A fixed interval in nanoseconds.
67    Fixed(NonZeroU64),
68    /// A source of absolute UTC deadlines.
69    Schedule(Arc<dyn TimerSchedule>),
70}
71
72impl TimerInterval {
73    // Fixed intervals retain their nominal grid; schedule sources supply absolute deadlines
74    pub(crate) fn next_time_after(
75        &self,
76        start_time_ns: UnixNanos,
77        time_ns: UnixNanos,
78        index: &mut u64,
79    ) -> Option<UnixNanos> {
80        match self {
81            Self::Fixed(interval_ns) => {
82                *index =
83                    time_ns.saturating_duration_since(start_time_ns).as_u64() / interval_ns.get();
84                *index = index.checked_add(1)?;
85                start_time_ns
86                    .checked_add(DurationNanos::new(interval_ns.get().checked_mul(*index)?))
87            }
88            Self::Schedule(schedule) => schedule
89                .next_after(time_ns, index)
90                .filter(|next| *next > time_ns),
91        }
92    }
93}
94
95impl From<NonZeroU64> for TimerInterval {
96    fn from(value: NonZeroU64) -> Self {
97        Self::Fixed(value)
98    }
99}
100
101#[repr(C)]
102#[derive(Clone, Debug, PartialEq, Eq)]
103#[cfg_attr(
104    feature = "python",
105    pyo3::pyclass(module = "nautilus_trader.common", from_py_object)
106)]
107#[cfg_attr(
108    feature = "python",
109    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.common")
110)]
111/// Represents a named timer event.
112///
113/// `ts_event` records the scheduled event time, while `ts_init` records
114/// when the event instance was initialized.
115pub struct TimeEvent {
116    /// The timer event name.
117    pub name: Ustr,
118    /// The unique identifier for the event.
119    pub event_id: UUID4,
120    /// UNIX timestamp (nanoseconds) when the event is scheduled to occur.
121    pub ts_event: UnixNanos,
122    /// UNIX timestamp (nanoseconds) when the instance was initialized.
123    pub ts_init: UnixNanos,
124}
125
126impl TimeEvent {
127    /// Creates a time event with the supplied identity and timestamps.
128    #[must_use]
129    pub const fn new(name: Ustr, event_id: UUID4, ts_event: UnixNanos, ts_init: UnixNanos) -> Self {
130        Self {
131            name,
132            event_id,
133            ts_event,
134            ts_init,
135        }
136    }
137}
138
139impl Display for TimeEvent {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        write!(
142            f,
143            "{}(name={}, event_id={}, ts_event={}, ts_init={})",
144            stringify!(TimeEvent),
145            self.name,
146            self.event_id,
147            self.ts_event,
148            self.ts_init
149        )
150    }
151}
152
153/// Orders a [`TimeEvent`] for earliest-first scheduling in a
154/// [`BinaryHeap`](std::collections::BinaryHeap).
155///
156/// The reversed ordering makes the heap pop events in ascending order by `ts_event`, then `name`,
157/// `ts_init`, and `event_id`.
158#[repr(transparent)] // Guarantees zero-cost abstraction with identical memory layout
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub struct ScheduledTimeEvent(
161    /// The time event to schedule.
162    pub TimeEvent,
163);
164
165impl ScheduledTimeEvent {
166    /// Creates a scheduled wrapper for `event`.
167    #[must_use]
168    pub const fn new(event: TimeEvent) -> Self {
169        Self(event)
170    }
171
172    /// Returns the wrapped time event.
173    #[must_use]
174    pub fn into_inner(self) -> TimeEvent {
175        self.0
176    }
177}
178
179impl PartialOrd for ScheduledTimeEvent {
180    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
181        Some(self.cmp(other))
182    }
183}
184
185impl Ord for ScheduledTimeEvent {
186    fn cmp(&self, other: &Self) -> Ordering {
187        // Reverse order for max heap: earlier timestamps have higher priority
188        cmp_time_events(&other.0, &self.0)
189    }
190}
191
192#[cfg(feature = "python")]
193/// Wraps a Python callable that handles time events.
194pub struct PythonTimeEventCallback {
195    callback: Py<PyAny>,
196    cancellations: Vec<Arc<AtomicBool>>,
197}
198
199#[cfg(feature = "python")]
200impl PythonTimeEventCallback {
201    /// Wraps a Python callable as a time event callback.
202    #[must_use]
203    pub const fn new(callback: Py<PyAny>) -> Self {
204        Self {
205            callback,
206            cancellations: Vec::new(),
207        }
208    }
209
210    /// Invokes the Python callback for `event`.
211    ///
212    /// Logs and suppresses any exception raised by the callback.
213    pub fn call(&self, event: TimeEvent) {
214        Python::attach(|py| {
215            if self
216                .cancellations
217                .iter()
218                .any(|canceled| canceled.load(AtomicOrdering::Acquire))
219            {
220                return;
221            }
222
223            if let Err(e) = self.callback.call1(py, (event,)) {
224                let exception = crate::python::logging::format_exception(&e);
225
226                log::error!("Python time event callback raised exception:\n{exception}");
227            }
228        });
229    }
230}
231
232#[cfg(feature = "python")]
233impl Debug for PythonTimeEventCallback {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct(stringify!(PythonTimeEventCallback))
236            .finish_non_exhaustive()
237    }
238}
239
240#[derive(Clone)]
241/// Represents a callback invoked for time events.
242///
243/// # Variants
244///
245/// - `Python`: For Python callbacks (requires `python` feature).
246/// - `Rust`: Thread-safe callbacks using `Arc`. Use when the closure is `Send + Sync`.
247/// - `RustLocal`: Single-threaded callbacks using `Rc`. Use when capturing `Rc<RefCell<...>>`.
248///
249/// # Choosing Between `Rust` and `RustLocal`
250///
251/// Use `Rust` (thread-safe) when:
252/// - The callback does not capture `Rc<RefCell<...>>` or other non-`Send` types.
253/// - The closure is `Send + Sync` (most simple closures qualify).
254///
255/// Use `RustLocal` when:
256/// - The callback captures `Rc<RefCell<...>>` for shared mutable state.
257/// - Thread safety constraints prevent using `Arc`.
258///
259/// `RustLocal` works with `VirtualClock` and with `LiveClock` when its event channel
260/// is drained on the callback's originating thread.
261///
262/// # Automatic Conversion
263///
264/// - Closures that are `Fn + Send + Sync + 'static` automatically convert to `Rust`.
265/// - `Rc<dyn Fn(TimeEvent)>` converts to `RustLocal`.
266/// - `Arc<dyn Fn(TimeEvent) + Send + Sync>` converts to `Rust`.
267pub enum TimeEventCallback {
268    /// Python callable for use from Python via PyO3.
269    #[cfg(feature = "python")]
270    Python(Arc<PythonTimeEventCallback>),
271    /// Thread-safe Rust callback using `Arc` (`Send + Sync`).
272    Rust(Arc<dyn Fn(TimeEvent) + Send + Sync>),
273    /// Local Rust callback using `Rc` (not `Send`/`Sync`).
274    RustLocal(Rc<dyn Fn(TimeEvent)>),
275}
276
277impl Debug for TimeEventCallback {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        match self {
280            #[cfg(feature = "python")]
281            Self::Python(_) => f.write_str("Python callback"),
282            Self::Rust(_) => f.write_str("Rust callback (thread-safe)"),
283            Self::RustLocal(_) => f.write_str("Rust callback (local)"),
284        }
285    }
286}
287
288impl TimeEventCallback {
289    /// Returns `true` if this is a local (non-thread-safe) Rust callback.
290    ///
291    /// Local callbacks use `Rc` internally and require creation, cloning, dropping,
292    /// and invocation to stay on the originating thread.
293    #[must_use]
294    pub const fn is_local(&self) -> bool {
295        matches!(self, Self::RustLocal(_))
296    }
297
298    /// Invokes the callback for the given `TimeEvent`.
299    ///
300    /// For Python callbacks, exceptions are logged as errors rather than panicking.
301    ///
302    /// # Panics
303    ///
304    /// Panics if a Rust callback panics. The panic propagates to the caller.
305    pub fn call(&self, event: TimeEvent) {
306        match self {
307            #[cfg(feature = "python")]
308            Self::Python(callback) => callback.call(event),
309            Self::Rust(callback) => callback(event),
310            Self::RustLocal(callback) => callback(event),
311        }
312    }
313
314    pub(crate) fn with_cancellation(self, canceled: Arc<AtomicBool>) -> Self {
315        match self {
316            #[cfg(feature = "python")]
317            Self::Python(callback) => Python::attach(|py| {
318                let mut cancellations = callback.cancellations.clone();
319                cancellations.push(canceled);
320                let callback = callback.callback.clone_ref(py);
321                Self::Python(Arc::new(PythonTimeEventCallback {
322                    callback,
323                    cancellations,
324                }))
325            }),
326            Self::Rust(callback) => Self::from(move |event| {
327                if canceled.load(AtomicOrdering::Acquire) {
328                    return;
329                }
330
331                callback(event);
332            }),
333            Self::RustLocal(callback) => Self::RustLocal(Rc::new(move |event| {
334                if canceled.load(AtomicOrdering::Acquire) {
335                    return;
336                }
337
338                callback(event);
339            })),
340        }
341    }
342}
343
344impl<F> From<F> for TimeEventCallback
345where
346    F: Fn(TimeEvent) + Send + Sync + 'static,
347{
348    fn from(value: F) -> Self {
349        Self::Rust(Arc::new(value))
350    }
351}
352
353impl From<Arc<dyn Fn(TimeEvent) + Send + Sync>> for TimeEventCallback {
354    fn from(value: Arc<dyn Fn(TimeEvent) + Send + Sync>) -> Self {
355        Self::Rust(value)
356    }
357}
358
359impl From<Rc<dyn Fn(TimeEvent)>> for TimeEventCallback {
360    fn from(value: Rc<dyn Fn(TimeEvent)>) -> Self {
361        Self::RustLocal(value)
362    }
363}
364
365#[cfg(feature = "python")]
366impl From<Py<PyAny>> for TimeEventCallback {
367    fn from(value: Py<PyAny>) -> Self {
368        Self::from_python_time_event(value)
369    }
370}
371
372#[cfg(feature = "python")]
373impl TimeEventCallback {
374    /// Creates a Python callback that receives a PyO3 `TimeEvent`.
375    #[must_use]
376    pub fn from_python_time_event(callback: Py<PyAny>) -> Self {
377        Self::Python(Arc::new(PythonTimeEventCallback::new(callback)))
378    }
379}
380
381#[repr(C)]
382#[derive(Clone, Debug)]
383/// Pairs a [`TimeEvent`] with its callback for ordered dispatch.
384///
385/// Natural ordering is ascending by `ts_event`, then `name`, `ts_init`, and `event_id`.
386pub struct TimeEventHandler {
387    /// The time event.
388    pub event: TimeEvent,
389    /// The callable handler for the event.
390    pub callback: TimeEventCallback,
391}
392
393impl TimeEventHandler {
394    /// Creates a handler for `event` and `callback`.
395    #[must_use]
396    pub const fn new(event: TimeEvent, callback: TimeEventCallback) -> Self {
397        Self { event, callback }
398    }
399
400    /// Dispatches the event to the installed message-bus tap, then invokes its callback.
401    ///
402    /// # Panics
403    ///
404    /// Panics if the message-bus tap or a Rust callback panics. The panic propagates to the caller.
405    pub fn run(self) {
406        let Self { event, callback } = self;
407        crate::msgbus::dispatch_tap_time_event(&event);
408        callback.call(event);
409    }
410}
411
412impl PartialOrd for TimeEventHandler {
413    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
414        Some(self.cmp(other))
415    }
416}
417
418impl PartialEq for TimeEventHandler {
419    fn eq(&self, other: &Self) -> bool {
420        self.cmp(other).is_eq()
421    }
422}
423
424impl Eq for TimeEventHandler {}
425
426impl Ord for TimeEventHandler {
427    fn cmp(&self, other: &Self) -> Ordering {
428        cmp_time_events(&self.event, &other.event)
429    }
430}
431
432fn cmp_time_events(left: &TimeEvent, right: &TimeEvent) -> Ordering {
433    left.ts_event
434        .cmp(&right.ts_event)
435        .then_with(|| left.name.cmp(&right.name))
436        .then_with(|| left.ts_init.cmp(&right.ts_init))
437        .then_with(|| left.event_id.as_str().cmp(right.event_id.as_str()))
438}
439
440pub(crate) trait Timer {
441    fn is_expired(&self) -> bool;
442    fn cancel(&mut self);
443}
444
445/// A deterministic interval timer for use with a [`VirtualClock`](crate::clock::VirtualClock).
446///
447/// The timer generates scheduled events through an optional inclusive stop time as its iterator is
448/// consumed.
449#[derive(Clone, Debug)]
450pub struct VirtualTimer {
451    /// The name of the timer.
452    pub name: Ustr,
453    /// The fixed interval or source of UTC deadlines.
454    pub interval: TimerInterval,
455    /// The start time of the timer in UNIX nanoseconds.
456    pub start_time_ns: UnixNanos,
457    /// The optional inclusive stop time of the timer in UNIX nanoseconds.
458    pub stop_time_ns: Option<UnixNanos>,
459    /// Whether the first event fires at the start time instead of after one interval.
460    pub fire_immediately: bool,
461    next_time_ns: UnixNanos,
462    next_index: u64,
463    is_expired: bool,
464}
465
466impl VirtualTimer {
467    /// Creates a virtual timer with the supplied schedule.
468    ///
469    /// # Panics
470    ///
471    /// Panics if:
472    /// - `name` is not a valid string.
473    /// - `fire_immediately` is `false` and there is no valid deadline after `start_time_ns`.
474    #[must_use]
475    pub fn new(
476        name: Ustr,
477        interval: impl Into<TimerInterval>,
478        start_time_ns: UnixNanos,
479        stop_time_ns: Option<UnixNanos>,
480        fire_immediately: bool,
481    ) -> Self {
482        check_valid_string_utf8(name, stringify!(name)).expect(FAILED);
483
484        let interval = interval.into();
485        let mut next_index = 0;
486
487        let next_time_ns = if fire_immediately {
488            start_time_ns
489        } else {
490            interval
491                .next_time_after(start_time_ns, start_time_ns, &mut next_index)
492                .expect("first timer event should be within the UnixNanos range")
493        };
494
495        Self {
496            name,
497            interval,
498            start_time_ns,
499            stop_time_ns,
500            fire_immediately,
501            next_time_ns,
502            next_index,
503            is_expired: false,
504        }
505    }
506
507    /// Returns the next time in UNIX nanoseconds when the timer will fire.
508    #[must_use]
509    pub const fn next_time_ns(&self) -> UnixNanos {
510        self.next_time_ns
511    }
512
513    /// Returns whether the timer is expired.
514    #[must_use]
515    pub const fn is_expired(&self) -> bool {
516        self.is_expired
517    }
518
519    /// Returns a lazy iterator over events scheduled at or before `to_time_ns`.
520    ///
521    /// Consuming the iterator advances the timer. Events at `to_time_ns` and at the configured stop
522    /// time are included.
523    pub fn advance(&mut self, to_time_ns: UnixNanos) -> impl Iterator<Item = TimeEvent> + '_ {
524        std::iter::from_fn(move || {
525            if self.next_time_ns > to_time_ns {
526                return None;
527            }
528
529            self.next().map(|(event, _)| event)
530        })
531    }
532
533    /// Cancels the timer so it produces no further events.
534    pub const fn cancel(&mut self) {
535        self.is_expired = true;
536    }
537}
538
539impl Timer for VirtualTimer {
540    fn is_expired(&self) -> bool {
541        Self::is_expired(self)
542    }
543
544    fn cancel(&mut self) {
545        Self::cancel(self);
546    }
547}
548
549impl Iterator for VirtualTimer {
550    type Item = (TimeEvent, UnixNanos);
551
552    fn next(&mut self) -> Option<Self::Item> {
553        if self.is_expired {
554            return None;
555        }
556
557        // Check if current event would exceed stop time before creating the event
558        if let Some(stop_time_ns) = self.stop_time_ns
559            && self.next_time_ns > stop_time_ns
560        {
561            self.is_expired = true;
562            return None;
563        }
564
565        let event_time_ns = self.next_time_ns;
566
567        let item = (
568            TimeEvent {
569                name: self.name,
570                event_id: UUID4::new(),
571                ts_event: event_time_ns,
572                ts_init: event_time_ns,
573            },
574            event_time_ns,
575        );
576
577        if let Some(following_time_ns) =
578            self.interval
579                .next_time_after(self.start_time_ns, event_time_ns, &mut self.next_index)
580        {
581            self.next_time_ns = following_time_ns;
582        } else {
583            self.is_expired = true;
584        }
585
586        if self.stop_time_ns == Some(event_time_ns) {
587            self.is_expired = true;
588        }
589
590        Some(item)
591    }
592}
593
594#[cfg(test)]
595mod tests {
596    use std::{cell::RefCell, collections::BinaryHeap, num::NonZeroU64, rc::Rc, sync::Arc};
597
598    use jiff::{Span, Timestamp};
599    use nautilus_core::{DurationNanos, UUID4, UnixNanos, datetime::get_timezone};
600    #[cfg(feature = "python")]
601    use pyo3::{
602        Bound, PyResult, Python,
603        ffi::c_str,
604        types::{
605            PyAnyMethods, PyCFunction, PyDict, PyList, PyListMethods, PyModule, PyTuple,
606            PyTupleMethods, PyTypeMethods,
607        },
608    };
609    use rstest::*;
610    use ustr::Ustr;
611
612    use super::{
613        ScheduledTimeEvent, TimeEvent, TimeEventCallback, TimeEventHandler, TimerInterval,
614        VirtualTimer, create_valid_interval,
615    };
616    #[cfg(feature = "python")]
617    use crate::logging::{
618        arm_shutdown_on_error, disarm_shutdown_on_error, init_logging,
619        take_shutdown_on_error_trigger,
620    };
621    use crate::{
622        calendar::CalendarSchedule,
623        msgbus::{BusTap, Endpoint, MStr, MessagingSwitchboard, Topic, clear_bus_tap, set_bus_tap},
624    };
625
626    #[rstest]
627    #[case(0, 1)]
628    #[case(1, 1)]
629    #[case(25, 25)]
630    fn test_create_valid_interval(#[case] interval_ns: u64, #[case] expected: u64) {
631        assert_eq!(
632            create_valid_interval(DurationNanos::new(interval_ns)).get(),
633            expected
634        );
635    }
636
637    fn utc_nanos(time: &str) -> UnixNanos {
638        UnixNanos::from(time.parse::<Timestamp>().unwrap())
639    }
640
641    #[rstest]
642    #[case::next_interval(100, 100, 0, Some(110), 1)]
643    #[case::skips_elapsed_intervals(100, 135, 0, Some(140), 4)]
644    #[case::scheduled_time_equal_to_time_is_skipped(100, 140, 3, Some(150), 5)]
645    #[case::unrepresentable(u64::MAX - 5, u64::MAX - 5, 0, None, 1)]
646    fn test_timer_interval_fixed_next_time_after(
647        #[case] start_time_ns: u64,
648        #[case] time_ns: u64,
649        #[case] index: u64,
650        #[case] expected: Option<u64>,
651        #[case] expected_index: u64,
652    ) {
653        let interval = TimerInterval::Fixed(NonZeroU64::new(10).unwrap());
654        let mut index = index;
655
656        let next_time_ns = interval.next_time_after(
657            UnixNanos::from(start_time_ns),
658            UnixNanos::from(time_ns),
659            &mut index,
660        );
661
662        assert_eq!(next_time_ns, expected.map(UnixNanos::from));
663        assert_eq!(index, expected_index);
664    }
665
666    #[rstest]
667    fn test_virtual_timer_calendar_advance_keeps_local_time() {
668        let mut timer = VirtualTimer::new(
669            Ustr::from("TEST_TIMER"),
670            TimerInterval::Schedule(Arc::new(
671                CalendarSchedule::new(
672                    &utc_nanos("2026-10-23T07:00:00Z")
673                        .to_datetime_utc()
674                        .to_zoned(get_timezone("Europe/London").unwrap()),
675                    Span::new().days(1),
676                )
677                .unwrap(),
678            )),
679            utc_nanos("2026-10-23T07:00:00Z"),
680            None,
681            false,
682        );
683
684        let events: Vec<UnixNanos> = timer
685            .advance(utc_nanos("2026-10-26T08:00:00Z"))
686            .map(|event| event.ts_event)
687            .collect();
688
689        assert_eq!(
690            events,
691            vec![
692                utc_nanos("2026-10-24T07:00:00Z"),
693                utc_nanos("2026-10-25T08:00:00Z"),
694                utc_nanos("2026-10-26T08:00:00Z"),
695            ]
696        );
697        assert_eq!(timer.next_time_ns(), utc_nanos("2026-10-27T08:00:00Z"));
698    }
699
700    #[rstest]
701    fn test_virtual_timer_advance_within_next_time_ns() {
702        let mut timer = VirtualTimer::new(
703            Ustr::from("TEST_TIMER"),
704            NonZeroU64::new(5).unwrap(),
705            UnixNanos::default(),
706            None,
707            false,
708        );
709        let _: Vec<TimeEvent> = timer.advance(UnixNanos::from(1)).collect();
710        let _: Vec<TimeEvent> = timer.advance(UnixNanos::from(2)).collect();
711        let _: Vec<TimeEvent> = timer.advance(UnixNanos::from(3)).collect();
712        assert_eq!(timer.advance(UnixNanos::from(4)).count(), 0);
713        assert_eq!(timer.next_time_ns, 5);
714        assert!(!timer.is_expired);
715    }
716
717    #[rstest]
718    fn test_virtual_timer_advance_up_to_next_time_ns() {
719        let mut timer = VirtualTimer::new(
720            Ustr::from("TEST_TIMER"),
721            NonZeroU64::new(1).unwrap(),
722            UnixNanos::default(),
723            None,
724            false,
725        );
726        assert_eq!(timer.advance(UnixNanos::from(1)).count(), 1);
727        assert!(!timer.is_expired);
728    }
729
730    #[rstest]
731    fn test_virtual_timer_advance_up_to_next_time_ns_with_stop_time() {
732        let mut timer = VirtualTimer::new(
733            Ustr::from("TEST_TIMER"),
734            NonZeroU64::new(1).unwrap(),
735            UnixNanos::default(),
736            Some(UnixNanos::from(2)),
737            false,
738        );
739        assert_eq!(timer.advance(UnixNanos::from(2)).count(), 2);
740        assert!(timer.is_expired);
741    }
742
743    #[rstest]
744    fn test_virtual_timer_advance_beyond_next_time_ns() {
745        let mut timer = VirtualTimer::new(
746            Ustr::from("TEST_TIMER"),
747            NonZeroU64::new(1).unwrap(),
748            UnixNanos::default(),
749            Some(UnixNanos::from(5)),
750            false,
751        );
752        assert_eq!(timer.advance(UnixNanos::from(5)).count(), 5);
753        assert!(timer.is_expired);
754    }
755
756    #[rstest]
757    fn test_virtual_timer_advance_beyond_stop_time() {
758        let mut timer = VirtualTimer::new(
759            Ustr::from("TEST_TIMER"),
760            NonZeroU64::new(1).unwrap(),
761            UnixNanos::default(),
762            Some(UnixNanos::from(5)),
763            false,
764        );
765        assert_eq!(timer.advance(UnixNanos::from(10)).count(), 5);
766        assert!(timer.is_expired);
767    }
768
769    #[rstest]
770    fn test_virtual_timer_advance_exact_boundary() {
771        let mut timer = VirtualTimer::new(
772            Ustr::from("TEST_TIMER"),
773            NonZeroU64::new(5).unwrap(),
774            UnixNanos::from(0),
775            None,
776            false,
777        );
778        assert_eq!(
779            timer.advance(UnixNanos::from(5)).count(),
780            1,
781            "Expected one event at the 5 ns boundary"
782        );
783        assert_eq!(
784            timer.advance(UnixNanos::from(10)).count(),
785            1,
786            "Expected one event at the 10 ns boundary"
787        );
788    }
789
790    #[rstest]
791    fn test_virtual_timer_fire_immediately_true() {
792        let mut timer = VirtualTimer::new(
793            Ustr::from("TEST_TIMER"),
794            NonZeroU64::new(5).unwrap(),
795            UnixNanos::from(10),
796            None,
797            true, // fire_immediately = true
798        );
799
800        // With fire_immediately=true, next_time_ns should be start_time_ns
801        assert_eq!(timer.next_time_ns(), UnixNanos::from(10));
802
803        // Advance to start time should produce an event
804        let events: Vec<TimeEvent> = timer.advance(UnixNanos::from(10)).collect();
805        assert_eq!(events.len(), 1);
806        assert_eq!(events[0].ts_event, UnixNanos::from(10));
807
808        // Next event should be at start_time + interval
809        assert_eq!(timer.next_time_ns(), UnixNanos::from(15));
810    }
811
812    #[rstest]
813    fn test_virtual_timer_fire_immediately_false() {
814        let mut timer = VirtualTimer::new(
815            Ustr::from("TEST_TIMER"),
816            NonZeroU64::new(5).unwrap(),
817            UnixNanos::from(10),
818            None,
819            false, // fire_immediately = false
820        );
821
822        // With fire_immediately=false, next_time_ns should be start_time_ns + interval
823        assert_eq!(timer.next_time_ns(), UnixNanos::from(15));
824
825        // Advance to start time should produce no events
826        assert_eq!(timer.advance(UnixNanos::from(10)).count(), 0);
827
828        // Advance to first interval should produce an event
829        let events: Vec<TimeEvent> = timer.advance(UnixNanos::from(15)).collect();
830        assert_eq!(events.len(), 1);
831        assert_eq!(events[0].ts_event, UnixNanos::from(15));
832    }
833
834    #[rstest]
835    fn test_time_event_handler_ordering_uses_tie_breakers() {
836        let callback = TimeEventCallback::from(|_: TimeEvent| {});
837
838        let later_name = TimeEventHandler::new(
839            TimeEvent::new(
840                Ustr::from("TIME_BAR_ESM4-2-MINUTE-ASK-INTERNAL"),
841                UUID4::from("00000000-0000-4000-8000-000000000003"),
842                100.into(),
843                100.into(),
844            ),
845            callback.clone(),
846        );
847        let earlier_name = TimeEventHandler::new(
848            TimeEvent::new(
849                Ustr::from("SPREAD_QUOTE_ESM4"),
850                UUID4::from("00000000-0000-4000-8000-000000000002"),
851                100.into(),
852                100.into(),
853            ),
854            callback.clone(),
855        );
856        let later_init = TimeEventHandler::new(
857            TimeEvent::new(
858                Ustr::from("SPREAD_QUOTE_ESM4"),
859                UUID4::from("00000000-0000-4000-8000-000000000004"),
860                100.into(),
861                101.into(),
862            ),
863            callback.clone(),
864        );
865        let later_id = TimeEventHandler::new(
866            TimeEvent::new(
867                Ustr::from("SPREAD_QUOTE_ESM4"),
868                UUID4::from("00000000-0000-4000-8000-000000000005"),
869                100.into(),
870                100.into(),
871            ),
872            callback,
873        );
874
875        assert!(earlier_name < later_name);
876        assert!(earlier_name < later_init);
877        assert!(earlier_name < later_id);
878        assert_ne!(earlier_name, later_id);
879    }
880
881    #[rstest]
882    fn test_scheduled_time_event_ordering_laws() {
883        let base = ScheduledTimeEvent::new(TimeEvent::new(
884            Ustr::from("ALPHA"),
885            UUID4::from("00000000-0000-4000-8000-000000000001"),
886            100.into(),
887            10.into(),
888        ));
889        let variants = [
890            base.clone(),
891            ScheduledTimeEvent::new(TimeEvent::new(
892                Ustr::from("BETA"),
893                base.0.event_id,
894                base.0.ts_event,
895                base.0.ts_init,
896            )),
897            ScheduledTimeEvent::new(TimeEvent::new(
898                base.0.name,
899                UUID4::from("00000000-0000-4000-8000-000000000002"),
900                base.0.ts_event,
901                base.0.ts_init,
902            )),
903            ScheduledTimeEvent::new(TimeEvent::new(
904                base.0.name,
905                base.0.event_id,
906                101.into(),
907                base.0.ts_init,
908            )),
909            ScheduledTimeEvent::new(TimeEvent::new(
910                base.0.name,
911                base.0.event_id,
912                base.0.ts_event,
913                11.into(),
914            )),
915        ];
916
917        for a in &variants {
918            for b in &variants {
919                assert_eq!(a == b, a.cmp(b).is_eq());
920                assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
921                assert_eq!(a.cmp(b), b.cmp(a).reverse());
922            }
923        }
924    }
925
926    #[rstest]
927    fn test_scheduled_time_event_heap_ordering() {
928        let expected = [
929            TimeEvent::new(
930                Ustr::from("ALPHA"),
931                UUID4::from("00000000-0000-4000-8000-000000000001"),
932                100.into(),
933                10.into(),
934            ),
935            TimeEvent::new(
936                Ustr::from("ALPHA"),
937                UUID4::from("00000000-0000-4000-8000-000000000002"),
938                100.into(),
939                10.into(),
940            ),
941            TimeEvent::new(
942                Ustr::from("ALPHA"),
943                UUID4::from("00000000-0000-4000-8000-000000000003"),
944                100.into(),
945                11.into(),
946            ),
947            TimeEvent::new(
948                Ustr::from("BETA"),
949                UUID4::from("00000000-0000-4000-8000-000000000004"),
950                100.into(),
951                10.into(),
952            ),
953            TimeEvent::new(
954                Ustr::from("ALPHA"),
955                UUID4::from("00000000-0000-4000-8000-000000000005"),
956                101.into(),
957                10.into(),
958            ),
959        ];
960        let insertion_order = [4, 1, 3, 0, 2];
961        let mut heap = BinaryHeap::new();
962
963        for index in insertion_order {
964            heap.push(ScheduledTimeEvent::new(expected[index].clone()));
965        }
966
967        let popped = std::iter::from_fn(|| heap.pop().map(ScheduledTimeEvent::into_inner))
968            .collect::<Vec<_>>();
969        assert_eq!(popped, expected);
970    }
971
972    #[cfg(feature = "python")]
973    #[rstest]
974    #[case(false)]
975    #[case(true)]
976    fn test_python_callback_exception_requests_shutdown(#[case] shutdown: bool) {
977        Python::initialize();
978        let _guard = init_logging(
979            "TRADER-001".into(),
980            UUID4::new(),
981            Default::default(),
982            Default::default(),
983        )
984        .unwrap();
985        Python::attach(|py| {
986            let module = PyModule::from_code(
987                py,
988                c_str!(
989                    r#"
990seen = []
991def callback(event):
992    seen.append(event.name)
993    raise RuntimeError("timer callback failure")
994"#
995                ),
996                c_str!("timer_callback.py"),
997                c_str!("timer_callback"),
998            )
999            .unwrap();
1000            let callback = TimeEventCallback::from_python_time_event(
1001                module.getattr("callback").unwrap().unbind(),
1002            );
1003
1004            let event = TimeEvent::new(
1005                Ustr::from("ALERT"),
1006                UUID4::new(),
1007                UnixNanos::from(10),
1008                UnixNanos::from(11),
1009            );
1010            arm_shutdown_on_error(shutdown);
1011            callback.call(event.clone());
1012            let trigger = take_shutdown_on_error_trigger();
1013            disarm_shutdown_on_error();
1014            callback.call(event);
1015            let seen = module
1016                .getattr("seen")
1017                .unwrap()
1018                .extract::<Vec<String>>()
1019                .unwrap();
1020
1021            assert_eq!(seen, ["ALERT", "ALERT"]);
1022
1023            if shutdown {
1024                let trigger = trigger.expect("timer exception must request shutdown");
1025                assert!(
1026                    trigger
1027                        .message
1028                        .contains("Python time event callback raised exception:")
1029                );
1030                assert!(trigger.message.contains("in callback"));
1031                assert!(
1032                    trigger
1033                        .message
1034                        .contains("RuntimeError: timer callback failure")
1035                );
1036            } else {
1037                assert_eq!(trigger, None);
1038            }
1039        });
1040    }
1041
1042    #[cfg(feature = "python")]
1043    #[rstest]
1044    fn test_python_callback_passes_time_event() {
1045        Python::initialize();
1046
1047        Python::attach(|py| {
1048            let seen = PyList::empty(py);
1049            let seen_obj = seen.clone().unbind().into_any();
1050
1051            let callback = new_sync_py_callback(
1052                py,
1053                move |args: &Bound<'_, PyTuple>,
1054                      _kwargs: Option<&Bound<'_, PyDict>>|
1055                      -> PyResult<()> {
1056                    let arg = args.get_item(0)?;
1057                    let type_name = arg.get_type().name()?.to_string();
1058                    Python::attach(|py| seen_obj.call_method1(py, "append", (type_name,)))?;
1059                    Ok(())
1060                },
1061            )
1062            .expect("callback should create")
1063            .into_any()
1064            .unbind();
1065
1066            let event = TimeEvent::new(
1067                Ustr::from("PY_CALLBACK_MODE"),
1068                UUID4::from("00000000-0000-4000-8000-000000000007"),
1069                UnixNanos::from(100),
1070                UnixNanos::from(99),
1071            );
1072
1073            TimeEventCallback::from_python_time_event(callback).call(event);
1074
1075            assert_eq!(seen.len(), 1);
1076            assert_eq!(
1077                seen.get_item(0).unwrap().extract::<String>().unwrap(),
1078                "TimeEvent"
1079            );
1080        });
1081    }
1082
1083    #[cfg(feature = "python")]
1084    fn new_sync_py_callback<F>(py: Python<'_>, closure: F) -> PyResult<Bound<'_, PyCFunction>>
1085    where
1086        F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> PyResult<()>
1087            + Send
1088            + Sync
1089            + 'static,
1090    {
1091        PyCFunction::new_closure(py, None, None, closure)
1092    }
1093
1094    #[derive(Default)]
1095    struct RecordingTimeEventTap {
1096        time_events: RefCell<Vec<(String, TimeEvent)>>,
1097    }
1098
1099    impl RecordingTimeEventTap {
1100        fn time_events(&self) -> Vec<(String, TimeEvent)> {
1101            self.time_events.borrow().clone()
1102        }
1103    }
1104
1105    impl BusTap for RecordingTimeEventTap {
1106        fn on_publish(&self, topic: MStr<Topic>, message: &dyn std::any::Any) {
1107            if let Some(event) = message.downcast_ref::<TimeEvent>() {
1108                self.time_events
1109                    .borrow_mut()
1110                    .push((topic.to_string(), event.clone()));
1111            }
1112        }
1113
1114        fn on_send(&self, _endpoint: MStr<Endpoint>, _message: &dyn std::any::Any) {}
1115    }
1116
1117    #[rstest]
1118    fn test_time_event_handler_run_dispatches_tap_before_callback() {
1119        let event = TimeEvent::new(
1120            Ustr::from("strategy.heartbeat"),
1121            UUID4::from("00000000-0000-4000-8000-000000000006"),
1122            UnixNanos::from(100),
1123            UnixNanos::from(99),
1124        );
1125        let tap = Rc::new(RecordingTimeEventTap::default());
1126        let callback_seen: Rc<RefCell<Vec<TimeEvent>>> = Rc::new(RefCell::new(Vec::new()));
1127        let expected_topic = MessagingSwitchboard::time_event_topic().to_string();
1128        let callback_expected = event.clone();
1129        let callback_expected_topic = expected_topic.clone();
1130        let callback_tap = Rc::clone(&tap);
1131        let callback_seen_ref = Rc::clone(&callback_seen);
1132
1133        let callback: Rc<dyn Fn(TimeEvent)> = Rc::new(move |callback_event| {
1134            assert_eq!(
1135                callback_tap.time_events(),
1136                vec![(callback_expected_topic.clone(), callback_expected.clone())],
1137            );
1138            callback_seen_ref.borrow_mut().push(callback_event);
1139        });
1140
1141        set_bus_tap(tap.clone());
1142        TimeEventHandler::new(event.clone(), TimeEventCallback::from(callback)).run();
1143        clear_bus_tap();
1144
1145        assert_eq!(tap.time_events(), vec![(expected_topic, event.clone())]);
1146        assert_eq!(*callback_seen.borrow(), vec![event]);
1147    }
1148
1149    use proptest::{prelude::*, test_runner::TestCaseResult};
1150
1151    #[derive(Clone, Debug)]
1152    enum TimerOperation {
1153        AdvanceTime(u64),
1154        Cancel,
1155    }
1156
1157    fn timer_operation_strategy() -> impl Strategy<Value = TimerOperation> {
1158        prop_oneof![
1159            8 => (0u64..=1000).prop_map(TimerOperation::AdvanceTime),
1160            2 => Just(TimerOperation::Cancel),
1161        ]
1162    }
1163
1164    fn timer_config_strategy() -> impl Strategy<Value = (u64, u64, Option<u64>, bool)> {
1165        (
1166            1u64..=1000,
1167            timer_start_time_strategy(),
1168            prop::option::of(0u64..=20_000),
1169            prop::bool::ANY,
1170        )
1171            .prop_map(
1172                |(interval_ns, start_time_ns, stop_after_ns, fire_immediately)| {
1173                    (
1174                        interval_ns,
1175                        start_time_ns,
1176                        stop_after_ns.map(|offset| start_time_ns + offset),
1177                        fire_immediately,
1178                    )
1179                },
1180            )
1181    }
1182
1183    fn timer_start_time_strategy() -> impl Strategy<Value = u64> {
1184        prop_oneof![
1185            6 => 0u64..=u64::MAX - TIMER_TIME_HEADROOM,
1186            2 => 0u64..=1_000_000,
1187            1 => Just(1_700_000_000_000_000_000),
1188            1 => Just(u64::MAX - TIMER_TIME_HEADROOM),
1189        ]
1190    }
1191
1192    fn timer_test_strategy()
1193    -> impl Strategy<Value = (Vec<TimerOperation>, (u64, u64, Option<u64>, bool))> {
1194        (
1195            prop::collection::vec(timer_operation_strategy(), 5..=75),
1196            timer_config_strategy(),
1197        )
1198    }
1199
1200    fn test_timer_with_operations(
1201        operations: Vec<TimerOperation>,
1202        (interval_ns, start_time_ns, stop_time_ns, fire_immediately): (u64, u64, Option<u64>, bool),
1203    ) -> TestCaseResult {
1204        let mut timer = VirtualTimer::new(
1205            Ustr::from("PROP_TEST_TIMER"),
1206            NonZeroU64::new(interval_ns).unwrap(),
1207            UnixNanos::from(start_time_ns),
1208            stop_time_ns.map(UnixNanos::from),
1209            fire_immediately,
1210        );
1211
1212        let mut current_time = start_time_ns;
1213
1214        let mut expected_next = if fire_immediately {
1215            start_time_ns
1216        } else {
1217            start_time_ns + interval_ns
1218        };
1219
1220        let mut expected_expired = false;
1221
1222        for operation in operations {
1223            match operation {
1224                TimerOperation::AdvanceTime(delta) => {
1225                    let to_time = current_time + delta;
1226                    let actual: Vec<(Ustr, u64, u64)> = timer
1227                        .advance(UnixNanos::from(to_time))
1228                        .map(|event| time_event_state(&event))
1229                        .collect();
1230                    let expected = expected_event_states(
1231                        expected_event_times(
1232                            to_time,
1233                            interval_ns,
1234                            stop_time_ns,
1235                            &mut expected_next,
1236                            &mut expected_expired,
1237                        ),
1238                        Ustr::from("PROP_TEST_TIMER"),
1239                    );
1240                    current_time = to_time;
1241
1242                    prop_assert_eq!(actual, expected);
1243                }
1244                TimerOperation::Cancel => {
1245                    timer.cancel();
1246                    expected_expired = true;
1247                }
1248            }
1249
1250            prop_assert_eq!(timer.is_expired(), expected_expired);
1251            prop_assert_eq!(timer.next_time_ns().as_u64(), expected_next);
1252        }
1253
1254        if !expected_expired && let Some(stop_time_ns) = stop_time_ns {
1255            let to_time = stop_time_ns.saturating_add(interval_ns);
1256            let actual: Vec<(Ustr, u64, u64)> = timer
1257                .advance(UnixNanos::from(to_time))
1258                .map(|event| time_event_state(&event))
1259                .collect();
1260            let expected = expected_event_states(
1261                expected_event_times(
1262                    to_time,
1263                    interval_ns,
1264                    Some(stop_time_ns),
1265                    &mut expected_next,
1266                    &mut expected_expired,
1267                ),
1268                Ustr::from("PROP_TEST_TIMER"),
1269            );
1270            prop_assert_eq!(actual, expected);
1271            prop_assert!(expected_expired);
1272            prop_assert!(timer.is_expired());
1273            prop_assert_eq!(timer.next_time_ns().as_u64(), expected_next);
1274        }
1275
1276        Ok(())
1277    }
1278
1279    fn expected_event_times(
1280        to_time: u64,
1281        interval_ns: u64,
1282        stop_time_ns: Option<u64>,
1283        next_time: &mut u64,
1284        is_expired: &mut bool,
1285    ) -> Vec<u64> {
1286        let mut events = Vec::new();
1287
1288        while !*is_expired && *next_time <= to_time {
1289            if let Some(stop_time_ns) = stop_time_ns
1290                && *next_time > stop_time_ns
1291            {
1292                *is_expired = true;
1293                break;
1294            }
1295
1296            let event_time = *next_time;
1297            events.push(event_time);
1298
1299            let Some(following_time) = event_time.checked_add(interval_ns) else {
1300                *is_expired = true;
1301                break;
1302            };
1303
1304            *next_time = following_time;
1305
1306            if Some(event_time) == stop_time_ns {
1307                *is_expired = true;
1308                break;
1309            }
1310        }
1311
1312        events
1313    }
1314
1315    proptest! {
1316        #[rstest]
1317        fn prop_timer_advance_operations((operations, config) in timer_test_strategy()) {
1318            test_timer_with_operations(operations, config)?;
1319        }
1320
1321        #[rstest]
1322        fn prop_timer_advance_batching_is_consistent(
1323            interval_ns in 1u64..=1000,
1324            start_time_ns in timer_start_time_strategy(),
1325            fire_immediately in prop::bool::ANY,
1326            advance_count in 1u64..=20,
1327        ) {
1328            let mut timer = VirtualTimer::new(
1329                Ustr::from("CONSISTENCY_TEST"),
1330                NonZeroU64::new(interval_ns).unwrap(),
1331                UnixNanos::from(start_time_ns),
1332                None, // No stop time for this test
1333                fire_immediately,
1334            );
1335
1336            let first_event_time = if fire_immediately { start_time_ns } else { start_time_ns + interval_ns };
1337            let final_event_time = first_event_time + interval_ns * (advance_count - 1);
1338            let expected = expected_event_states(
1339                (0..advance_count)
1340                    .map(|index| first_event_time + interval_ns * index)
1341                    .collect(),
1342                Ustr::from("CONSISTENCY_TEST"),
1343            );
1344
1345            let mut batched_timer = timer.clone();
1346            let batched: Vec<(Ustr, u64, u64)> = batched_timer
1347                .advance(UnixNanos::from(final_event_time))
1348                .map(|event| time_event_state(&event))
1349                .collect();
1350
1351            let mut stepped = Vec::new();
1352
1353            for event_time in
1354                (0..advance_count).map(|index| first_event_time + interval_ns * index)
1355            {
1356                stepped.extend(
1357                    timer
1358                        .advance(UnixNanos::from(event_time))
1359                        .map(|event| time_event_state(&event)),
1360                );
1361            }
1362
1363            prop_assert_eq!(&batched, &expected);
1364            prop_assert_eq!(&stepped, &expected);
1365            prop_assert_eq!(timer.next_time_ns(), batched_timer.next_time_ns());
1366            prop_assert_eq!(timer.is_expired(), batched_timer.is_expired());
1367        }
1368
1369        #[rstest]
1370        fn prop_timer_terminal_time_does_not_require_following_time(
1371            (interval_ns, event_headroom) in terminal_time_strategy(),
1372            fire_immediately in prop::bool::ANY,
1373            bounded in prop::bool::ANY,
1374        ) {
1375            let event_time_ns = u64::MAX - event_headroom;
1376            let start_time_ns = if fire_immediately {
1377                event_time_ns
1378            } else {
1379                event_time_ns - interval_ns
1380            };
1381            let mut timer = VirtualTimer::new(
1382                Ustr::from("TERMINAL_STOP_TEST"),
1383                NonZeroU64::new(interval_ns).unwrap(),
1384                UnixNanos::from(start_time_ns),
1385                bounded.then_some(UnixNanos::max()),
1386                fire_immediately,
1387            );
1388
1389            let events: Vec<(Ustr, u64, u64)> = timer
1390                .advance(UnixNanos::max())
1391                .map(|event| time_event_state(&event))
1392                .collect();
1393
1394            prop_assert_eq!(
1395                events,
1396                vec![(Ustr::from("TERMINAL_STOP_TEST"), event_time_ns, event_time_ns)]
1397            );
1398            prop_assert!(timer.is_expired());
1399            prop_assert_eq!(timer.next_time_ns(), UnixNanos::from(event_time_ns));
1400        }
1401    }
1402
1403    const TIMER_TIME_HEADROOM: u64 = 100_000;
1404
1405    fn time_event_state(event: &TimeEvent) -> (Ustr, u64, u64) {
1406        (event.name, event.ts_event.as_u64(), event.ts_init.as_u64())
1407    }
1408
1409    fn expected_event_states(times: Vec<u64>, name: Ustr) -> Vec<(Ustr, u64, u64)> {
1410        times.into_iter().map(|time| (name, time, time)).collect()
1411    }
1412
1413    fn terminal_time_strategy() -> impl Strategy<Value = (u64, u64)> {
1414        (1u64..=1000).prop_flat_map(|interval_ns| (Just(interval_ns), 0u64..interval_ns))
1415    }
1416}