qubit-clock 0.10.1

Injectable wall and monotonic clocks with deterministic timers
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

use qubit_clock::{
    ManualMonotonicClock,
    MonotonicClock,
    MonotonicInstant,
    TimeError,
    Timer,
    TimerUnavailableError,
    TokioMonotonicClock,
    TokioRuntimeError,
    TokioTimer,
};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;

/// Environment flag selecting the isolated runtime-shutdown child path.
const TOKIO_SHUTDOWN_CHILD: &str = "QUBIT_CLOCK_TOKIO_SHUTDOWN_CHILD";

/// Exact integration-test path executed in the isolated child process.
const TOKIO_SHUTDOWN_TEST: &str = concat!(
    "timer::tokio_timer_tests::",
    "test_tokio_timer_reports_retained_runtime_shutdown_without_panicking",
);

/// Environment flag selecting post-shutdown registration in an isolated child.
const TOKIO_POST_SHUTDOWN_REGISTRATION_CHILD: &str =
    "QUBIT_CLOCK_TOKIO_POST_SHUTDOWN_REGISTRATION_CHILD";

/// Exact post-shutdown registration test path executed in the isolated child.
const TOKIO_POST_SHUTDOWN_REGISTRATION_TEST: &str = concat!(
    "timer::tokio_timer_tests::",
    "test_tokio_timer_registers_after_retained_runtime_shutdown_without_panicking",
);

/// Runs one runtime-shutdown case in an isolated child process.
///
/// # Parameters
///
/// * `child_variable` - Environment variable selecting the child path.
/// * `test_path` - Exact integration-test path executed in the child.
///
/// # Returns
///
/// `true` after the parent validates its child, or `false` inside that child.
///
/// # Panics
///
/// Panics when the child cannot start, fails, or invokes Tokio's shutdown panic
/// hook.
fn run_isolated_shutdown_test(child_variable: &str, test_path: &str) -> bool {
    if std::env::var_os(child_variable).is_some() {
        return false;
    }
    let output = Command::new(
        std::env::current_exe().expect("current test executable should exist"),
    )
    .args(["--exact", test_path, "--nocapture"])
    .env(child_variable, "1")
    .output()
    .expect("isolated shutdown test should start");
    assert!(
        output.status.success(),
        "isolated shutdown test should pass: {}",
        String::from_utf8_lossy(&output.stderr),
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains(
            "A Tokio 1.x context was found, but it is being shutdown."
        ),
        "runtime shutdown must not invoke the panic hook: {stderr}",
    );
    true
}

#[tokio::test(start_paused = true)]
async fn test_tokio_timer_fixes_deadline_before_first_poll() {
    let clock = TokioMonotonicClock::current();
    let timer = TokioTimer::from_clock(&clock);
    let future = timer
        .after(Duration::from_secs(8))
        .expect("Tokio deadline should register");

    tokio::time::advance(Duration::from_secs(8)).await;
    future.await.expect("Tokio timer should complete");
}

/// Verifies that relative deadline overflow remains a structured time error.
#[tokio::test]
async fn test_tokio_timer_after_reports_duration_overflow() {
    let timer = TokioTimer::current();

    assert!(matches!(
        timer.after(Duration::MAX),
        Err(TimeError::InstantOverflow),
    ));
}

/// Verifies that fallible timer construction reports a missing runtime.
#[test]
fn test_tokio_timer_try_current_reports_missing_runtime() {
    assert!(matches!(
        TokioTimer::try_current(),
        Err(TokioRuntimeError::NotEntered { .. }),
    ));
}

/// Verifies that infallible timer construction rejects a missing runtime.
#[test]
#[should_panic(expected = "cannot create Tokio timer")]
fn test_tokio_timer_current_panics_outside_runtime() {
    let _ = TokioTimer::current();
}

/// Verifies that fallible timer construction allocates a new clock domain.
#[tokio::test]
async fn test_tokio_timer_try_current_creates_independent_timer() {
    let timer = TokioTimer::try_current()
        .expect("entered runtime should create a Tokio timer");
    let other = TokioTimer::current();

    assert_ne!(timer.clock().now().domain(), other.clock().now().domain());
}

/// Verifies that a future deadline can be registered without an ambient
/// runtime and is driven by the retained handle.
#[test]
fn test_tokio_timer_registers_future_deadline_outside_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .start_paused(true)
        .build()
        .expect("runtime should build");
    let timer = TokioTimer::from_handle(runtime.handle().clone());
    let future = timer
        .after(Duration::from_secs(1))
        .expect("future deadline should register outside the runtime");

    runtime.block_on(async {
        tokio::time::advance(Duration::from_secs(1)).await;
        future.await.expect("Tokio timer should complete");
    });
}

/// Verifies that relative reached deadlines need no ambient runtime.
#[test]
fn test_tokio_timer_after_zero_succeeds_outside_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime should build");
    let timer = TokioTimer::from_handle(runtime.handle().clone());
    let future = timer
        .after(Duration::ZERO)
        .expect("zero delay should be ready without a time driver");

    runtime
        .block_on(future)
        .expect("reached Tokio timer should complete");
}

/// Verifies that Arc delegation preserves retained-runtime registration.
#[test]
fn test_tokio_timer_arc_after_uses_retained_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime should build");
    let timer: Arc<dyn Timer> =
        Arc::new(TokioTimer::from_handle(runtime.handle().clone()));
    let future = timer
        .after(Duration::ZERO)
        .expect("Arc timer should register through its retained runtime");

    runtime
        .block_on(future)
        .expect("Arc Tokio timer should complete");
}

/// Verifies that Box delegation preserves retained-runtime registration.
#[test]
fn test_tokio_timer_box_after_uses_retained_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime should build");
    let timer: Box<dyn Timer> =
        Box::new(TokioTimer::from_handle(runtime.handle().clone()));
    let future = timer
        .after(Duration::ZERO)
        .expect("boxed timer should register through its retained runtime");

    runtime
        .block_on(future)
        .expect("boxed Tokio timer should complete");
}

#[test]
fn test_tokio_timer_reports_disabled_time_driver_at_registration() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime should build");
    let timer = TokioTimer::from_handle(runtime.handle().clone());

    assert!(matches!(
        timer.after(Duration::from_secs(1)),
        Err(TimeError::TimerUnavailable {
            source: TimerUnavailableError::TimeDriverDisabled,
        }),
    ));
}

/// Verifies that reached deadlines do not require a Tokio time driver.
#[test]
fn test_tokio_timer_reached_deadline_needs_no_time_driver() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime should build");
    let timer = TokioTimer::from_handle(runtime.handle().clone());
    let deadline = timer.clock().now();
    let future = timer
        .at(deadline)
        .expect("reached deadline should be immediately ready");

    runtime
        .block_on(future)
        .expect("reached Tokio timer should complete");
}

/// Verifies that native overflow is reported before Tokio runtime validation.
#[test]
fn test_tokio_timer_reports_native_instant_overflow() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .build()
        .expect("runtime should build");
    let (timer, deadline) = runtime.block_on(async {
        let clock = TokioMonotonicClock::current();
        let deadline =
            MonotonicInstant::new(clock.now().domain(), Duration::MAX);
        (TokioTimer::from_clock(&clock), deadline)
    });

    let error = match timer.at(deadline) {
        Ok(_) => panic!("overflowing native deadline should fail"),
        Err(error) => error,
    };

    assert!(matches!(error, TimeError::InstantOverflow));
}

#[tokio::test]
async fn test_tokio_timer_returns_ready_future_for_reached_deadline() {
    let clock = TokioMonotonicClock::current();
    let timer = TokioTimer::from_clock(&clock);
    let deadline = clock.now();
    let future = timer
        .at(deadline)
        .expect("reached deadline should register successfully");

    future.await.expect("Tokio timer should complete");
}

#[tokio::test]
async fn test_tokio_timer_rejects_foreign_deadline_immediately() {
    let clock = TokioMonotonicClock::current();
    let timer = TokioTimer::from_clock(&clock);
    let foreign = ManualMonotonicClock::new().now();
    let expected = clock.now().domain();

    let error = match timer.at(foreign) {
        Ok(_) => panic!("foreign deadline should fail at registration"),
        Err(error) => error,
    };

    let TimeError::ClockDomainMismatch {
        expected: actual_expected,
        actual,
    } = error
    else {
        panic!("foreign deadline should report a domain mismatch");
    };
    assert_eq!(expected, actual_expected);
    assert_eq!(foreign.domain(), actual);
}

#[tokio::test]
async fn test_tokio_timer_retains_domain_after_source_is_dropped() {
    let (timer, domain) = {
        let clock = TokioMonotonicClock::current();
        let domain = clock.now().domain();
        (TokioTimer::from_clock(&clock), domain)
    };

    assert_eq!(domain, timer.clock().now().domain());
}

/// Verifies that the retained runtime, rather than the polling runtime, drives
/// a future deadline.
#[test]
fn test_tokio_timer_future_is_driven_by_retained_runtime() {
    let target = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .start_paused(true)
        .build()
        .expect("target runtime should build");
    let polling = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .start_paused(true)
        .build()
        .expect("polling runtime should build");
    let timer = TokioTimer::from_handle(target.handle().clone());
    let mut future = timer
        .after(Duration::from_secs(5))
        .expect("future deadline should register on the retained runtime");

    let completed = polling.block_on(async {
        tokio::select! {
            result = &mut future => {
                result.expect("retained-runtime timer should complete");
                true
            },
            () = tokio::time::sleep(Duration::from_secs(1)) => false,
        }
    });
    assert!(!completed, "advancing the polling runtime must not fire it");

    target.block_on(tokio::time::advance(Duration::from_secs(5)));
    polling
        .block_on(future)
        .expect("retained-runtime timer should complete");
}

/// Verifies runtime shutdown becomes a structured error without invoking the
/// process panic hook.
#[test]
fn test_tokio_timer_reports_retained_runtime_shutdown_without_panicking() {
    if run_isolated_shutdown_test(TOKIO_SHUTDOWN_CHILD, TOKIO_SHUTDOWN_TEST) {
        return;
    }

    let future = {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_time()
            .build()
            .expect("retained runtime should build");
        let timer = TokioTimer::from_handle(runtime.handle().clone());
        timer
            .after(Duration::from_secs(1))
            .expect("future deadline should register")
    };
    let polling = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .build()
        .expect("polling runtime should build");

    let error = polling
        .block_on(future)
        .expect_err("shutdown target runtime should fail the timer future");

    assert!(matches!(
        error,
        TimeError::TimerUnavailable {
            source: TimerUnavailableError::RuntimeShuttingDown,
        },
    ));
}

/// Verifies first registration after retained-runtime shutdown remains typed
/// and does not invoke the process panic hook.
#[test]
fn test_tokio_timer_registers_after_retained_runtime_shutdown_without_panicking()
 {
    if run_isolated_shutdown_test(
        TOKIO_POST_SHUTDOWN_REGISTRATION_CHILD,
        TOKIO_POST_SHUTDOWN_REGISTRATION_TEST,
    ) {
        return;
    }

    let timer = {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_time()
            .build()
            .expect("retained runtime should build");
        TokioTimer::from_handle(runtime.handle().clone())
    };
    let future = timer
        .after(Duration::from_secs(1))
        .expect("shutdown runtime should still create a diagnostic future");
    let polling = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .build()
        .expect("polling runtime should build");

    let error = polling
        .block_on(future)
        .expect_err("shutdown target runtime should fail the timer future");

    assert!(matches!(
        error,
        TimeError::TimerUnavailable {
            source: TimerUnavailableError::RuntimeShuttingDown,
        },
    ));
}

/// Verifies that domain validation does not depend on an ambient runtime.
#[test]
fn test_tokio_timer_reports_foreign_deadline_outside_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .build()
        .expect("runtime should build");
    let timer = TokioTimer::from_handle(runtime.handle().clone());
    let foreign = ManualMonotonicClock::new().now();

    assert!(matches!(
        timer.at(foreign),
        Err(TimeError::ClockDomainMismatch { .. }),
    ));
}