Skip to content

Fix clock sync producing wrong timing on the first measurement - #28

Merged
OnFreund merged 2 commits into
Sendspin:mainfrom
formatBCE:fix/clocksync-first-measurement-seeding
Aug 2, 2026
Merged

OnFreund merged 2 commits into
Sendspin:mainfrom
formatBCE:fix/clocksync-first-measurement-seeding

Conversation

@formatBCE

Copy link
Copy Markdown
Contributor

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:

  • offset — how far apart the two clocks are
  • drift — how fast that gap is slowly changing over time

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:

  • when the estimate swings too far one way, chunks get scheduled far in the future → silence until the user seeks;
  • when it swings the other way, chunks get scheduled in the past → the buffer dumps them all at once → fast, garbled playback.

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:

  • set the offset to exactly what the first measurement says,
  • start the drift at zero (we have no basis to claim any drift yet),
  • mark the timing baseline from that first measurement.

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

  • Added a regression test that feeds a realistic server-sized offset (~3.45 trillion microseconds) across sparse measurements and checks that the offset stays accurate and the drift stays in a physically sane range. This test fails on the current code and passes with the fix.
    • Note: the test bases its timestamps on the actual local clock rather than a fixed number. This matters — with a fixed value, the bug can be accidentally hidden on machines that have been running for a while, so the test would falsely pass. Tying it to the real clock reproduces the true on-device condition every time.
  • Replaced one existing test (low RTT sample converges faster than high RTT sample). That test only "passed" because of the leftover error from the buggy zero-start behavior. With the fix, both cases settle exactly on the truth, so its comparison no longer makes sense. The replacement checks the property it was actually meant to verify — that a lower-latency measurement is trusted more — by confirming a low-latency outlier pulls the estimate more than an equal high-latency one.

Verification

  • Full sendspin-protocol test suite passes.
  • Confirmed the regression test fails without the production change and passes with it, so it genuinely guards against this bug returning.

@OnFreund OnFreund left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@formatBCE

Copy link
Copy Markdown
Contributor Author

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.

@OnFreund OnFreund left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @formatBCE

@OnFreund
OnFreund merged commit a3d8788 into Sendspin:main Aug 2, 2026
2 checks passed
@formatBCE
formatBCE deleted the fix/clocksync-first-measurement-seeding branch August 2, 2026 19:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants