Repository navigation
Fix clock sync producing wrong timing on the first measurement - #28
Conversation
OnFreund
left a comment
There was a problem hiding this comment.
Reviewed the diff and checked out the branch to verify — ClockSyncTest passes on this branch.
The core fix is correct. predict() runs before update() on the very first sample, so p10 becomes dt·p11 (nonzero) before the huge first innovation (~10¹² µs offset vs a zero-initialized state) is absorbed, and that nonzero p10 makes the drift Kalman gain k1 nonzero — leaking a slice of the giant innovation into xDrift. Seeding xOffset directly from the first measurement and forcing xDrift = 0 is the standard way to initialize a filter far from its zero prior, and the math checks out by hand against the PR's described failure mode (drift → millions of ppm, offset swinging tens of seconds per cycle).
The regression test is well constructed — tying timestamps to the real local clock instead of a fixed value is a good catch, since a fixed dt could be silently coerced to zero on a long-uptime machine and hide the bug. The replaced "low RTT converges faster" test was indeed testing an artifact of the old bug, and the outlier-perturbation replacement still exercises the real R = (rtt/4)² weighting.
One gap worth considering: SendSpinClient.clockSync (SendSpinClient.kt:83) is a single long-lived instance that's never recreated across reconnects. clearSessionState() resets firstMeasurementCompleted and other per-connection flags on every new connection (acceptIncomingConnection, disconnect(), reconnect-success) but never touches clockSync or the new seeded flag. In SERVER_INITIATED mode, SendSpinServerHost can hand the same SendSpinClient a connection from a genuinely different server_id with an unrelated clock offset. Since seeded only guards the very first measurement ever, reconnecting to a different server replays the original failure mode through the normal predict()+update() path — arguably worse than before, since by then p00 may have converged small, making the offset gain k0 sluggish too (not just drift corrupted).
Not a regression from this PR (the pre-existing code never reset ClockSync across reconnects either), but since this PR is specifically about correct behavior "right after connecting to a real server," it might be the natural place to also close this: expose a ClockSync.reset() and call it from clearSessionState(), or re-seed when server_id changes.
Minor nits (non-blocking): lastOffsetMicros = xOffset is duplicated in both branches of the new if/else in processMeasurement and could be hoisted out; sampleCount isn't incremented on the seed path (harmless — just shifts the adaptive-forgetting threshold by one sample).
|
Thanks for the thorough review — all three points addressed in the latest commit. Reset ClockSync across sessions (the substantive gap).Added ClockSync.reset() and call it from clearSessionState(), right next to the existing firstMeasurementCompleted = false. That method already fires on every session start (onOpen, acceptIncomingConnection, disconnect) and already treats each connection as a fresh sync session — resetting the Kalman state there simply completes that intent. I went with an unconditional reset rather than a server_id-conditional one: the same-server reconnect cost is negligible (the next measurement re-seeds the offset directly), and conditional reset would add state for no correctness gain. Failure/close paths need nothing, since the subsequent successful open calls clearSessionState(). Nit 1 (duplicated diagnostics).Hoisted out of the if/else — and both lastOffsetMicros and lastDriftPpm turned out to be branch-independent, since the seed path zeroes xDrift. Nit 2 (sampleCount).Now incremented on the seed path so the adaptive-forgetting threshold counts the seed as the sample it is. One extra:the covariance-prior literals (1e12, 1e-6) are now named constants shared between the field initializers and reset(), so the construction prior and reset can't silently diverge. Tests:a reset regression in ClockSyncTest (converge on a ~3.45e12 µs server, reset(), then re-seed cleanly on a very different offset), plus a new SendSpinClientSessionResetTest that guards the client wiring through the public API — so a future refactor dropping the reset() call gets caught. Both bite when their fix is reverted; full suite green. |
Summary
The clock synchronizer (ClockSync) could produce badly wrong timing estimates right after connecting to a real server, causing audio to either go silent or play too fast and garbled until the user seeked. This fixes it by initializing the filter from the first measurement instead of letting it try to "learn" the value from scratch.
Background: what ClockSync does
The client and server each have their own clock, and they don't agree on the current time. To play audio at the right moment, the client has to figure out the difference between the two clocks. It does this with a running estimator (a Kalman filter) that tracks two things:
Every time the client measures the round trip to the server, it feeds the result in and the estimator refines both numbers.
The problem
The estimator starts by assuming the offset is zero and then treats the very first real measurement as a correction to nudge it toward the truth.
That works fine when the two clocks are close together. But a real server's clock is typically a huge number ahead of the client's — on the order of a trillion microseconds. So the "correction" on the very first measurement isn't a small nudge; it's an enormous jump.
The offset itself recovers from that jump almost immediately, so at a glance everything looks fine. The real damage is to the drift number. A tiny fraction of that giant first correction leaks into the drift estimate, and the result is a drift value that's physically impossible — implying the clocks are pulling apart millions of times faster than any real clock ever could.
From then on it snowballs. Every few seconds the estimator uses that bogus drift to project the offset forward, throwing it off by tens of seconds each time. The offset estimate ends up swinging wildly around the correct value instead of settling on it.
The symptom
Because audio is scheduled based on this offset:
Everything downstream (decoding, buffering, output) was working correctly — it was being fed bad timing from the very start.
Why existing tests didn't catch it
All the existing tests used small, artificial clock offsets (tens of milliseconds). At that scale the first measurement is a small nudge, so the drift never blows up. The bug only shows up against a real server-sized offset, which no test exercised.
The fix
Instead of starting from zero and treating the first measurement as a correction, we use the first measurement to set the starting values directly:
After that, every following measurement is handled exactly as before. This keeps every correction small from the very start, so nothing ever leaks into the drift estimate. It's the standard way to start this kind of estimator when the initial value is far from zero.
The change is small, self-contained, and doesn't alter any public API — callers see no difference.
Tests
Verification