Skip to main content

ash_log/
hlc.rs

1//! Hybrid Logical Clock timestamps for events.
2//!
3//! # Why this exists
4//!
5//! Every event carries a [`SystemTime`](std::time::SystemTime), and a system
6//! clock can move backwards: NTP steps it, a VM resumes from a snapshot, an
7//! operator corrects it by hand. When that happens the audit log keeps
8//! verifying — [`chain_index`](crate::HmacChainIntegrity) is monotonic whatever
9//! the wall clock does — but the timestamps no longer describe the order things
10//! actually happened in, which is most of what an audit log is for.
11//!
12//! A Hybrid Logical Clock timestamp is monotonic by construction. It tracks
13//! wall time when wall time is sane, and falls back to a logical counter when
14//! it is not, so `a.hlc < b.hlc` means `a` really was recorded first.
15//!
16//! # Across services
17//!
18//! [`HlcClock::recv`] is the other half. A service that receives a request
19//! carrying an upstream timestamp calls `recv` before recording its own events,
20//! and those events are then provably ordered after the upstream ones — without
21//! the two hosts' clocks agreeing. See [`Logger::observe_hlc`](crate::Logger::observe_hlc).
22//!
23//! # Integrity
24//!
25//! The timestamp is part of the event's canonical form, so it is covered by
26//! whatever [`AuditIntegrity`](crate::AuditIntegrity) is in use: with
27//! [`HmacChainIntegrity`](crate::HmacChainIntegrity) the causal ordering cannot
28//! be rewritten without detection. Events written without this feature carry no
29//! `hlc` field at all, and their canonical bytes are unchanged, so logs and
30//! chains produced by either build verify identically.
31
32use serde::{Deserialize, Serialize};
33
34pub use ash_time::{HlcClock, HlcError, HlcTimestamp};
35
36/// An [`HlcTimestamp`] as it is stored on an event.
37///
38/// [`HlcTimestamp`] carries no serde derives, so this mirrors its two fields.
39/// It serializes as `{"physical": <ns>, "logical": <n>}`, and orders exactly as
40/// the underlying timestamp does: by wall-clock nanoseconds first, then by the
41/// logical counter that breaks ties within the same nanosecond.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
43pub struct EventClock {
44    /// Wall-clock component: nanoseconds since the Unix epoch.
45    pub physical: u64,
46    /// Logical counter, distinguishing events within one nanosecond.
47    pub logical: u32,
48}
49
50impl EventClock {
51    /// Whether `self` was recorded before `other`.
52    #[must_use]
53    pub fn happened_before(self, other: Self) -> bool {
54        self < other
55    }
56}
57
58impl From<HlcTimestamp> for EventClock {
59    fn from(ts: HlcTimestamp) -> Self {
60        Self {
61            physical: ts.physical,
62            logical: ts.logical,
63        }
64    }
65}
66
67impl From<EventClock> for HlcTimestamp {
68    fn from(clock: EventClock) -> Self {
69        Self {
70            physical: clock.physical,
71            logical: clock.logical,
72        }
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_round_trips_through_the_underlying_timestamp() {
82        let clock = HlcClock::new();
83        let ts = clock.now().expect("system clock is sane under test");
84
85        let stored = EventClock::from(ts);
86        assert_eq!(HlcTimestamp::from(stored), ts);
87    }
88
89    #[test]
90    fn test_ordering_matches_the_underlying_timestamp() {
91        let clock = HlcClock::new();
92        let first = clock.now().unwrap();
93        let second = clock.now().unwrap();
94
95        assert!(first.happened_before(second));
96        assert!(EventClock::from(first).happened_before(EventClock::from(second)));
97        assert!(EventClock::from(first) < EventClock::from(second));
98    }
99
100    #[test]
101    fn test_serializes_as_two_named_fields() {
102        let clock = EventClock {
103            physical: 1_700_000_000_000_000_000,
104            logical: 7,
105        };
106
107        let json = serde_json::to_value(clock).unwrap();
108        assert_eq!(json["physical"], 1_700_000_000_000_000_000_u64);
109        assert_eq!(json["logical"], 7);
110
111        let back: EventClock = serde_json::from_value(json).unwrap();
112        assert_eq!(back, clock);
113    }
114
115    #[test]
116    fn test_logical_counter_breaks_ties_within_a_nanosecond() {
117        // Same physical component, different logical: the ordering must still
118        // be total, or two events in the same nanosecond would be unorderable.
119        let earlier = EventClock {
120            physical: 42,
121            logical: 0,
122        };
123        let later = EventClock {
124            physical: 42,
125            logical: 1,
126        };
127
128        assert!(earlier.happened_before(later));
129        assert!(!later.happened_before(earlier));
130    }
131}