Expand description
Clock synchronisation: a two-dimensional Kalman filter over clock offset and drift.
The filter turns server/time round trips into a mapping from the local monotonic clock to
the server clock. One exchange is a TimeSample with four timestamps, all in microseconds:
client_sent_us T1 local time when the request left
server_received_us T2 server time when the request arrived
server_sent_us T3 server time when the answer left
client_received_us T4 local time when the answer arrivedEach sample yields one offset measurement (server clock minus local clock) and one error bound for it, both in microseconds:
measurement = ((T2 - T1) + (T3 - T4)) / 2
max_error = ((T4 - T1) - (T3 - T2)) / 2The integer arithmetic divides with truncation toward zero, as the protocol specifies. The measurement enters a Kalman filter whose state is the offset and the drift (the rate at which the offset changes, in microseconds per microsecond):
- the offset performs a random walk with diffusion
PROCESS_STD_DEVand the drift one withDRIFT_PROCESS_STD_DEV; - the measurement variance grows with
max_error, so a sample that crossed a stalled queue moves the estimate far less than a quick one - that is the outlier handling, and it needs no special case; - once
ADAPTIVE_FORGETTING_AFTERsamples are in, a residual larger thanADAPTIVE_CUTOFFtimes the error bound inflates the covariance byFORGET_FACTOR², so the filter can follow a genuine step instead of treating it as noise; - drift is applied to a conversion only while it is statistically significant.
Readiness (ClockFilter::is_ready) is an availability signal, not an accuracy guarantee: it
says that an estimate exists, not that it is fresh or good. The estimate’s error grows with the
distance from ClockFilter::last_sample_us, so a caller that needs a bounded error keeps
feeding samples. The published algorithm has a single 100-sample cutoff, after which adaptive
forgetting may start; this module keeps that cutoff for its own purpose and adds a separate,
much earlier threshold for availability, because the two answer different questions.
Local timestamps must be positive. The filter starts with last_sample_us == 0 and discards a
sample that does not advance it, so a local clock that reads zero or less never gets a sample
accepted and never becomes ready.
The module is pure computation: no I/O, no clock reads, no blocking. The caller owns time.
Structs§
- Clock
Filter - Two-dimensional Kalman filter over clock offset and drift.
- Time
Sample - The four timestamps of one round trip, in microseconds.
Constants§
- READY_
AFTER_ SAMPLES - Number of accepted samples
ClockFilterneeds before it reports an estimate.