engenho-substrate-core 0.53.154

engenho-substrate-core — the tokio-free core of engenho's substrate: typed error kinds, names, hex and BLAKE3 hash newtypes, fingerprints, atomic writes, magic-headered blobs, redaction and clocks. No async runtime is a dependency, so none can be used here.
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! relógio — typed deterministic clock + Hybrid Logical Clock (HLC).
//!
//! Per the research brief — the HIGHEST-leverage inventive
//! primitive. Every substrate site that currently calls
//! `std::time::SystemTime::now()` or accepts a raw `u64`
//! timestamp gains a typed `Clock` trait + `Instant` value.
//! The substrate becomes deterministic-at-the-type-level for
//! tests (via `FrozenClock`) AND causally-ordered cross-node
//! for federation (via `HlcClock` merge semantics).
//!
//! ## What ships
//!
//!   - `Instant` value (48-bit physical ms + 16-bit logical counter)
//!     with total ordering + causally_after + serde + Fingerprint
//!   - `Clock` trait — universal time surface, supertraits `Named`
//!   - `WallClock` — production: `SystemTime::now()` based
//!   - `FrozenClock` — tests: returns a fixed Instant; `advance()` mutates
//!   - `LogicalClock` — deterministic counter; no wall-time at all
//!   - `HlcClock` — HLC merge semantics for cross-node ordering
//!
//! ## Composition
//!
//!   - `Named` supertrait → every clock has telemetry name
//!   - `Fingerprint` over `Instant` → deterministic bytes
//!   - `Hex` over Instant.to_bytes() for log display
//!   - Future: `MaterializationReceipt.emitted_at: Instant` (next round)

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::named::Named;

/// Typed instant: 48-bit physical milliseconds since unix epoch +
/// 16-bit logical counter. Packs into 64 bits, totally ordered.
///
/// Constraints:
///   - `physical_ms < 2^48` (~8908 years from epoch — plenty)
///   - `logical < 2^16` (65k ticks per ms in worst-case bursts)
///
/// Tie-breaking: lexicographic on (physical_ms, logical).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Instant {
    /// Physical milliseconds since UNIX epoch.
    pub physical_ms: u64,
    /// Logical counter — increments when wall-clock doesn't advance.
    pub logical: u16,
}

impl Instant {
    /// Construct an Instant.
    #[must_use]
    pub fn new(physical_ms: u64, logical: u16) -> Self {
        Self {
            physical_ms,
            logical,
        }
    }

    /// The zero instant — useful for empty receipts + initial states.
    #[must_use]
    pub const fn zero() -> Self {
        Self {
            physical_ms: 0,
            logical: 0,
        }
    }

    /// Construct from a physical millisecond timestamp with logical=0.
    /// Third-site extraction — pattern appeared in selo, orcamento, and
    /// 4+ test sites before this constructor existed.
    #[must_use]
    pub const fn from_ms(physical_ms: u64) -> Self {
        Self {
            physical_ms,
            logical: 0,
        }
    }

    /// Pack into 64 bits: 48-bit physical | 16-bit logical.
    /// `physical_ms` above 2^48 is silently saturated.
    #[must_use]
    pub fn to_packed(&self) -> u64 {
        let phys = self.physical_ms & ((1u64 << 48) - 1);
        (phys << 16) | u64::from(self.logical)
    }

    /// Unpack from 64-bit packed form.
    #[must_use]
    pub fn from_packed(packed: u64) -> Self {
        let logical = (packed & 0xFFFF) as u16;
        let physical_ms = packed >> 16;
        Self {
            physical_ms,
            logical,
        }
    }

    /// Canonical 8-byte representation (big-endian packed).
    #[must_use]
    pub fn to_bytes(&self) -> [u8; 8] {
        self.to_packed().to_be_bytes()
    }

    /// Total order: returns true if `self` is strictly after `other`
    /// in the (physical_ms, logical) lexicographic order.
    #[must_use]
    pub fn causally_after(&self, other: &Self) -> bool {
        (self.physical_ms, self.logical) > (other.physical_ms, other.logical)
    }

    /// Tick: produce the next Instant at-or-after `now` that is
    /// strictly greater than `previous`. Used by HLC merge.
    ///
    /// If `now > previous`, returns `now` (wall-clock advanced).
    /// If `now <= previous`, returns `previous + 1 logical`.
    #[must_use]
    pub fn tick(now: Self, previous: Self) -> Self {
        if now.causally_after(&previous) || now == previous {
            if now == previous {
                // Tie → bump logical counter on `now`.
                Self {
                    physical_ms: now.physical_ms,
                    logical: now.logical.saturating_add(1),
                }
            } else {
                now
            }
        } else {
            // Wall clock went backward (NTP correction, sleep) →
            // keep `previous.physical_ms` + bump logical.
            Self {
                physical_ms: previous.physical_ms,
                logical: previous.logical.saturating_add(1),
            }
        }
    }
}

impl PartialOrd for Instant {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Instant {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (self.physical_ms, self.logical).cmp(&(other.physical_ms, other.logical))
    }
}

impl std::fmt::Display for Instant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{:05}", self.physical_ms, self.logical)
    }
}

crate::impl_fingerprint!(Instant);

/// Universal clock surface. Implementers supply `now()`;
/// HLC-aware implementers additionally implement `tick(observed)`.
pub trait Clock: Named + Send + Sync {
    /// Current instant per this clock's notion of time.
    fn now(&self) -> Instant;

    /// HLC merge: given an observed Instant from elsewhere, return
    /// the next local Instant that is strictly after both `self.now()`
    /// AND `observed`. Default implementation is wall-clock-based;
    /// HLC-aware clocks override.
    fn tick(&self, observed: Instant) -> Instant {
        let now = self.now();
        Instant::tick(now.max(observed), observed)
    }

    /// Unix timestamp in seconds (`now().physical_ms / 1000`). Provided
    /// as a default method so the dozens of `SystemTime::now().duration_since(UNIX_EPOCH)`
    /// idiom sites across the fleet migrate to one typed surface.
    fn unix_secs(&self) -> u64 {
        self.now().physical_ms / 1000
    }

    /// Unix timestamp in milliseconds (`now().physical_ms`). Synonym
    /// of `now().physical_ms`; exists for symmetry with `unix_secs`.
    fn unix_ms(&self) -> u64 {
        self.now().physical_ms
    }
}

// =================================================================
// WallClock — production
// =================================================================

/// Production clock backed by `std::time::SystemTime::now()`.
/// Returns Instant with current ms-since-epoch + logical 0.
/// Use [`HlcClock`] for monotonicity within a process.
#[derive(Default, Clone, Copy)]
pub struct WallClock;

crate::define_named!(WallClock, "wall");

impl Clock for WallClock {
    fn now(&self) -> Instant {
        let physical_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        Instant {
            physical_ms,
            logical: 0,
        }
    }
}

// =================================================================
// FrozenClock — tests
// =================================================================

/// Test clock — returns a fixed Instant; mutable via `advance()`.
/// Replaces the per-site `42`/`100` test timestamp pattern with
/// one typed primitive.
pub struct FrozenClock {
    physical_ms: AtomicU64,
    logical: AtomicU64, // u64 for atomic; cast to u16 on read
}

crate::define_named!(FrozenClock, "frozen");

impl FrozenClock {
    /// New clock pinned at `(physical_ms, 0)`.
    #[must_use]
    pub fn at(physical_ms: u64) -> Self {
        Self {
            physical_ms: AtomicU64::new(physical_ms),
            logical: AtomicU64::new(0),
        }
    }

    /// Advance physical wallclock by `ms`. Resets logical to 0.
    pub fn advance(&self, ms: u64) {
        self.physical_ms.fetch_add(ms, Ordering::SeqCst);
        self.logical.store(0, Ordering::SeqCst);
    }

    /// Bump the logical counter (simulates same-millisecond tick).
    pub fn tick_logical(&self) {
        self.logical.fetch_add(1, Ordering::SeqCst);
    }

    /// Reset to (0, 0).
    pub fn reset(&self) {
        self.physical_ms.store(0, Ordering::SeqCst);
        self.logical.store(0, Ordering::SeqCst);
    }
}

impl Default for FrozenClock {
    fn default() -> Self {
        Self::at(0)
    }
}

impl Clock for FrozenClock {
    fn now(&self) -> Instant {
        Instant {
            physical_ms: self.physical_ms.load(Ordering::SeqCst),
            logical: self.logical.load(Ordering::SeqCst) as u16,
        }
    }
}

// =================================================================
// LogicalClock — pure counter, no wall time
// =================================================================

/// Deterministic logical-only clock. Every `now()` call returns
/// (0, counter) with counter incrementing. Used when ordering
/// matters but wallclock is irrelevant (search trial ordering,
/// test fixture pinning).
#[derive(Default)]
pub struct LogicalClock {
    counter: AtomicU64,
}

crate::define_named!(LogicalClock, "logical");

impl LogicalClock {
    /// New clock starting at counter 0.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Current counter without advancing.
    pub fn peek(&self) -> u64 {
        self.counter.load(Ordering::SeqCst)
    }
}

impl Clock for LogicalClock {
    fn now(&self) -> Instant {
        let n = self.counter.fetch_add(1, Ordering::SeqCst);
        Instant {
            physical_ms: 0,
            logical: (n & 0xFFFF) as u16,
        }
    }
}

// =================================================================
// HlcClock — Hybrid Logical Clock with monotonicity guarantees
// =================================================================

/// HLC clock — wraps a wall-clock source + ensures monotonicity
/// across `now()` calls + correctly merges `observed` instants
/// from peer nodes.
pub struct HlcClock {
    wall: WallClock,
    last: std::sync::Mutex<Instant>,
}

crate::define_named!(HlcClock, "hlc");

impl Default for HlcClock {
    fn default() -> Self {
        Self::new()
    }
}

impl HlcClock {
    /// New HLC starting at the current wall time.
    #[must_use]
    pub fn new() -> Self {
        let wall = WallClock;
        let initial = wall.now();
        Self {
            wall,
            last: std::sync::Mutex::new(initial),
        }
    }
}

impl Clock for HlcClock {
    fn now(&self) -> Instant {
        let wall_now = self.wall.now();
        let mut last = self.last.lock().unwrap();
        *last = Instant::tick(wall_now, *last);
        *last
    }

    fn tick(&self, observed: Instant) -> Instant {
        let wall_now = self.wall.now();
        let mut last = self.last.lock().unwrap();
        // HLC merge: take max of (wall_now, observed, last) + bump logical
        let candidate = wall_now.max(observed).max(*last);
        *last = if candidate == *last || candidate == observed || candidate == wall_now {
            Instant {
                physical_ms: candidate.physical_ms,
                logical: candidate.logical.saturating_add(1),
            }
        } else {
            candidate
        };
        *last
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Instant: ordering, packing, ticking ────────────────────

    #[test]
    fn instant_total_order_lexicographic() {
        let a = Instant::new(100, 5);
        let b = Instant::new(100, 6);
        let c = Instant::new(101, 0);
        assert!(b > a);
        assert!(c > b);
        assert!(c > a);
    }

    #[test]
    fn instant_zero_is_minimal() {
        assert!(Instant::new(1, 0) > Instant::zero());
        assert!(Instant::new(0, 1) > Instant::zero());
    }

    #[test]
    fn instant_from_ms_yields_logical_zero() {
        let i = Instant::from_ms(42_000);
        assert_eq!(i.physical_ms, 42_000);
        assert_eq!(i.logical, 0);
        assert_eq!(i, Instant::new(42_000, 0));
    }

    #[test]
    fn instant_from_ms_zero_equals_zero() {
        assert_eq!(Instant::from_ms(0), Instant::zero());
    }

    #[test]
    fn instant_pack_unpack_round_trip() {
        for i in [
            Instant::zero(),
            Instant::new(1, 0),
            Instant::new(0, 1),
            Instant::new(1000, 5),
            Instant::new(u64::MAX >> 16, u16::MAX),
        ] {
            assert_eq!(Instant::from_packed(i.to_packed()), i);
        }
    }

    #[test]
    fn instant_to_bytes_is_eight() {
        let i = Instant::new(100, 5);
        assert_eq!(i.to_bytes().len(), 8);
    }

    #[test]
    fn instant_causally_after_strict() {
        let a = Instant::new(10, 0);
        let b = Instant::new(10, 0);
        assert!(!a.causally_after(&b));
        assert!(!b.causally_after(&a));
    }

    #[test]
    fn instant_tick_advances_wall_clock_when_strictly_after() {
        let prev = Instant::new(100, 5);
        let now = Instant::new(200, 0);
        let next = Instant::tick(now, prev);
        assert_eq!(next, now);
    }

    #[test]
    fn instant_tick_bumps_logical_on_tie() {
        let prev = Instant::new(100, 5);
        let now = Instant::new(100, 5);
        let next = Instant::tick(now, prev);
        assert_eq!(next, Instant::new(100, 6));
    }

    #[test]
    fn instant_tick_bumps_logical_when_wall_goes_backward() {
        let prev = Instant::new(200, 3);
        let now = Instant::new(100, 0); // wall regressed
        let next = Instant::tick(now, prev);
        assert_eq!(next.physical_ms, 200);
        assert_eq!(next.logical, 4);
    }

    #[test]
    fn instant_display_renders_dot_separated() {
        let i = Instant::new(1234, 42);
        assert_eq!(format!("{i}"), "1234.00042");
    }

    #[test]
    fn instant_serde_round_trips() {
        let i = Instant::new(1234, 56);
        let bytes = serde_json::to_vec(&i).unwrap();
        let back: Instant = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(back, i);
    }

    #[test]
    fn instant_fingerprint_deterministic() {
        use crate::Fingerprint;
        let i = Instant::new(1, 2);
        assert_eq!(i.fingerprint(), i.fingerprint());
    }

    // ── WallClock ──────────────────────────────────────────────

    #[test]
    fn wallclock_now_returns_nonzero_recent_time() {
        let w = WallClock;
        let now = w.now();
        // ~1.7e12 ms since epoch = ~2023+. Sanity, not exact.
        assert!(now.physical_ms > 1_500_000_000_000);
        assert_eq!(now.logical, 0);
    }

    #[test]
    fn wallclock_named() {
        assert_eq!(WallClock.name(), "wall");
    }

    // ── FrozenClock ───────────────────────────────────────────

    #[test]
    fn frozen_clock_returns_fixed_instant() {
        let c = FrozenClock::at(1000);
        assert_eq!(c.now(), Instant::new(1000, 0));
        // Multiple calls stay frozen.
        assert_eq!(c.now(), c.now());
    }

    #[test]
    fn frozen_clock_advance_mutates_physical() {
        let c = FrozenClock::at(100);
        c.advance(50);
        assert_eq!(c.now(), Instant::new(150, 0));
    }

    #[test]
    fn frozen_clock_tick_logical_bumps_counter() {
        let c = FrozenClock::at(100);
        c.tick_logical();
        c.tick_logical();
        assert_eq!(c.now(), Instant::new(100, 2));
    }

    #[test]
    fn frozen_clock_reset_zeroes_state() {
        let c = FrozenClock::at(100);
        c.advance(50);
        c.tick_logical();
        c.reset();
        assert_eq!(c.now(), Instant::zero());
    }

    #[test]
    fn frozen_clock_named() {
        assert_eq!(FrozenClock::at(0).name(), "frozen");
    }

    // ── LogicalClock ──────────────────────────────────────────

    #[test]
    fn logical_clock_advances_on_now() {
        let c = LogicalClock::new();
        let a = c.now();
        let b = c.now();
        assert!(b > a);
    }

    #[test]
    fn logical_clock_peek_doesnt_advance() {
        let c = LogicalClock::new();
        let _ = c.now(); // counter = 1
        let p1 = c.peek();
        let p2 = c.peek();
        assert_eq!(p1, p2);
    }

    #[test]
    fn logical_clock_named() {
        assert_eq!(LogicalClock::new().name(), "logical");
    }

    // ── HlcClock ──────────────────────────────────────────────

    #[test]
    fn hlc_clock_now_is_monotonic() {
        let c = HlcClock::new();
        let a = c.now();
        let b = c.now();
        // Each call advances logical at minimum.
        assert!(b > a);
    }

    #[test]
    fn hlc_clock_tick_merges_with_observed() {
        let c = HlcClock::new();
        let observed = Instant::new(u64::MAX >> 16, 0); // far future
        let merged = c.tick(observed);
        // Local clock catches up to observed + bumps.
        assert!(merged > observed);
    }

    #[test]
    fn hlc_clock_named() {
        assert_eq!(HlcClock::new().name(), "hlc");
    }

    // ── Polymorphic dispatch ──────────────────────────────────

    #[test]
    fn clock_trait_object_dispatch() {
        let clocks: Vec<Box<dyn Clock>> = vec![
            Box::new(WallClock),
            Box::new(FrozenClock::at(100)),
            Box::new(LogicalClock::new()),
            Box::new(HlcClock::new()),
        ];
        for c in &clocks {
            let _ = c.now();
            let _ = c.name();
        }
    }
}