Skip to main content

engenho_substrate_core/
relogio.rs

1//! relógio — typed deterministic clock + Hybrid Logical Clock (HLC).
2//!
3//! Per the research brief — the HIGHEST-leverage inventive
4//! primitive. Every substrate site that currently calls
5//! `std::time::SystemTime::now()` or accepts a raw `u64`
6//! timestamp gains a typed `Clock` trait + `Instant` value.
7//! The substrate becomes deterministic-at-the-type-level for
8//! tests (via `FrozenClock`) AND causally-ordered cross-node
9//! for federation (via `HlcClock` merge semantics).
10//!
11//! ## What ships
12//!
13//!   - `Instant` value (48-bit physical ms + 16-bit logical counter)
14//!     with total ordering + `causally_after` + serde + Fingerprint
15//!   - `Clock` trait — universal time surface, supertraits `Named`
16//!   - `WallClock` — production: `SystemTime::now()` based
17//!   - `FrozenClock` — tests: returns a fixed Instant; `advance()` mutates
18//!   - `LogicalClock` — deterministic counter; no wall-time at all
19//!   - `HlcClock` — HLC merge semantics for cross-node ordering
20//!
21//! ## Composition
22//!
23//!   - `Named` supertrait → every clock has telemetry name
24//!   - `Fingerprint` over `Instant` → deterministic bytes
25//!   - `Hex` over `Instant.to_bytes()` for log display
26//!   - Future: `MaterializationReceipt.emitted_at: Instant` (next round)
27
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::time::{SystemTime, UNIX_EPOCH};
30
31use serde::{Deserialize, Serialize};
32
33use crate::named::Named;
34
35/// Typed instant: 48-bit physical milliseconds since unix epoch +
36/// 16-bit logical counter. Packs into 64 bits, totally ordered.
37///
38/// Constraints:
39///   - `physical_ms < 2^48` (~8908 years from epoch — plenty)
40///   - `logical < 2^16` (65k ticks per ms in worst-case bursts)
41///
42/// Tie-breaking: lexicographic on (`physical_ms`, logical).
43#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44pub struct Instant {
45    /// Physical milliseconds since UNIX epoch.
46    pub physical_ms: u64,
47    /// Logical counter — increments when wall-clock doesn't advance.
48    pub logical: u16,
49}
50
51impl Instant {
52    /// Construct an Instant.
53    #[must_use]
54    pub fn new(physical_ms: u64, logical: u16) -> Self {
55        Self {
56            physical_ms,
57            logical,
58        }
59    }
60
61    /// The zero instant — useful for empty receipts + initial states.
62    #[must_use]
63    pub const fn zero() -> Self {
64        Self {
65            physical_ms: 0,
66            logical: 0,
67        }
68    }
69
70    /// Construct from a physical millisecond timestamp with logical=0.
71    /// Third-site extraction — pattern appeared in selo, orcamento, and
72    /// 4+ test sites before this constructor existed.
73    #[must_use]
74    pub const fn from_ms(physical_ms: u64) -> Self {
75        Self {
76            physical_ms,
77            logical: 0,
78        }
79    }
80
81    /// Pack into 64 bits: 48-bit physical | 16-bit logical.
82    /// `physical_ms` above 2^48 is silently saturated.
83    #[must_use]
84    pub fn to_packed(&self) -> u64 {
85        let phys = self.physical_ms & ((1u64 << 48) - 1);
86        (phys << 16) | u64::from(self.logical)
87    }
88
89    /// Unpack from 64-bit packed form.
90    #[must_use]
91    pub fn from_packed(packed: u64) -> Self {
92        let logical = (packed & 0xFFFF) as u16;
93        let physical_ms = packed >> 16;
94        Self {
95            physical_ms,
96            logical,
97        }
98    }
99
100    /// Canonical 8-byte representation (big-endian packed).
101    #[must_use]
102    pub fn to_bytes(&self) -> [u8; 8] {
103        self.to_packed().to_be_bytes()
104    }
105
106    /// Total order: returns true if `self` is strictly after `other`
107    /// in the (`physical_ms`, logical) lexicographic order.
108    #[must_use]
109    pub fn causally_after(&self, other: &Self) -> bool {
110        (self.physical_ms, self.logical) > (other.physical_ms, other.logical)
111    }
112
113    /// Tick: produce the next Instant at-or-after `now` that is
114    /// strictly greater than `previous`. Used by HLC merge.
115    ///
116    /// If `now > previous`, returns `now` (wall-clock advanced).
117    /// If `now <= previous`, returns `previous + 1 logical`.
118    #[must_use]
119    pub fn tick(now: Self, previous: Self) -> Self {
120        if now.causally_after(&previous) || now == previous {
121            if now == previous {
122                // Tie → bump logical counter on `now`.
123                Self {
124                    physical_ms: now.physical_ms,
125                    logical: now.logical.saturating_add(1),
126                }
127            } else {
128                now
129            }
130        } else {
131            // Wall clock went backward (NTP correction, sleep) →
132            // keep `previous.physical_ms` + bump logical.
133            Self {
134                physical_ms: previous.physical_ms,
135                logical: previous.logical.saturating_add(1),
136            }
137        }
138    }
139}
140
141impl PartialOrd for Instant {
142    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
143        Some(self.cmp(other))
144    }
145}
146
147impl Ord for Instant {
148    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
149        (self.physical_ms, self.logical).cmp(&(other.physical_ms, other.logical))
150    }
151}
152
153impl std::fmt::Display for Instant {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        write!(f, "{}.{:05}", self.physical_ms, self.logical)
156    }
157}
158
159crate::impl_fingerprint!(Instant);
160
161/// Universal clock surface. Implementers supply `now()`;
162/// HLC-aware implementers additionally implement `tick(observed)`.
163pub trait Clock: Named + Send + Sync {
164    /// Current instant per this clock's notion of time.
165    fn now(&self) -> Instant;
166
167    /// HLC merge: given an observed Instant from elsewhere, return
168    /// the next local Instant that is strictly after both `self.now()`
169    /// AND `observed`. Default implementation is wall-clock-based;
170    /// HLC-aware clocks override.
171    fn tick(&self, observed: Instant) -> Instant {
172        let now = self.now();
173        Instant::tick(now.max(observed), observed)
174    }
175
176    /// Unix timestamp in seconds (`now().physical_ms / 1000`). Provided
177    /// as a default method so the dozens of `SystemTime::now().duration_since(UNIX_EPOCH)`
178    /// idiom sites across the fleet migrate to one typed surface.
179    fn unix_secs(&self) -> u64 {
180        self.now().physical_ms / 1000
181    }
182
183    /// Unix timestamp in milliseconds (`now().physical_ms`). Synonym
184    /// of `now().physical_ms`; exists for symmetry with `unix_secs`.
185    fn unix_ms(&self) -> u64 {
186        self.now().physical_ms
187    }
188}
189
190// =================================================================
191// WallClock — production
192// =================================================================
193
194/// Production clock backed by `std::time::SystemTime::now()`.
195/// Returns Instant with current ms-since-epoch + logical 0.
196/// Use [`HlcClock`] for monotonicity within a process.
197#[derive(Default, Clone, Copy)]
198pub struct WallClock;
199
200crate::define_named!(WallClock, "wall");
201
202impl Clock for WallClock {
203    fn now(&self) -> Instant {
204        let physical_ms = SystemTime::now()
205            .duration_since(UNIX_EPOCH)
206            .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
207        Instant {
208            physical_ms,
209            logical: 0,
210        }
211    }
212}
213
214// =================================================================
215// FrozenClock — tests
216// =================================================================
217
218/// Test clock — returns a fixed Instant; mutable via `advance()`.
219/// Replaces the per-site `42`/`100` test timestamp pattern with
220/// one typed primitive.
221pub struct FrozenClock {
222    physical_ms: AtomicU64,
223    logical: AtomicU64, // u64 for atomic; cast to u16 on read
224}
225
226crate::define_named!(FrozenClock, "frozen");
227
228impl FrozenClock {
229    /// New clock pinned at `(physical_ms, 0)`.
230    #[must_use]
231    pub fn at(physical_ms: u64) -> Self {
232        Self {
233            physical_ms: AtomicU64::new(physical_ms),
234            logical: AtomicU64::new(0),
235        }
236    }
237
238    /// Advance physical wallclock by `ms`. Resets logical to 0.
239    pub fn advance(&self, ms: u64) {
240        self.physical_ms.fetch_add(ms, Ordering::SeqCst);
241        self.logical.store(0, Ordering::SeqCst);
242    }
243
244    /// Bump the logical counter (simulates same-millisecond tick).
245    pub fn tick_logical(&self) {
246        self.logical.fetch_add(1, Ordering::SeqCst);
247    }
248
249    /// Reset to (0, 0).
250    pub fn reset(&self) {
251        self.physical_ms.store(0, Ordering::SeqCst);
252        self.logical.store(0, Ordering::SeqCst);
253    }
254}
255
256impl Default for FrozenClock {
257    fn default() -> Self {
258        Self::at(0)
259    }
260}
261
262impl Clock for FrozenClock {
263    fn now(&self) -> Instant {
264        Instant {
265            physical_ms: self.physical_ms.load(Ordering::SeqCst),
266            logical: u16::try_from(self.logical.load(Ordering::SeqCst)).unwrap_or(u16::MAX),
267        }
268    }
269}
270
271// =================================================================
272// LogicalClock — pure counter, no wall time
273// =================================================================
274
275/// Deterministic logical-only clock. Every `now()` call returns
276/// (0, counter) with counter incrementing. Used when ordering
277/// matters but wallclock is irrelevant (search trial ordering,
278/// test fixture pinning).
279#[derive(Default)]
280pub struct LogicalClock {
281    counter: AtomicU64,
282}
283
284crate::define_named!(LogicalClock, "logical");
285
286impl LogicalClock {
287    /// New clock starting at counter 0.
288    #[must_use]
289    pub fn new() -> Self {
290        Self::default()
291    }
292
293    /// Current counter without advancing.
294    pub fn peek(&self) -> u64 {
295        self.counter.load(Ordering::SeqCst)
296    }
297}
298
299impl Clock for LogicalClock {
300    fn now(&self) -> Instant {
301        let n = self.counter.fetch_add(1, Ordering::SeqCst);
302        Instant {
303            physical_ms: 0,
304            logical: (n & 0xFFFF) as u16,
305        }
306    }
307}
308
309// =================================================================
310// HlcClock — Hybrid Logical Clock with monotonicity guarantees
311// =================================================================
312
313/// HLC clock — wraps a wall-clock source + ensures monotonicity
314/// across `now()` calls + correctly merges `observed` instants
315/// from peer nodes.
316pub struct HlcClock {
317    wall: WallClock,
318    last: std::sync::Mutex<Instant>,
319}
320
321crate::define_named!(HlcClock, "hlc");
322
323impl Default for HlcClock {
324    fn default() -> Self {
325        Self::new()
326    }
327}
328
329impl HlcClock {
330    /// New HLC starting at the current wall time.
331    #[must_use]
332    pub fn new() -> Self {
333        let wall = WallClock;
334        let initial = wall.now();
335        Self {
336            wall,
337            last: std::sync::Mutex::new(initial),
338        }
339    }
340}
341
342impl Clock for HlcClock {
343    fn now(&self) -> Instant {
344        let wall_now = self.wall.now();
345        let mut last = self.last.lock().unwrap();
346        *last = Instant::tick(wall_now, *last);
347        *last
348    }
349
350    fn tick(&self, observed: Instant) -> Instant {
351        let wall_now = self.wall.now();
352        let mut last = self.last.lock().unwrap();
353        // HLC merge: take max of (wall_now, observed, last) + bump logical
354        let candidate = wall_now.max(observed).max(*last);
355        *last = if candidate == *last || candidate == observed || candidate == wall_now {
356            Instant {
357                physical_ms: candidate.physical_ms,
358                logical: candidate.logical.saturating_add(1),
359            }
360        } else {
361            candidate
362        };
363        *last
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    // ── Instant: ordering, packing, ticking ────────────────────
372
373    #[test]
374    fn instant_total_order_lexicographic() {
375        let a = Instant::new(100, 5);
376        let b = Instant::new(100, 6);
377        let c = Instant::new(101, 0);
378        assert!(b > a);
379        assert!(c > b);
380        assert!(c > a);
381    }
382
383    #[test]
384    fn instant_zero_is_minimal() {
385        assert!(Instant::new(1, 0) > Instant::zero());
386        assert!(Instant::new(0, 1) > Instant::zero());
387    }
388
389    #[test]
390    fn instant_from_ms_yields_logical_zero() {
391        let i = Instant::from_ms(42_000);
392        assert_eq!(i.physical_ms, 42_000);
393        assert_eq!(i.logical, 0);
394        assert_eq!(i, Instant::new(42_000, 0));
395    }
396
397    #[test]
398    fn instant_from_ms_zero_equals_zero() {
399        assert_eq!(Instant::from_ms(0), Instant::zero());
400    }
401
402    #[test]
403    fn instant_pack_unpack_round_trip() {
404        for i in [
405            Instant::zero(),
406            Instant::new(1, 0),
407            Instant::new(0, 1),
408            Instant::new(1000, 5),
409            Instant::new(u64::MAX >> 16, u16::MAX),
410        ] {
411            assert_eq!(Instant::from_packed(i.to_packed()), i);
412        }
413    }
414
415    #[test]
416    fn instant_to_bytes_is_eight() {
417        let i = Instant::new(100, 5);
418        assert_eq!(i.to_bytes().len(), 8);
419    }
420
421    #[test]
422    fn instant_causally_after_strict() {
423        let a = Instant::new(10, 0);
424        let b = Instant::new(10, 0);
425        assert!(!a.causally_after(&b));
426        assert!(!b.causally_after(&a));
427    }
428
429    #[test]
430    fn instant_tick_advances_wall_clock_when_strictly_after() {
431        let prev = Instant::new(100, 5);
432        let now = Instant::new(200, 0);
433        let next = Instant::tick(now, prev);
434        assert_eq!(next, now);
435    }
436
437    #[test]
438    fn instant_tick_bumps_logical_on_tie() {
439        let prev = Instant::new(100, 5);
440        let now = Instant::new(100, 5);
441        let next = Instant::tick(now, prev);
442        assert_eq!(next, Instant::new(100, 6));
443    }
444
445    #[test]
446    fn instant_tick_bumps_logical_when_wall_goes_backward() {
447        let prev = Instant::new(200, 3);
448        let now = Instant::new(100, 0); // wall regressed
449        let next = Instant::tick(now, prev);
450        assert_eq!(next.physical_ms, 200);
451        assert_eq!(next.logical, 4);
452    }
453
454    #[test]
455    fn instant_display_renders_dot_separated() {
456        let i = Instant::new(1234, 42);
457        assert_eq!(format!("{i}"), "1234.00042");
458    }
459
460    #[test]
461    fn instant_serde_round_trips() {
462        let i = Instant::new(1234, 56);
463        let bytes = serde_json::to_vec(&i).unwrap();
464        let back: Instant = serde_json::from_slice(&bytes).unwrap();
465        assert_eq!(back, i);
466    }
467
468    #[test]
469    fn instant_fingerprint_deterministic() {
470        use crate::Fingerprint;
471        let i = Instant::new(1, 2);
472        assert_eq!(i.fingerprint(), i.fingerprint());
473    }
474
475    // ── WallClock ──────────────────────────────────────────────
476
477    #[test]
478    fn wallclock_now_returns_nonzero_recent_time() {
479        let w = WallClock;
480        let now = w.now();
481        // ~1.7e12 ms since epoch = ~2023+. Sanity, not exact.
482        assert!(now.physical_ms > 1_500_000_000_000);
483        assert_eq!(now.logical, 0);
484    }
485
486    #[test]
487    fn wallclock_named() {
488        assert_eq!(WallClock.name(), "wall");
489    }
490
491    // ── FrozenClock ───────────────────────────────────────────
492
493    #[test]
494    fn frozen_clock_returns_fixed_instant() {
495        let c = FrozenClock::at(1000);
496        assert_eq!(c.now(), Instant::new(1000, 0));
497        // Multiple calls stay frozen.
498        assert_eq!(c.now(), c.now());
499    }
500
501    #[test]
502    fn frozen_clock_advance_mutates_physical() {
503        let c = FrozenClock::at(100);
504        c.advance(50);
505        assert_eq!(c.now(), Instant::new(150, 0));
506    }
507
508    #[test]
509    fn frozen_clock_tick_logical_bumps_counter() {
510        let c = FrozenClock::at(100);
511        c.tick_logical();
512        c.tick_logical();
513        assert_eq!(c.now(), Instant::new(100, 2));
514    }
515
516    #[test]
517    fn frozen_clock_reset_zeroes_state() {
518        let c = FrozenClock::at(100);
519        c.advance(50);
520        c.tick_logical();
521        c.reset();
522        assert_eq!(c.now(), Instant::zero());
523    }
524
525    #[test]
526    fn frozen_clock_named() {
527        assert_eq!(FrozenClock::at(0).name(), "frozen");
528    }
529
530    // ── LogicalClock ──────────────────────────────────────────
531
532    #[test]
533    fn logical_clock_advances_on_now() {
534        let c = LogicalClock::new();
535        let a = c.now();
536        let b = c.now();
537        assert!(b > a);
538    }
539
540    #[test]
541    fn logical_clock_peek_doesnt_advance() {
542        let c = LogicalClock::new();
543        let _ = c.now(); // counter = 1
544        let p1 = c.peek();
545        let p2 = c.peek();
546        assert_eq!(p1, p2);
547    }
548
549    #[test]
550    fn logical_clock_named() {
551        assert_eq!(LogicalClock::new().name(), "logical");
552    }
553
554    // ── HlcClock ──────────────────────────────────────────────
555
556    #[test]
557    fn hlc_clock_now_is_monotonic() {
558        let c = HlcClock::new();
559        let a = c.now();
560        let b = c.now();
561        // Each call advances logical at minimum.
562        assert!(b > a);
563    }
564
565    #[test]
566    fn hlc_clock_tick_merges_with_observed() {
567        let c = HlcClock::new();
568        let observed = Instant::new(u64::MAX >> 16, 0); // far future
569        let merged = c.tick(observed);
570        // Local clock catches up to observed + bumps.
571        assert!(merged > observed);
572    }
573
574    #[test]
575    fn hlc_clock_named() {
576        assert_eq!(HlcClock::new().name(), "hlc");
577    }
578
579    // ── Polymorphic dispatch ──────────────────────────────────
580
581    #[test]
582    fn clock_trait_object_dispatch() {
583        let clocks: Vec<Box<dyn Clock>> = vec![
584            Box::new(WallClock),
585            Box::new(FrozenClock::at(100)),
586            Box::new(LogicalClock::new()),
587            Box::new(HlcClock::new()),
588        ];
589        for c in &clocks {
590            let _ = c.now();
591            let _ = c.name();
592        }
593    }
594}