Skip to main content

agentmux_srv_core/backend/user_sync/
hlc.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The hybrid logical clock that orders a collection's records (SPEC_USER_DATA_SYNC_LAYER ยง3.2): wall
5//! milliseconds, a counter for changes in the same millisecond, and the machine that made the change, so any
6//! two versions are totally ordered. A version far ahead of the receiver's own clock is refused, so a machine
7//! with a wrong clock cannot win every merge.
8
9use std::cmp::Ordering;
10
11use serde::{Deserialize, Serialize};
12
13/// How far ahead of the receiver's clock a version may be before it is refused.
14pub const MAX_SKEW_MS: i64 = 5 * 60 * 1000;
15
16/// A record's version: ordered by wall time, then counter, then machine.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Version {
19    pub wall_ms: i64,
20    pub counter: u32,
21    /// The machine that made the change (its pinned instance identifier).
22    pub machine: String,
23}
24
25impl Ord for Version {
26    fn cmp(&self, other: &Self) -> Ordering {
27        (self.wall_ms, self.counter, &self.machine).cmp(&(other.wall_ms, other.counter, &other.machine))
28    }
29}
30
31impl PartialOrd for Version {
32    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
33        Some(self.cmp(other))
34    }
35}
36
37/// A version was too far ahead of this machine's clock.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39pub struct SkewRefused {
40    /// How far ahead of this machine's clock it was.
41    pub ahead_ms: i64,
42}
43
44/// One machine's clock for one collection.
45#[derive(Debug, Clone)]
46pub struct Clock {
47    machine: String,
48    last_wall: i64,
49    last_counter: u32,
50}
51
52impl Clock {
53    pub fn new(machine: &str) -> Clock {
54        Clock { machine: machine.to_string(), last_wall: 0, last_counter: 0 }
55    }
56
57    /// The version of a change made here at `now_ms`; always after every version this clock has made or seen.
58    pub fn tick(&mut self, now_ms: i64) -> Version {
59        if now_ms > self.last_wall {
60            self.last_wall = now_ms;
61            self.last_counter = 0;
62        } else if let Some(next) = self.last_counter.checked_add(1) {
63            self.last_counter = next;
64        } else {
65            // The counter is full (a received version can carry any counter): carry into the wall time.
66            self.last_wall += 1;
67            self.last_counter = 0;
68        }
69        Version { wall_ms: self.last_wall, counter: self.last_counter, machine: self.machine.clone() }
70    }
71
72    /// Takes in a version seen from another machine, so the next one made here is after it; refuses one more
73    /// than [`MAX_SKEW_MS`] ahead of `now_ms`.
74    pub fn observe(&mut self, seen: &Version, now_ms: i64) -> Result<(), SkewRefused> {
75        let ahead = seen.wall_ms - now_ms;
76        if ahead > MAX_SKEW_MS {
77            return Err(SkewRefused { ahead_ms: ahead });
78        }
79        self.raise(seen);
80        Ok(())
81    }
82
83    /// Moves the clock to at least `held`, a version already stored here (no skew check: it was accepted when it
84    /// was stored). A clock made fresh after a restart is raised this way, so it never makes a version at or
85    /// before one already held.
86    pub fn raise(&mut self, held: &Version) {
87        if held.wall_ms > self.last_wall {
88            self.last_wall = held.wall_ms;
89            self.last_counter = held.counter;
90        } else if held.wall_ms == self.last_wall && held.counter > self.last_counter {
91            self.last_counter = held.counter;
92        }
93    }
94}