syncspin_core/clock.rs
1//! Clock synchronisation: a two-dimensional Kalman filter over clock offset and drift.
2//!
3//! The filter turns `server/time` round trips into a mapping from the local monotonic clock to
4//! the server clock. One exchange is a [`TimeSample`] with four timestamps, all in microseconds:
5//!
6//! ```text
7//! client_sent_us T1 local time when the request left
8//! server_received_us T2 server time when the request arrived
9//! server_sent_us T3 server time when the answer left
10//! client_received_us T4 local time when the answer arrived
11//! ```
12//!
13//! Each sample yields one offset measurement (server clock minus local clock) and one error
14//! bound for it, both in microseconds:
15//!
16//! ```text
17//! measurement = ((T2 - T1) + (T3 - T4)) / 2
18//! max_error = ((T4 - T1) - (T3 - T2)) / 2
19//! ```
20//!
21//! The integer arithmetic divides with truncation toward zero, as the protocol specifies. The
22//! measurement enters a Kalman filter whose state is the offset and the drift (the rate at which
23//! the offset changes, in microseconds per microsecond):
24//!
25//! * the offset performs a random walk with diffusion `PROCESS_STD_DEV` and the drift one with
26//! `DRIFT_PROCESS_STD_DEV`;
27//! * the measurement variance grows with `max_error`, so a sample that crossed a stalled queue
28//! moves the estimate far less than a quick one - that is the outlier handling, and it needs no
29//! special case;
30//! * once `ADAPTIVE_FORGETTING_AFTER` samples are in, a residual larger than `ADAPTIVE_CUTOFF`
31//! times the error bound inflates the covariance by `FORGET_FACTOR`², so the filter can follow a
32//! genuine step instead of treating it as noise;
33//! * drift is applied to a conversion only while it is statistically significant.
34//!
35//! Readiness ([`ClockFilter::is_ready`]) is an availability signal, not an accuracy guarantee: it
36//! says that an estimate exists, not that it is fresh or good. The estimate's error grows with the
37//! distance from [`ClockFilter::last_sample_us`], so a caller that needs a bounded error keeps
38//! feeding samples. The published algorithm has a single 100-sample cutoff, after which adaptive
39//! forgetting may start; this module keeps that cutoff for its own purpose and adds a separate,
40//! much earlier threshold for availability, because the two answer different questions.
41//!
42//! Local timestamps must be positive. The filter starts with `last_sample_us == 0` and discards a
43//! sample that does not advance it, so a local clock that reads zero or less never gets a sample
44//! accepted and never becomes ready.
45//!
46//! The module is pure computation: no I/O, no clock reads, no blocking. The caller owns time.
47
48/// Offset random-walk diffusion, in µs per √µs.
49const PROCESS_STD_DEV: f64 = 0.0;
50
51/// Drift random-walk diffusion, in 1 per õs.
52const DRIFT_PROCESS_STD_DEV: f64 = 1e-11;
53
54/// Value greater than 1 whose square scales the covariances on a large residual.
55const FORGET_FACTOR: f64 = 2.0;
56
57/// Multiple of `max_error` above which a residual counts as large.
58const ADAPTIVE_CUTOFF: f64 = 3.0;
59
60/// Scale from `max_error` to the measurement standard deviation.
61const MAX_ERROR_SCALE: f64 = 0.5;
62
63/// Ratio of `drift` to its standard deviation above which drift is applied to conversions.
64const DRIFT_SIGNIFICANCE_THRESHOLD: f64 = 2.0;
65
66/// Number of accepted samples after which adaptive forgetting may apply.
67const ADAPTIVE_FORGETTING_AFTER: usize = 100;
68
69/// Number of accepted samples [`ClockFilter`] needs before it reports an estimate.
70///
71/// Three is the smallest count for which every stage of the filter has run: the first sample seeds
72/// the offset, the second seeds the drift, and the third performs the first full predict/correct
73/// cycle. This is an availability threshold, not an accuracy one - see
74/// [`ClockFilter::is_ready`].
75pub const READY_AFTER_SAMPLES: usize = 3;
76
77/// The four timestamps of one round trip, in microseconds.
78///
79/// The two `client_*` fields come from the local monotonic clock and the two `server_*` fields
80/// from the server clock; they need not share an epoch or a rate.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct TimeSample {
83 /// Local time when the request was sent.
84 pub client_sent_us: i64,
85 /// Server time when the request arrived.
86 pub server_received_us: i64,
87 /// Server time when the answer was sent.
88 pub server_sent_us: i64,
89 /// Local time when the answer arrived.
90 pub client_received_us: i64,
91}
92
93/// Two-dimensional Kalman filter over clock offset and drift.
94///
95/// Feed it every `server/time` reply with [`ClockFilter::push`] and ask it for the matching server
96/// timestamp with [`ClockFilter::now_us`], or the matching local timestamp with
97/// [`ClockFilter::client_time_us`]. Clone it to snapshot an estimate; the clone is independent.
98#[derive(Debug, Clone)]
99pub struct ClockFilter {
100 /// Estimated server clock minus local clock, in microseconds.
101 offset: f64,
102 /// Estimated rate of change of the offset, in microseconds per microsecond.
103 drift: f64,
104 /// Offset variance.
105 p_oo: f64,
106 /// Offset-drift covariance.
107 p_od: f64,
108 /// Drift variance.
109 p_dd: f64,
110 /// `client_received_us` of the last accepted sample.
111 last_accepted_us: i64,
112 /// Accepted samples, saturating at `usize::MAX`.
113 count: usize,
114 /// Whether `drift` is significant enough to apply during a conversion.
115 use_drift: bool,
116}
117
118impl Default for ClockFilter {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124impl ClockFilter {
125 /// Creates a filter with an infinite offset variance and no samples.
126 pub fn new() -> Self {
127 Self {
128 offset: 0.0,
129 drift: 0.0,
130 p_oo: f64::INFINITY,
131 p_od: 0.0,
132 p_dd: 0.0,
133 last_accepted_us: 0,
134 count: 0,
135 use_drift: false,
136 }
137 }
138
139 /// Folds one round trip into the estimate.
140 ///
141 /// A sample is discarded, leaving the estimate and [`ClockFilter::sample_count`] untouched,
142 /// when its error bound is not positive or when it would not advance the filter in time -
143 /// that is, when `client_received_us` is not later than the last accepted sample's.
144 ///
145 /// Local timestamps must be positive. The filter starts at `last_sample_us == 0` and discards
146 /// any sample that does not advance it, so a local clock reading zero or less never sees a
147 /// sample accepted.
148 pub fn push(&mut self, sample: TimeSample) {
149 let t1 = sample.client_sent_us as i128;
150 let t2 = sample.server_received_us as i128;
151 let t3 = sample.server_sent_us as i128;
152 let t4 = sample.client_received_us as i128;
153
154 // Integer division truncates toward zero, matching the protocol's `/ 2`.
155 let measurement_i = ((t2 - t1) + (t3 - t4)) / 2;
156 let max_error_i = ((t4 - t1) - (t3 - t2)) / 2;
157
158 if sample.client_received_us <= self.last_accepted_us || max_error_i <= 0 {
159 return;
160 }
161
162 let measurement = measurement_i as f64;
163 let max_error = max_error_i as f64;
164 let dt = sample
165 .client_received_us
166 .saturating_sub(self.last_accepted_us) as f64;
167 self.last_accepted_us = sample.client_received_us;
168
169 // Measurement variance.
170 let r = (MAX_ERROR_SCALE * max_error).powi(2);
171
172 if self.count == 0 {
173 self.offset = measurement;
174 self.p_oo = r;
175 self.drift = 0.0;
176 self.count = 1;
177 return;
178 }
179
180 if self.count == 1 {
181 self.drift = (measurement - self.offset) / dt;
182 self.p_dd = (self.p_oo + r) / (dt * dt);
183 self.offset = measurement;
184 self.p_oo = r;
185 self.count = 2;
186 return;
187 }
188
189 // Predict.
190 let offset_p = self.offset + self.drift * dt;
191 let mut p_oo_p =
192 self.p_oo + 2.0 * self.p_od * dt + self.p_dd * dt * dt + PROCESS_STD_DEV.powi(2) * dt;
193 let mut p_od_p = self.p_od + self.p_dd * dt;
194 let mut p_dd_p = self.p_dd + DRIFT_PROCESS_STD_DEV.powi(2) * dt;
195
196 let residual = measurement - offset_p;
197 // Adaptive forgetting only starts once enough samples are behind the filter: a large
198 // residual then means the offset really stepped rather than that one packet was slow.
199 if self.count >= ADAPTIVE_FORGETTING_AFTER && residual.abs() > ADAPTIVE_CUTOFF * max_error {
200 let scale = FORGET_FACTOR.powi(2);
201 p_oo_p *= scale;
202 p_od_p *= scale;
203 p_dd_p *= scale;
204 }
205
206 // Correct.
207 let s = p_oo_p + r;
208 let k_o = p_oo_p / s;
209 let k_d = p_od_p / s;
210 self.offset = offset_p + k_o * residual;
211 self.drift += k_d * residual;
212 self.p_oo = p_oo_p - k_o * p_oo_p;
213 self.p_od = p_od_p - k_d * p_oo_p;
214 self.p_dd = p_dd_p - k_d * p_od_p;
215 self.count = self.count.saturating_add(1);
216 self.use_drift = self.drift * self.drift > DRIFT_SIGNIFICANCE_THRESHOLD.powi(2) * self.p_dd;
217 }
218
219 /// Reports whether an estimate exists.
220 ///
221 /// True once [`READY_AFTER_SAMPLES`] samples have been accepted. This is an availability
222 /// signal, not an accuracy guarantee: it says nothing about how fresh or how good the estimate
223 /// is. Its error grows with the distance from [`ClockFilter::last_sample_us`].
224 #[must_use]
225 pub fn is_ready(&self) -> bool {
226 self.count >= READY_AFTER_SAMPLES
227 }
228
229 /// Returns the server clock reading that corresponds to the local reading `local_us`.
230 ///
231 /// Drift is applied only while it is statistically significant, matching the protocol.
232 /// Returns `None` until the filter is ready; readiness means an estimate exists, not that it
233 /// is fresh, so the error grows with the distance from [`ClockFilter::last_sample_us`].
234 #[must_use]
235 pub fn now_us(&self, local_us: i64) -> Option<i64> {
236 if !self.is_ready() {
237 return None;
238 }
239 let d = if self.use_drift { self.drift } else { 0.0 };
240 Some(round_away_from_zero(
241 local_us as f64 + self.offset + d * (local_us as f64 - self.last_accepted_us as f64),
242 ))
243 }
244
245 /// Returns the local clock reading that corresponds to the server reading `server_us`.
246 ///
247 /// The inverse of [`ClockFilter::now_us`], up to the final rounding. Drift is applied only
248 /// while it is statistically significant, matching the protocol. Returns `None` until the
249 /// filter is ready, which means an estimate exists rather than that it is fresh.
250 #[must_use]
251 pub fn client_time_us(&self, server_us: i64) -> Option<i64> {
252 if !self.is_ready() {
253 return None;
254 }
255 let d = if self.use_drift { self.drift } else { 0.0 };
256 Some(round_away_from_zero(
257 (server_us as f64 - self.offset + d * self.last_accepted_us as f64) / (1.0 + d),
258 ))
259 }
260
261 /// Returns the current offset estimate, server clock minus local clock, in microseconds.
262 ///
263 /// Rounded to the nearest microsecond, with halves away from zero. Returns `None` until the
264 /// filter is ready.
265 #[must_use]
266 pub fn offset_us(&self) -> Option<i64> {
267 if !self.is_ready() {
268 return None;
269 }
270 Some(round_away_from_zero(self.offset))
271 }
272
273 /// Returns the local time at which the last accepted sample arrived.
274 ///
275 /// Zero until a sample is accepted, and never later than the local clock now. The estimate's
276 /// error grows with the distance from this instant, so this is the freshness horizon a caller
277 /// can compare against its own clock.
278 #[must_use]
279 pub fn last_sample_us(&self) -> i64 {
280 self.last_accepted_us
281 }
282
283 /// Returns the number of accepted samples.
284 ///
285 /// Discarded samples do not count. The value saturates at `usize::MAX`.
286 #[must_use]
287 pub fn sample_count(&self) -> usize {
288 self.count
289 }
290
291 /// Drops every sample and returns the filter to its [`ClockFilter::new`] state.
292 pub fn reset(&mut self) {
293 *self = Self::new();
294 }
295}
296
297/// Rounds to the nearest integer, with halves rounded away from zero (like the protocol).
298///
299/// The `as i64` conversion saturates: an estimate beyond the range becomes `i64::MIN` or
300/// `i64::MAX`, and a NaN becomes zero.
301fn round_away_from_zero(value: f64) -> i64 {
302 value.round() as i64
303}