nautilus_core/time.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//! The core `AtomicTime` for real-time and static clocks.
17//!
18//! This module provides an atomic time abstraction that supports both real-time and static
19//! clocks. It ensures thread-safe operations and monotonic time retrieval with nanosecond precision.
20//!
21//! # Modes
22//!
23//! - **Real-time mode:** The clock continuously syncs with system wall-clock time (via
24//! [`SystemTime::now()`]). To ensure strict monotonic increments across multiple threads,
25//! the internal updates use an atomic compare-and-exchange loop (`time_since_epoch`).
26//! While this guarantees that every new timestamp is at least one nanosecond greater than the
27//! last, it may introduce higher contention if many threads call it heavily.
28//!
29//! - **Static mode:** The clock is manually controlled via [`AtomicTime::set_time`] or [`AtomicTime::increment_time`],
30//! which can be useful for simulations or backtesting. You can switch modes at runtime using
31//! [`AtomicTime::make_realtime`] or [`AtomicTime::make_static`]. In **static mode**, we use
32//! acquire/release semantics so that updates from one thread can be observed by another;
33//! however, we do not enforce strict global ordering for manual updates. If you need strong,
34//! multi-threaded ordering in **static mode**, you must coordinate higher-level synchronization yourself.
35
36use std::{
37 sync::{
38 OnceLock,
39 atomic::{AtomicBool, AtomicU64, Ordering},
40 },
41 time::{Duration, SystemTime, UNIX_EPOCH},
42};
43
44use crate::{
45 UnixNanos,
46 datetime::{NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND, NANOSECONDS_IN_SECOND},
47};
48
49/// Global atomic time in **real-time mode** for use across the system.
50///
51/// This clock operates in **real-time mode**, synchronizing with the system clock.
52/// It provides globally unique, strictly increasing timestamps across threads.
53pub static ATOMIC_CLOCK_REALTIME: OnceLock<AtomicTime> = OnceLock::new();
54
55/// Global atomic time in **static mode** for use across the system.
56///
57/// This clock operates in **static mode**, where the time value can be set or incremented
58/// manually. Useful for backtesting or simulated time control.
59pub static ATOMIC_CLOCK_STATIC: OnceLock<AtomicTime> = OnceLock::new();
60
61/// Returns a static reference to the global atomic clock in **real-time mode**.
62///
63/// This clock uses [`AtomicTime::time_since_epoch`] under the hood, ensuring strictly increasing
64/// timestamps across threads.
65pub fn get_atomic_clock_realtime() -> &'static AtomicTime {
66 ATOMIC_CLOCK_REALTIME.get_or_init(AtomicTime::default)
67}
68
69/// Returns a static reference to the global atomic clock in **static mode**.
70///
71/// This clock allows manual time control via [`AtomicTime::set_time`] or [`AtomicTime::increment_time`],
72/// and does not automatically sync with system time.
73pub fn get_atomic_clock_static() -> &'static AtomicTime {
74 ATOMIC_CLOCK_STATIC.get_or_init(|| AtomicTime::new(false, UnixNanos::default()))
75}
76
77/// Returns the duration since the UNIX epoch based on [`SystemTime::now()`].
78///
79/// # Panics
80///
81/// Panics if the system time is set before the UNIX epoch.
82#[inline(always)]
83#[must_use]
84pub fn duration_since_unix_epoch() -> Duration {
85 // The expect() is acceptable here because:
86 // - SystemTime failure indicates catastrophic system clock issues
87 // - This would affect the entire application's ability to function
88 // - Alternative error handling would complicate all time-dependent code paths
89 // - Such failures are extremely rare in practice and indicate hardware/OS problems
90 wall_clock_now()
91 .duration_since(UNIX_EPOCH)
92 .expect("Error calling `SystemTime`")
93}
94
95/// Returns the current wall-clock time as [`SystemTime`].
96///
97/// Under simulation (`simulation` + `cfg(madsim)`), returns virtual wall-clock
98/// time from the madsim deterministic scheduler when called from inside a
99/// madsim runtime. When called outside a runtime (e.g. plain `#[rstest]` test
100/// bodies), falls back to [`SystemTime::now()`], which under `cfg(madsim)` is
101/// libc-intercepted by madsim and resolves to the same real syscall it would
102/// in a normal build. Under normal builds, returns [`SystemTime::now()`].
103///
104/// This is the wall-clock seam. It preserves Unix-epoch semantics (unlike
105/// `tokio::time::Instant` which is monotonic and carries no epoch).
106#[inline(always)]
107#[must_use]
108fn wall_clock_now() -> SystemTime {
109 #[cfg(not(all(feature = "simulation", madsim)))]
110 {
111 SystemTime::now()
112 }
113 #[cfg(all(feature = "simulation", madsim))]
114 {
115 // `try_current` returns `None` when no madsim runtime is active.
116 // Falling back to `SystemTime::now()` matches what madsim's own libc
117 // shim does for `clock_gettime` outside a runtime; production paths
118 // running under simulation are always inside a runtime, so they
119 // continue to receive virtual time.
120 match madsim::time::TimeHandle::try_current() {
121 Some(handle) => handle.now_time(),
122 None => SystemTime::now(),
123 }
124 }
125}
126
127/// Returns the current UNIX time in nanoseconds, based on [`SystemTime::now()`].
128///
129/// # Panics
130///
131/// Panics if the duration in nanoseconds exceeds `u64::MAX`.
132#[inline(always)]
133#[must_use]
134pub fn nanos_since_unix_epoch() -> u64 {
135 u64::try_from(duration_since_unix_epoch().as_nanos())
136 .expect("System time overflow: value exceeds u64::MAX nanoseconds")
137}
138
139/// Represents an atomic timekeeping structure.
140///
141/// [`AtomicTime`] can act as a real-time clock or static clock based on its mode.
142/// It uses an [`AtomicU64`] to atomically update the value using only immutable
143/// references.
144///
145/// The `realtime` flag indicates which mode the clock is currently in.
146/// For concurrency, this struct uses atomic operations with appropriate memory orderings:
147/// - **Acquire/Release** for reading/writing in **static mode**.
148/// - **Compare-and-exchange (`AcqRel`)** in real-time mode to guarantee monotonic increments.
149///
150/// The mode flag and timestamp are private so every update flows through the methods
151/// that uphold the monotonicity and mode invariants.
152#[repr(C)]
153#[derive(Debug)]
154pub struct AtomicTime {
155 realtime: AtomicBool,
156 timestamp_ns: AtomicU64,
157}
158
159impl Default for AtomicTime {
160 /// Creates a new default [`AtomicTime`] instance in **real-time mode**, starting at the current system time.
161 fn default() -> Self {
162 Self::new(true, UnixNanos::default())
163 }
164}
165
166impl AtomicTime {
167 /// Creates a new [`AtomicTime`] instance.
168 ///
169 /// - If `realtime` is `true`, the provided `time` is used only as an initial placeholder
170 /// and will quickly be overridden by calls to [`AtomicTime::time_since_epoch`].
171 /// - If `realtime` is `false`, this clock starts in **static mode**, with the given `time`
172 /// as its current value.
173 #[must_use]
174 pub fn new(realtime: bool, time: UnixNanos) -> Self {
175 Self {
176 realtime: AtomicBool::new(realtime),
177 timestamp_ns: AtomicU64::new(time.into()),
178 }
179 }
180
181 /// Returns the current time in nanoseconds, based on the clock’s mode.
182 ///
183 /// - In **real-time mode**, calls [`AtomicTime::time_since_epoch`], ensuring strictly increasing
184 /// timestamps across threads, using `AcqRel` semantics for the underlying atomic.
185 /// - In **static mode**, reads the stored time using [`Ordering::Acquire`]. Updates by other
186 /// threads using [`AtomicTime::set_time`] or [`AtomicTime::increment_time`] (Release/AcqRel)
187 /// will be visible here.
188 ///
189 /// # Thread Safety
190 ///
191 /// The mode check is not atomic with the subsequent read/update. If another thread
192 /// switches modes between the check and the operation, one stale-mode result may be
193 /// returned. This is intentional: mode switching is a setup-time operation and should
194 /// not occur concurrently with time operations.
195 #[must_use]
196 pub fn get_time_ns(&self) -> UnixNanos {
197 if self.realtime.load(Ordering::Acquire) {
198 self.time_since_epoch()
199 } else {
200 UnixNanos::from(self.timestamp_ns.load(Ordering::Acquire))
201 }
202 }
203
204 /// Returns the current time as microseconds.
205 #[must_use]
206 pub fn get_time_us(&self) -> u64 {
207 self.get_time_ns().as_u64() / NANOSECONDS_IN_MICROSECOND
208 }
209
210 /// Returns the current time as milliseconds.
211 #[must_use]
212 pub fn get_time_ms(&self) -> u64 {
213 self.get_time_ns().as_u64() / NANOSECONDS_IN_MILLISECOND
214 }
215
216 /// Returns the current time as seconds.
217 #[must_use]
218 #[expect(
219 clippy::cast_precision_loss,
220 reason = "Precision loss acceptable for time conversion"
221 )]
222 pub fn get_time(&self) -> f64 {
223 self.get_time_ns().as_f64() / (NANOSECONDS_IN_SECOND as f64)
224 }
225
226 /// Manually sets a new time for the clock (only possible in **static mode**).
227 ///
228 /// This uses an atomic store with [`Ordering::Release`], so any thread reading with
229 /// [`Ordering::Acquire`] will see the updated time. This does *not* enforce a total ordering
230 /// among all threads, but is enough to ensure that once a thread sees this update, it also
231 /// sees all writes made before this call in the writing thread.
232 ///
233 /// Typically used in single-threaded scenarios or coordinated concurrency in **static mode**,
234 /// since there's no global ordering across threads.
235 ///
236 /// # Panics
237 ///
238 /// Panics if invoked when in real-time mode.
239 ///
240 /// # Thread Safety
241 ///
242 /// The mode check is not atomic with the subsequent store. If another thread calls
243 /// `make_realtime()` between the check and store, the invariant can be violated.
244 /// This is intentional: mode switching is a setup-time operation and should not
245 /// occur concurrently with time operations. Callers must ensure mode switches are
246 /// complete before resuming time operations.
247 pub fn set_time(&self, time: UnixNanos) {
248 assert!(
249 !self.realtime.load(Ordering::SeqCst),
250 "Cannot set time while clock is in realtime mode"
251 );
252
253 self.timestamp_ns.store(time.into(), Ordering::Release);
254
255 debug_assert!(
256 !self.realtime.load(Ordering::SeqCst),
257 "Invariant: clock must remain in static mode across `set_time`"
258 );
259 }
260
261 /// Increments the current (static-mode) time by `delta` nanoseconds and returns the updated value.
262 ///
263 /// Internally this uses [`AtomicU64::try_update`] with [`Ordering::AcqRel`] to ensure the increment is
264 /// atomic and visible to readers using `Acquire` loads.
265 ///
266 /// # Errors
267 ///
268 /// Returns an error if the increment would overflow `u64::MAX` or if called
269 /// while the clock is in real-time mode.
270 ///
271 /// # Thread Safety
272 ///
273 /// The mode check is not atomic with the subsequent update. If another thread calls
274 /// `make_realtime()` between the check and update, the invariant can be violated.
275 /// This is intentional: mode switching is a setup-time operation and should not
276 /// occur concurrently with time operations. Callers must ensure mode switches are
277 /// complete before resuming time operations.
278 pub fn increment_time(&self, delta: u64) -> anyhow::Result<UnixNanos> {
279 anyhow::ensure!(
280 !self.realtime.load(Ordering::SeqCst),
281 "Cannot increment time while clock is in realtime mode"
282 );
283
284 let previous =
285 match self
286 .timestamp_ns
287 .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
288 current.checked_add(delta)
289 }) {
290 Ok(prev) => prev,
291 Err(_) => anyhow::bail!("Cannot increment time beyond u64::MAX"),
292 };
293
294 debug_assert!(
295 !self.realtime.load(Ordering::SeqCst),
296 "Invariant: clock must remain in static mode across `increment_time`"
297 );
298
299 Ok(UnixNanos::from(previous + delta))
300 }
301
302 /// Retrieves and updates the current “real-time” clock, returning a strictly increasing
303 /// timestamp based on system time.
304 ///
305 /// Internally:
306 /// - We fetch `now` from [`SystemTime::now()`].
307 /// - We do an atomic compare-and-exchange (using [`Ordering::AcqRel`]) to ensure the stored
308 /// timestamp is never less than the last timestamp.
309 ///
310 /// This ensures:
311 /// 1. **Monotonic increments**: The returned timestamp is strictly greater than the previous
312 /// one (by at least 1 nanosecond).
313 /// 2. **No backward jumps**: If the OS time moves backward, we ignore that shift to preserve
314 /// monotonicity.
315 /// 3. **Visibility**: In a multi-threaded environment, other threads see the updated value
316 /// once this compare-and-exchange completes.
317 ///
318 /// # Panics
319 ///
320 /// Panics if the internal counter has reached `u64::MAX`, which would indicate the process has
321 /// been running for longer than the representable range (~584 years) *or* the clock was
322 /// manually corrupted.
323 pub fn time_since_epoch(&self) -> UnixNanos {
324 // This method guarantees strict consistency but may incur a performance cost under
325 // high contention due to retries in the `compare_exchange` loop.
326 let now = nanos_since_unix_epoch();
327
328 loop {
329 // Acquire to observe the latest stored value
330 let last = self.timestamp_ns.load(Ordering::Acquire);
331
332 // Ensure we never wrap past u64::MAX – treat that as a fatal error
333 let incremented = last
334 .checked_add(1)
335 .expect("AtomicTime overflow: reached u64::MAX");
336 let next = now.max(incremented);
337
338 // AcqRel on success ensures this new value is published,
339 // Acquire on failure reloads if we lost a CAS race.
340 //
341 // Note that under heavy contention (many threads calling this in tight loops),
342 // the CAS loop may increase latency.
343 //
344 // However, in practice, the loop terminates quickly because:
345 // - System time naturally advances between iterations
346 // - Each iteration increments time by at least 1ns, preventing ABA problems
347 // - True contention requiring retry is rare in normal usage patterns
348 //
349 // The concurrent stress test (4 threads × 100k iterations) validates this approach.
350 if self
351 .timestamp_ns
352 .compare_exchange(last, next, Ordering::AcqRel, Ordering::Acquire)
353 .is_ok()
354 {
355 debug_assert!(
356 next > last,
357 "Invariant: time is strictly monotonic across CAS"
358 );
359 return UnixNanos::from(next);
360 }
361 }
362 }
363
364 /// Switches the clock to **real-time mode** (`realtime = true`).
365 ///
366 /// If transitioning from static mode, the internal counter is reset to the current
367 /// wall-clock time so that [`AtomicTime::time_since_epoch`] does not carry forward a
368 /// timestamp set during static mode (e.g. a backtest far in the future).
369 ///
370 /// Uses [`Ordering::SeqCst`] for the mode flag to ensure global ordering.
371 ///
372 /// # Thread Safety
373 ///
374 /// The mode swap and the counter reset are two separate atomic operations. A thread
375 /// reading between them can observe real-time mode with the stale static-mode counter
376 /// and return a timestamp derived from it (potentially far in the future), after which
377 /// the reset moves the clock backwards. Mode switching is a setup-time operation and
378 /// must not run concurrently with time reads.
379 pub fn make_realtime(&self) {
380 if !self.realtime.swap(true, Ordering::SeqCst) {
381 self.timestamp_ns
382 .store(nanos_since_unix_epoch(), Ordering::Release);
383 }
384 }
385
386 /// Switches the clock to **static mode** (`realtime = false`).
387 ///
388 /// If transitioning from real-time mode, the internal counter is snapshotted to the
389 /// current wall-clock time so that subsequent static reads return a reasonable value
390 /// rather than a stale or zero placeholder.
391 ///
392 /// Uses [`Ordering::SeqCst`] for the mode flag to ensure global ordering.
393 ///
394 /// # Thread Safety
395 ///
396 /// The mode swap and the counter snapshot are two separate atomic operations; see
397 /// [`AtomicTime::make_realtime`] for the race this implies. Mode switching is a
398 /// setup-time operation and must not run concurrently with time reads.
399 pub fn make_static(&self) {
400 if self.realtime.swap(false, Ordering::SeqCst) {
401 self.timestamp_ns
402 .store(nanos_since_unix_epoch(), Ordering::Release);
403 }
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use std::sync::Arc;
410
411 use rstest::*;
412
413 use super::*;
414
415 #[rstest]
416 fn test_global_clocks_initialization() {
417 let realtime_clock = get_atomic_clock_realtime();
418 assert!(realtime_clock.get_time_ns().as_u64() > 0);
419
420 let static_clock = get_atomic_clock_static();
421 static_clock.set_time(UnixNanos::from(500_000_000)); // 500 ms
422 assert_eq!(static_clock.get_time_ns().as_u64(), 500_000_000);
423 }
424
425 #[rstest]
426 fn test_mode_switching() {
427 let time = AtomicTime::new(true, UnixNanos::default());
428
429 // Verify real-time mode
430 let realtime_ns = time.get_time_ns();
431 assert!(realtime_ns.as_u64() > 0);
432
433 // Switch to static mode
434 time.make_static();
435 time.set_time(UnixNanos::from(1_000_000_000)); // 1 second
436 let static_ns = time.get_time_ns();
437 assert_eq!(static_ns.as_u64(), 1_000_000_000);
438
439 // Switch back to real-time mode
440 time.make_realtime();
441 let new_realtime_ns = time.get_time_ns();
442 assert!(new_realtime_ns.as_u64() > static_ns.as_u64());
443 }
444
445 #[rstest]
446 #[should_panic(expected = "Cannot set time while clock is in realtime mode")]
447 fn test_set_time_panics_in_realtime_mode() {
448 let clock = AtomicTime::new(true, UnixNanos::default());
449 clock.set_time(UnixNanos::from(123));
450 }
451
452 #[rstest]
453 fn test_increment_time_returns_error_in_realtime_mode() {
454 let clock = AtomicTime::new(true, UnixNanos::default());
455 let result = clock.increment_time(1);
456 assert!(result.is_err());
457 assert!(
458 result
459 .unwrap_err()
460 .to_string()
461 .contains("Cannot increment time while clock is in realtime mode")
462 );
463 }
464
465 #[rstest]
466 #[should_panic(expected = "AtomicTime overflow")]
467 fn test_time_since_epoch_overflow_panics() {
468 use std::sync::atomic::{AtomicBool, AtomicU64};
469
470 // Manually construct a clock with the counter already at u64::MAX
471 let clock = AtomicTime {
472 realtime: AtomicBool::new(true),
473 timestamp_ns: AtomicU64::new(u64::MAX),
474 };
475
476 // This call will attempt to add 1 and must panic
477 let _ = clock.time_since_epoch();
478 }
479
480 #[rstest]
481 fn test_make_static_snapshots_wall_time() {
482 // A fresh realtime clock that has never been read starts with timestamp_ns = 0.
483 // Switching to static should snapshot wall time, not leave it at 0.
484 let clock = AtomicTime::new(true, UnixNanos::default());
485 clock.make_static();
486 let ts = clock.get_time_ns();
487 assert!(
488 ts.as_u64() > 1_650_000_000_000_000_000,
489 "Expected wall-clock snapshot, was {ts}"
490 );
491 }
492
493 #[rstest]
494 fn test_make_realtime_resets_future_timestamp() {
495 // If static mode set the clock into the future, switching to realtime
496 // should reset to wall time so timestamps are not poisoned.
497 let clock = AtomicTime::new(false, UnixNanos::from(u64::MAX - 1_000));
498 clock.make_realtime();
499 let ts = clock.get_time_ns();
500 // Should be near current wall time, not near u64::MAX
501 let now = nanos_since_unix_epoch();
502 assert!(
503 ts.as_u64() <= now + 1_000_000_000, // within 1 second
504 "Expected wall-clock time, was {ts} (now={now})"
505 );
506 }
507
508 #[rstest]
509 fn test_make_static_idempotent() {
510 // Calling make_static on an already-static clock should not change the time
511 let clock = AtomicTime::new(false, UnixNanos::from(42));
512 clock.make_static();
513 assert_eq!(clock.get_time_ns(), UnixNanos::from(42));
514 }
515
516 #[rstest]
517 fn test_make_realtime_idempotent() {
518 // Calling make_realtime on an already-realtime clock should not reset the counter
519 let clock = AtomicTime::new(true, UnixNanos::default());
520 let ts1 = clock.get_time_ns();
521 clock.make_realtime(); // already realtime, should be a no-op
522 let ts2 = clock.get_time_ns();
523 assert!(ts2 >= ts1);
524 }
525
526 #[rstest]
527 fn test_static_time_is_stable() {
528 // Create a clock in static mode with an initial value
529 let clock = AtomicTime::new(false, UnixNanos::from(42));
530 let time1 = clock.get_time_ns();
531
532 // Sleep a bit to give the system time to change, if the clock were using real-time
533 std::thread::sleep(std::time::Duration::from_millis(10));
534 let time2 = clock.get_time_ns();
535
536 // In static mode, the value should remain unchanged
537 assert_eq!(time1, time2);
538 }
539
540 #[rstest]
541 fn test_increment_time() {
542 // Start in static mode
543 let time = AtomicTime::new(false, UnixNanos::from(0));
544
545 let updated_time = time.increment_time(500).unwrap();
546 assert_eq!(updated_time.as_u64(), 500);
547
548 let updated_time = time.increment_time(1_000).unwrap();
549 assert_eq!(updated_time.as_u64(), 1_500);
550 }
551
552 #[rstest]
553 fn test_increment_time_overflow_errors() {
554 let time = AtomicTime::new(false, UnixNanos::from(u64::MAX - 5));
555
556 let err = time.increment_time(10).unwrap_err();
557 assert_eq!(err.to_string(), "Cannot increment time beyond u64::MAX");
558 }
559
560 #[rstest]
561 fn test_increment_time_after_make_static() {
562 // Switching from realtime snapshots wall time; increments build on the snapshot
563 let clock = AtomicTime::new(true, UnixNanos::default());
564 clock.make_static();
565 let before = clock.get_time_ns();
566 let after = clock.increment_time(1_000).unwrap();
567 assert_eq!(after, before + 1_000_u64);
568 assert_eq!(clock.get_time_ns(), after);
569 }
570
571 #[rstest]
572 fn test_nanos_since_unix_epoch_vs_system_time() {
573 let unix_nanos = nanos_since_unix_epoch();
574 let system_ns = u64::try_from(duration_since_unix_epoch().as_nanos()).unwrap();
575 assert!(unix_nanos.abs_diff(system_ns) < NANOSECONDS_IN_SECOND);
576 }
577
578 #[rstest]
579 fn test_time_since_epoch_monotonicity() {
580 let clock = get_atomic_clock_realtime();
581 let mut previous = clock.time_since_epoch();
582 for _ in 0..1_000_000 {
583 let current = clock.time_since_epoch();
584 assert!(current > previous);
585 previous = current;
586 }
587 }
588
589 #[rstest]
590 fn test_time_since_epoch_strictly_increasing_concurrent() {
591 let time = Arc::new(AtomicTime::new(true, UnixNanos::default()));
592 let num_threads = 4;
593 let iterations = 100_000;
594 let mut handles = Vec::with_capacity(num_threads);
595
596 for thread_id in 0..num_threads {
597 let time_clone = Arc::clone(&time);
598
599 let handle = std::thread::spawn(move || {
600 let mut previous = time_clone.time_since_epoch().as_u64();
601
602 for i in 0..iterations {
603 let current = time_clone.time_since_epoch().as_u64();
604 assert!(
605 current > previous,
606 "Thread {thread_id}: iteration {i}: time did not increase: previous={previous}, current={current}",
607 );
608 previous = current;
609 }
610 });
611
612 handles.push(handle);
613 }
614
615 for handle in handles {
616 handle.join().unwrap();
617 }
618 }
619
620 #[rstest]
621 fn test_duration_since_unix_epoch() {
622 let time = AtomicTime::new(true, UnixNanos::default());
623 let duration = Duration::from_nanos(time.get_time_ns().into());
624 let now = SystemTime::now();
625
626 // Check if the duration is close to the actual difference between now and UNIX_EPOCH
627 let delta = now
628 .duration_since(UNIX_EPOCH)
629 .unwrap()
630 .checked_sub(duration);
631 assert!(delta.unwrap_or_default() < Duration::from_millis(100));
632
633 // Check if the duration is greater than a certain value (assuming the test is run after that point)
634 assert!(duration > Duration::from_mins(27_500_000));
635 }
636
637 #[rstest]
638 fn test_unix_timestamp_is_monotonic_increasing() {
639 let time = AtomicTime::new(true, UnixNanos::default());
640 let result1 = time.get_time();
641 let result2 = time.get_time();
642 let result3 = time.get_time();
643 let result4 = time.get_time();
644 let result5 = time.get_time();
645
646 assert!(result2 >= result1);
647 assert!(result3 >= result2);
648 assert!(result4 >= result3);
649 assert!(result5 >= result4);
650 assert!(result1 > 1_650_000_000.0);
651 }
652
653 #[rstest]
654 fn test_unix_timestamp_ms_is_monotonic_increasing() {
655 let time = AtomicTime::new(true, UnixNanos::default());
656 let result1 = time.get_time_ms();
657 let result2 = time.get_time_ms();
658 let result3 = time.get_time_ms();
659 let result4 = time.get_time_ms();
660 let result5 = time.get_time_ms();
661
662 assert!(result2 >= result1);
663 assert!(result3 >= result2);
664 assert!(result4 >= result3);
665 assert!(result5 >= result4);
666 assert!(result1 >= 1_650_000_000_000);
667 }
668
669 #[rstest]
670 fn test_unix_timestamp_us_is_monotonic_increasing() {
671 let time = AtomicTime::new(true, UnixNanos::default());
672 let result1 = time.get_time_us();
673 let result2 = time.get_time_us();
674 let result3 = time.get_time_us();
675 let result4 = time.get_time_us();
676 let result5 = time.get_time_us();
677
678 assert!(result2 >= result1);
679 assert!(result3 >= result2);
680 assert!(result4 >= result3);
681 assert!(result5 >= result4);
682 assert!(result1 > 1_650_000_000_000_000);
683 }
684
685 #[rstest]
686 fn test_unix_timestamp_ns_is_monotonic_increasing() {
687 let time = AtomicTime::new(true, UnixNanos::default());
688 let result1 = time.get_time_ns();
689 let result2 = time.get_time_ns();
690 let result3 = time.get_time_ns();
691 let result4 = time.get_time_ns();
692 let result5 = time.get_time_ns();
693
694 assert!(result2 >= result1);
695 assert!(result3 >= result2);
696 assert!(result4 >= result3);
697 assert!(result5 >= result4);
698 assert!(result1.as_u64() > 1_650_000_000_000_000_000);
699 }
700
701 #[rstest]
702 fn test_acquire_release_contract_static_mode() {
703 // This test explicitly proves the Acquire/Release memory ordering contract:
704 // - Writer thread uses set_time() which does Release store (see AtomicTime::set_time)
705 // - Reader thread uses get_time_ns() which does Acquire load (see AtomicTime::get_time_ns)
706 // - The Release-Acquire pair ensures all writes before Release are visible after Acquire
707
708 let clock = Arc::new(AtomicTime::new(false, UnixNanos::from(0)));
709 let aux_data = Arc::new(AtomicU64::new(0));
710 let done = Arc::new(AtomicBool::new(false));
711
712 // Writer thread: updates auxiliary data, then releases via set_time
713 let writer_clock = Arc::clone(&clock);
714 let writer_aux = Arc::clone(&aux_data);
715 let writer_done = Arc::clone(&done);
716
717 let writer = std::thread::spawn(move || {
718 for i in 1..=1_000u64 {
719 writer_aux.store(i, Ordering::Relaxed);
720
721 // Release store via set_time creates a release fence - all prior writes (including aux_data)
722 // must be visible to any thread that observes this time value via Acquire load
723 writer_clock.set_time(UnixNanos::from(i * 1000));
724
725 // Yield to encourage interleaving
726 std::thread::yield_now();
727 }
728 writer_done.store(true, Ordering::Release);
729 });
730
731 // Reader thread: acquires via get_time_ns, then checks auxiliary data
732 let reader_clock = Arc::clone(&clock);
733 let reader_aux = Arc::clone(&aux_data);
734 let reader_done = Arc::clone(&done);
735
736 let reader = std::thread::spawn(move || {
737 let mut last_time = 0u64;
738 let mut max_aux_seen = 0u64;
739
740 // Poll until writer is done, with no iteration limit
741 while !reader_done.load(Ordering::Acquire) {
742 let current_time = reader_clock.get_time_ns().as_u64();
743
744 if current_time > last_time {
745 // The Acquire in get_time_ns synchronizes with the Release in set_time,
746 // making aux_data visible
747 let aux_value = reader_aux.load(Ordering::Relaxed);
748
749 // Invariant: aux_value must never go backwards (proves Release-Acquire sync works)
750 if aux_value > 0 {
751 assert!(
752 aux_value >= max_aux_seen,
753 "Acquire/Release contract violated: aux went backwards from {max_aux_seen} to {aux_value}"
754 );
755 max_aux_seen = aux_value;
756 }
757
758 last_time = current_time;
759 }
760
761 std::thread::yield_now();
762 }
763
764 // Check final state after writer completes to ensure we observe updates
765 let final_time = reader_clock.get_time_ns().as_u64();
766 if final_time > last_time {
767 let final_aux = reader_aux.load(Ordering::Relaxed);
768 if final_aux > 0 {
769 assert!(
770 final_aux >= max_aux_seen,
771 "Acquire/Release contract violated: final aux {final_aux} < max {max_aux_seen}"
772 );
773 max_aux_seen = final_aux;
774 }
775 }
776
777 max_aux_seen
778 });
779
780 writer.join().unwrap();
781 let max_observed = reader.join().unwrap();
782
783 // Ensure the reader actually observed updates (not vacuously satisfied)
784 assert!(max_observed > 0, "Reader must observe writer updates");
785 }
786
787 #[rstest]
788 fn test_acquire_release_contract_increment_time() {
789 // Similar test for increment_time, which uses try_update with AcqRel (see AtomicTime::increment_time)
790
791 let clock = Arc::new(AtomicTime::new(false, UnixNanos::from(0)));
792 let aux_data = Arc::new(AtomicU64::new(0));
793 let done = Arc::new(AtomicBool::new(false));
794
795 let writer_clock = Arc::clone(&clock);
796 let writer_aux = Arc::clone(&aux_data);
797 let writer_done = Arc::clone(&done);
798
799 let writer = std::thread::spawn(move || {
800 for i in 1..=1_000u64 {
801 writer_aux.store(i, Ordering::Relaxed);
802 let _ = writer_clock.increment_time(1000).unwrap();
803 std::thread::yield_now();
804 }
805 writer_done.store(true, Ordering::Release);
806 });
807
808 let reader_clock = Arc::clone(&clock);
809 let reader_aux = Arc::clone(&aux_data);
810 let reader_done = Arc::clone(&done);
811
812 let reader = std::thread::spawn(move || {
813 let mut last_time = 0u64;
814 let mut max_aux = 0u64;
815
816 // Poll until writer is done, with no iteration limit
817 while !reader_done.load(Ordering::Acquire) {
818 let current_time = reader_clock.get_time_ns().as_u64();
819
820 if current_time > last_time {
821 let aux_value = reader_aux.load(Ordering::Relaxed);
822
823 // Invariant: aux_value must never regress (proves AcqRel sync works)
824 if aux_value > 0 {
825 assert!(
826 aux_value >= max_aux,
827 "AcqRel contract violated: aux regressed from {max_aux} to {aux_value}"
828 );
829 max_aux = aux_value;
830 }
831
832 last_time = current_time;
833 }
834
835 std::thread::yield_now();
836 }
837
838 // Check final state after writer completes to ensure we observe updates
839 let final_time = reader_clock.get_time_ns().as_u64();
840 if final_time > last_time {
841 let final_aux = reader_aux.load(Ordering::Relaxed);
842 if final_aux > 0 {
843 assert!(
844 final_aux >= max_aux,
845 "AcqRel contract violated: final aux {final_aux} < max {max_aux}"
846 );
847 max_aux = final_aux;
848 }
849 }
850
851 max_aux
852 });
853
854 writer.join().unwrap();
855 let max_observed = reader.join().unwrap();
856
857 // Ensure the reader actually observed updates (not vacuously satisfied)
858 assert!(max_observed > 0, "Reader must observe writer updates");
859 }
860
861 // The wall-clock seam (`wall_clock_now`) routes through madsim's virtual
862 // clock under simulation. Sleeping for 60 virtual seconds must advance
863 // the value returned by `nanos_since_unix_epoch` by 60s in wall-clock
864 // terms. If the cfg gate fell through to `SystemTime::now()`, the elapsed
865 // value would only reflect real wall-clock time (~0ms) and the assertion
866 // would fail.
867 #[cfg(all(feature = "simulation", madsim))]
868 #[madsim::test]
869 async fn test_wall_clock_advances_with_virtual_time() {
870 let before = nanos_since_unix_epoch();
871 madsim::time::sleep(std::time::Duration::from_secs(60)).await;
872 let after = nanos_since_unix_epoch();
873
874 let elapsed_ns = after.saturating_sub(before);
875 let sixty_seconds_ns = 60 * NANOSECONDS_IN_SECOND;
876 assert!(
877 elapsed_ns >= sixty_seconds_ns,
878 "wall clock did not advance by full virtual sleep: elapsed={elapsed_ns}ns"
879 );
880 }
881}