Skip to main content

beads_rs/daemon/
clock.rs

1//! HLC (Hybrid Logical Clock) for causal ordering.
2//!
3//! The clock generates monotonically increasing WriteStamps that form
4//! a total order across all actors.
5
6use std::time::{SystemTime, UNIX_EPOCH};
7
8pub trait TimeSource: Send + Sync {
9    fn now_ms(&self) -> u64;
10}
11
12pub struct SystemTimeSource;
13
14impl TimeSource for SystemTimeSource {
15    fn now_ms(&self) -> u64 {
16        SystemTime::now()
17            .duration_since(UNIX_EPOCH)
18            .unwrap_or_default()
19            .as_millis() as u64
20    }
21}
22
23use crate::core::WriteStamp;
24
25/// Hybrid Logical Clock.
26///
27/// Combines wall clock time with a logical counter to ensure monotonicity
28/// even when wall clock jumps backward or multiple events happen in the
29/// same millisecond.
30pub struct Clock {
31    /// Last known wall time in milliseconds.
32    wall_ms: u64,
33    /// Logical counter for tie-breaking within same wall time.
34    counter: u32,
35    time_source: Box<dyn TimeSource>,
36}
37
38impl Clock {
39    /// Create a new clock initialized to current wall time.
40    pub fn new() -> Self {
41        Self::with_time_source(Box::new(SystemTimeSource))
42    }
43
44    pub fn with_time_source(time_source: Box<dyn TimeSource>) -> Self {
45        let now = time_source.now_ms();
46        Self {
47            wall_ms: now,
48            counter: 0,
49            time_source,
50        }
51    }
52
53    /// Generate a new WriteStamp, advancing the clock.
54    ///
55    /// Guarantees:
56    /// - Returned stamp is strictly greater than any previous stamp from this clock
57    /// - Monotonic even if wall clock goes backward
58    pub fn tick(&mut self) -> WriteStamp {
59        let now = self.time_source.now_ms();
60
61        if now > self.wall_ms {
62            // Wall clock advanced - use new time, reset counter
63            self.wall_ms = now;
64            self.counter = 0;
65        } else {
66            // Same millisecond or clock went backward - increment counter
67            self.counter += 1;
68        }
69
70        WriteStamp::new(self.wall_ms, self.counter)
71    }
72
73    /// Update clock based on a remote stamp.
74    ///
75    /// Ensures next tick() will produce a stamp > remote.
76    /// Call this when receiving state from sync.
77    pub fn receive(&mut self, remote: &WriteStamp) {
78        let now = self.time_source.now_ms();
79
80        if remote.wall_ms > self.wall_ms {
81            // Remote is ahead - adopt its time
82            self.wall_ms = remote.wall_ms;
83            self.counter = remote.counter;
84        } else if remote.wall_ms == self.wall_ms && remote.counter > self.counter {
85            // Same time but remote has higher counter
86            self.counter = remote.counter;
87        }
88        // else: our clock is already ahead, nothing to do
89
90        // Also advance to current wall time if it's ahead
91        if now > self.wall_ms {
92            self.wall_ms = now;
93            self.counter = 0;
94        }
95    }
96
97    /// Get the current wall time tracked by this clock.
98    pub fn wall_ms(&self) -> u64 {
99        self.wall_ms
100    }
101}
102
103impl Default for Clock {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use std::sync::Arc;
113    use std::sync::atomic::{AtomicU64, Ordering};
114
115    #[test]
116    fn tick_is_monotonic() {
117        let mut clock = Clock::new();
118        let s1 = clock.tick();
119        let s2 = clock.tick();
120        let s3 = clock.tick();
121
122        assert!(s2 > s1);
123        assert!(s3 > s2);
124    }
125
126    #[test]
127    fn receive_advances_clock() {
128        let mut clock = Clock::new();
129        let local = clock.tick();
130
131        // Simulate remote with future timestamp
132        let remote = WriteStamp::new(local.wall_ms + 10000, 5);
133        clock.receive(&remote);
134
135        let after = clock.tick();
136        assert!(after > remote);
137    }
138
139    #[test]
140    fn receive_with_older_stamp_is_noop() {
141        let mut clock = Clock::new();
142        let s1 = clock.tick();
143        let s2 = clock.tick();
144
145        // Remote is older than our current state
146        let old_remote = WriteStamp::new(s1.wall_ms, s1.counter);
147        clock.receive(&old_remote);
148
149        let s3 = clock.tick();
150        assert!(s3 > s2);
151    }
152
153    struct TestTimeSource {
154        now: Arc<AtomicU64>,
155    }
156
157    impl TimeSource for TestTimeSource {
158        fn now_ms(&self) -> u64 {
159            self.now.load(Ordering::SeqCst)
160        }
161    }
162
163    #[test]
164    fn backward_jump_keeps_monotonicity() {
165        let now = Arc::new(AtomicU64::new(1_000));
166        let source = Box::new(TestTimeSource { now: now.clone() });
167        let mut clock = Clock::with_time_source(source);
168
169        let s1 = clock.tick();
170        now.store(900, Ordering::SeqCst);
171        let s2 = clock.tick();
172
173        assert!(s2 > s1);
174        assert_eq!(s2.wall_ms, s1.wall_ms);
175    }
176
177    #[test]
178    fn forward_jump_advances_wall_time() {
179        let now = Arc::new(AtomicU64::new(1_000));
180        let source = Box::new(TestTimeSource { now: now.clone() });
181        let mut clock = Clock::with_time_source(source);
182
183        let s1 = clock.tick();
184        now.store(2_000, Ordering::SeqCst);
185        let s2 = clock.tick();
186
187        assert!(s2 > s1);
188        assert_eq!(s2.wall_ms, 2_000);
189    }
190}