//! Hybrid logical clock — the total order the fold rule compares against. //! //! Format: `<13-digit ms>:<4-digit counter>:`. The widths are fixed //! so plain string comparison IS the ordering: no parsing on the hot path, and //! SQLite can compare `_hlc` columns directly in SQL. The device id trails as a //! deterministic tiebreak, so two devices writing in the same millisecond never //! produce an ambiguous "equal" stamp. //! //! 13 digits covers wall-clock milliseconds to the year 2286; a timestamp that //! overflows it would break the ordering silently, so it refuses instead. use crate::error::{Result, StoreError}; const MS_WIDTH: usize = 13; const COUNTER_WIDTH: usize = 4; /// `10 ** 13 - 1`. pub const MAX_MS: i64 = 9_999_999_999_999; /// `10 ** 4 - 1`. pub const MAX_COUNTER: i64 = 9_999; #[derive(Debug, Clone, PartialEq, Eq)] pub struct HlcParts { pub ms: i64, pub counter: i64, pub device_id: String, } /// Split a stamp back into its parts. Device ids may contain colons — /// server-authored ops use `server:` ids, so a naive split truncates. pub fn hlc_parts(hlc: &str) -> Result { let malformed = || StoreError::encode(format!("malformed hlc: {hlc}")); let first = hlc.find(':').ok_or_else(malformed)?; let second = hlc[first + 1..] .find(':') .map(|index| index + first + 1) .ok_or_else(malformed)?; Ok(HlcParts { // `Number("")` is 0 and `Number("abc")` is NaN in TypeScript; neither // reaches production, and a parse failure here is the same refusal the // malformed shape gets. ms: hlc[..first].parse().map_err(|_| malformed())?, counter: hlc[first + 1..second].parse().map_err(|_| malformed())?, device_id: hlc[second + 1..].to_string(), }) } /// The next stamp for this device, never sorting at or before `last`. /// /// When the wall clock has advanced past the last stamp we take it and reset /// the counter. When it has not — the same millisecond, or a clock that jumped /// BACKWARDS — we hold the last millisecond and bump the counter, which is /// what keeps a device from losing to its own earlier write after an NTP /// correction. /// /// `now_ms` is the CALLER's: this crate never reads the clock (spec R7). pub fn next_hlc(device_id: &str, last: Option<&str>, now_ms: i64) -> Result { if !(0..=MAX_MS).contains(&now_ms) { return Err(StoreError::encode(format!( "hlc timestamp out of range: {now_ms}" ))); } let mut ms = now_ms; let mut counter = 0i64; if let Some(last) = last { let last = hlc_parts(last)?; if now_ms <= last.ms { ms = last.ms; counter = last.counter + 1; if counter > MAX_COUNTER { // 10k stamps inside one millisecond on one device: borrow from // the future rather than emit a stamp that sorts backwards — // and refuse, as an out-of-range `now_ms` is refused, when the // borrowed millisecond itself leaves the thirteen digits. ms = last.ms + 1; counter = 0; if ms > MAX_MS { return Err(StoreError::encode(format!( "hlc timestamp out of range after a counter carry: {ms}" ))); } } } } Ok(format!( "{ms:0MS_WIDTH$}:{counter:0COUNTER_WIDTH$}:{device_id}", MS_WIDTH = MS_WIDTH, COUNTER_WIDTH = COUNTER_WIDTH )) } /// The first stamp of a NEW author's stream: counter 0, at `now_ms` or at the /// millisecond above the last stamp this file holds, whichever is later. A /// stream starts at counter 0 (the author fact sits there, `cotton_authors. /// first_stamp`), and never below the file's clock, so the fact sorts above /// everything the file has already seen. pub fn first_stamp_of(author: &str, last: Option<&str>, now_ms: i64) -> Result { let mut ms = now_ms; if let Some(last) = last { let last = hlc_parts(last)?; if now_ms <= last.ms { ms = last.ms + 1; } } next_hlc(author, None, ms) } /// The stamp at counter 0 of millisecond `ms` under `device_id` — a BOUND /// another stamp is compared with or clamped to (the fold's adoption bound, /// H1), never a write's stamp: those are `mint`'s. pub fn bound_at(device_id: &str, ms: i64) -> Result { next_hlc(device_id, None, ms) } #[cfg(test)] mod tests { use super::*; const DEV_A: &str = "device:aaaa"; const DEV_B: &str = "device:bbbb"; fn hlc(device: &str, last: Option<&str>, now: i64) -> String { next_hlc(device, last, now).expect("a stamp inside the range") } #[test] fn stamps_the_wall_clock_when_it_has_moved_on() { let stamp = hlc(DEV_A, None, 1_700_000_000_000); assert_eq!( hlc_parts(&stamp).expect("parses"), HlcParts { ms: 1_700_000_000_000, counter: 0, device_id: DEV_A.to_string() } ); assert_eq!(stamp, "1700000000000:0000:device:aaaa"); } #[test] fn bumps_the_counter_when_the_clock_stands_still() { let first = hlc(DEV_A, None, 1_700_000_000_000); let second = hlc(DEV_A, Some(&first), 1_700_000_000_000); let third = hlc(DEV_A, Some(&second), 1_700_000_000_000); assert_eq!(hlc_parts(&second).expect("parses").counter, 1); assert_eq!(hlc_parts(&third).expect("parses").counter, 2); assert_eq!(hlc_parts(&third).expect("parses").ms, 1_700_000_000_000); } #[test] fn keeps_moving_forward_when_the_clock_goes_backwards() { // The invariant the whole protocol rests on: a device whose clock jumps // back must never emit an hlc that sorts before one it already emitted. let first = hlc(DEV_A, None, 1_700_000_000_000); let after = hlc(DEV_A, Some(&first), 1_600_000_000_000); assert!(after > first); assert_eq!(hlc_parts(&after).expect("parses").ms, 1_700_000_000_000); assert_eq!(hlc_parts(&after).expect("parses").counter, 1); } #[test] fn orders_by_string_comparison_across_ms_counter_and_device() { let early = hlc(DEV_A, None, 1_700_000_000_000); let late = hlc(DEV_A, None, 1_700_000_000_001); assert!(late > early); let bumped = hlc(DEV_A, Some(&early), 1_700_000_000_000); assert!(bumped > early); assert!(late > bumped); // Same ms and counter: the device id is the deterministic tiebreak. let from_a = hlc(DEV_A, None, 1_700_000_000_000); let from_b = hlc(DEV_B, None, 1_700_000_000_000); assert!(from_b > from_a); } #[test] fn pads_so_a_bigger_number_never_sorts_before_a_smaller_one() { let small = hlc(DEV_A, None, 999); let big = hlc(DEV_A, None, 1_700_000_000_000); assert!(big > small); let mut parts = small.splitn(3, ':'); assert_eq!(parts.next().expect("ms").len(), 13); assert_eq!(parts.next().expect("counter").len(), 4); assert_eq!(small, "0000000000999:0000:device:aaaa"); } #[test] fn round_trips_through_hlc_parts() { let stamp = hlc(DEV_A, None, 1_712_345_678_901); let parts = hlc_parts(&stamp).expect("parses"); assert_eq!( parts, HlcParts { ms: 1_712_345_678_901, counter: 0, device_id: DEV_A.to_string() } ); assert_eq!(hlc(&parts.device_id, None, parts.ms), stamp); } #[test] fn keeps_a_device_id_containing_colons_intact() { let stamp = hlc("device:serving-mac", None, 1_700_000_000_000); assert_eq!( hlc_parts(&stamp).expect("parses").device_id, "device:serving-mac" ); } #[test] fn a_counter_overflow_borrows_a_millisecond_rather_than_sorting_backwards() { let full = format!("1700000000000:{MAX_COUNTER:04}:{DEV_A}"); let next = hlc(DEV_A, Some(&full), 1_700_000_000_000); assert_eq!(next, "1700000000001:0000:device:aaaa"); assert!(next > full); } #[test] fn refuses_a_timestamp_outside_the_thirteen_digit_window() { assert!(next_hlc(DEV_A, None, -1).is_err()); assert!(next_hlc(DEV_A, None, MAX_MS + 1).is_err()); assert!(next_hlc(DEV_A, None, MAX_MS).is_ok()); } /// RULE: A counter carry refuses milliseconds past MAX_MS, because a fourteen-digit stamp sorts below every valid one. /// This is the same refusal as an out-of-range `now_ms` (F3). #[test] fn next_hlc_refuses_ms_overflow_after_counter_carry() { let full = format!("{MAX_MS}:{MAX_COUNTER:04}:{DEV_A}"); assert!(next_hlc(DEV_A, Some(&full), MAX_MS).is_err()); let below = format!("{}:{MAX_COUNTER:04}:{DEV_A}", MAX_MS - 1); assert_eq!( hlc(DEV_A, Some(&below), MAX_MS - 1), format!("{MAX_MS}:0000:{DEV_A}") ); } #[test] fn refuses_a_malformed_stamp() { assert!(hlc_parts("nope").is_err()); assert!(hlc_parts("1700000000000:0000").is_err()); } }