From 84b228a440d304ca33d00265ee0b3c253bd27537 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 06:56:54 -0500 Subject: [PATCH 1/2] Publish each admitted slot's clock instead of sharing its filter A connection's SendspinTimeFilter becomes a by-value member used on the protocol task only, so it loses its mutex and its shared_ptr. Role threads read a TimeTransform instead: the filter's offset and drift as of its latest measurement, which refresh_published_state() copies into one slot per admitted connection whenever a measurement, a slot's connection or the primary moved it. ConnectionManager::clock() returns the primary's, which is_time_synced() and get_client_time() convert through as before. A reader shares nothing with the connection, and a second admitted connection gets its own clock slot. Accept to admission: 4 -> 3 allocations under libc++, 6 -> 5 under libstdc++. --- CLAUDE.md | 2 +- docs/conventions.md | 9 +++-- docs/internals.md | 13 ++++--- docs/playback-sync.md | 4 +-- src/client.cpp | 12 +++---- src/connection.cpp | 8 ----- src/connection.h | 32 ++++++------------ src/connection_manager.cpp | 58 +++++++++++++++++++------------ src/connection_manager.h | 47 +++++++++++++++----------- src/source_role.cpp | 3 +- src/time_burst.cpp | 12 +++---- src/time_burst.h | 2 +- src/time_filter.cpp | 60 ++++++++++++++++++--------------- src/time_filter.h | 33 ++++++++++++++---- tests/test_allocations.cpp | 4 +-- tests/test_client_lifecycle.cpp | 21 +++++++----- tests/test_noise_transport.cpp | 4 --- tests/test_source_role.cpp | 8 ++--- 18 files changed, 177 insertions(+), 155 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e0ba1ae5..ba563bd2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ The library provides `SendspinClient` as the main public API. It handles the ful - `SendspinClient` (`client.h`): main orchestration class; owns the protocol task, the connection manager, the inbound ring and the message routing. Its protocol-task half (the tick, the command handler, the JSON and binary dispatch) is in `client_dispatch.cpp` - `ProtocolTask` (`protocol_task.h`): the `SsProto` thread, its bounded command queue, the latest client/state slot and the never-refused lifecycle-request slot; ticks through `SendspinClient::protocol_tick()` to its next deadline -- `ConnectionManager` (`connection_manager.h`): the admitted array with role ownership, the nursery, the reaping list, admission and arbitration, time bursts, watchdogs and the published time filter and server information; pairing state machines in `connection_manager_pairing.cpp` +- `ConnectionManager` (`connection_manager.h`): the admitted array with role ownership, the nursery, the reaping list, admission and arbitration, time bursts, watchdogs and the published clocks and server information; pairing state machines in `connection_manager_pairing.cpp` - `InboundRing` / `InboundItemList` / `InboundConsumer` / `InboundGate` (`inbound_ring.h`): the shared ring every admitted transport receives into (over `SharedRingBuffer`), the intrusive per-role item lists that hand audio, visualizer frames and artwork image parts to their consumer threads in place, and the per-connection transport/protocol-task hand-off - `OutboundRing` (`outbound_ring.h`): a ring one producer thread (the source task) writes outbound binary messages into; the protocol task encrypts each in place and lends its item to the transport, which returns it once the frame is written. The source's capture ring reuses the class - `PlayerRole` (`player_role.h`): audio streaming role, owns `SyncTask`, writes decoded audio via `on_audio_write` callback diff --git a/docs/conventions.md b/docs/conventions.md index 7688190e..a9e448f8 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -52,9 +52,9 @@ checklists in `.claude/skills/` apply these standards to a diff. - State published from one writer thread to one reader thread uses a `ShadowSlot` (`src/platform/shadow_slot.h`), whichever side (if either) the main loop is on. State the main loop *reads* goes through the Inbox instead. - The values read by several threads without being consumed, the primary - admitted connection's time filter and server information, sit in - `ConnectionManager`'s own slot behind a leaf mutex (`time_filter()`, + The values read by several threads without being consumed, the admitted + connections' clocks and the primary's server information, sit in + `ConnectionManager`'s own slot behind a leaf mutex (`clock()`, `server_information()`), written by the protocol task; a flag read the same way is a plain atomic. - Event producers push through `push_event_or_log()` rather than hand-rolling @@ -118,8 +118,7 @@ checklists in `.claude/skills/` apply these standards to a diff. state, never across a call that takes another library lock, a send, a listener or the persistence provider, so the library has no lock order to cite. The leaves are `ConnectionManager::published_mutex_`, - `RecordStore::mutex_`, the Inbox mutex, each - `SendspinTimeFilter`'s `state_mutex_`, the inbound ring's, each outbound + `RecordStore::mutex_`, the Inbox mutex, the inbound ring's, each outbound ring's, item lists' and protocol task command queue's own locks, the artwork role's slot mutex, `ShadowSlot`'s and the ESP server's pending-upgrade mutex. A change that would take a second library lock under one of them is a design diff --git a/docs/internals.md b/docs/internals.md index 0165e5a8..772defc3 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -50,15 +50,14 @@ The primitives other than the Inbox and the inbound and outbound rings live in ` | Artwork `SlotGate`s (`DrainTask::slot_gates`, under `slot_mutex`) | Artwork decode thread (arms a gate, parks a complete image); main loop (presents, acks, drops a park at a stream end) | Each other | | `ShadowSlot` (sync-task playback progress) | The consumer's audio thread (`notify_audio_played()`) | Sync task | | `Inbox` (`src/inbox.h`, see [Inbox](#inbox)) | Protocol task, sync task, artwork decode thread | Main loop | -| `ConnectionManager` published primary slot (time filter and server information) | Protocol task (`refresh_published_state()`) | Any thread (`time_filter()`, `server_information()`) | -| Each connection's `SendspinTimeFilter` | Protocol task (its burst's measurements) | Sync task and visualizer drain thread, converting timestamps | +| `ConnectionManager` published state (each admitted slot's clock, the primary's server information) | Protocol task (`refresh_published_state()`) | Any thread (`clock()`, `server_information()`) | | `RecordStore` | Protocol task (resolves and changes records) | Main loop (writes them to the provider) | Plain atomics carry the rest: the `connected_` flag on `ConnectionManager`; the admission flag `accepting_` on `ProtocolTask`, written on the main loop under the queue lock; the unpaired-access setting, the lifecycle state, the network provider's last answer (`network_ready_`, written by the main loop's poll and read by the protocol task before it starts the WebSocket server) and the high-performance grant count (`high_performance_granted_`, see [One Main Loop Drain](#one-main-loop-drain)) on `SendspinClient`; and each role's teardown generation (`cleanup_generation`), written by the protocol task and read by the main loop and the role's thread. The role- and connection-local atomics (a connection's last-arrival stamp, upgrade flag and time-frame write time; artwork's `stream_active` and slot epochs, the visualizer's `spectrum_bin_count`, `tracks_downbeats` and `boundary_sequence`, the player's output delay, the controller's supported commands, the source's stream gate and codec, the source task's overflow generation) each state their writer and reader at their declaration. ### Locks -Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `time_filter()` reads behind `server_information()` copies); each `SendspinTimeFilter::state_mutex_`; `RecordStore::mutex_`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration. +Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `clock()` reads behind `server_information()` copies); `RecordStore::mutex_`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration. ### The Inbound Ring @@ -130,9 +129,9 @@ Every role state slot is a `GenerationSlot`: each payload carries the stamp i OUTBOUND_RING_ITEM_COUNT chunks from its outbound ring, each sent or returned unsent 10. Losses from the sends of steps 7 to 9: a connection a failed send detached is dropped, as in step 6, before anything is published -11. ConnectionManager::refresh_published_state(): the published primary slot (time filter and - server information); then publish_connected(), the connected flag other threads read, - raised only here, after every handler of the tick, so is_connected() never reads true +11. ConnectionManager::refresh_published_state(): the published state (each admitted slot's + clock, the primary's server information); then publish_connected(), the connected flag + other threads read, raised only here, after every handler of the tick, so is_connected() never reads true before the tick's whole effect (the published slots and the events it queued for the drain); a loss lowers it at once ``` @@ -400,7 +399,7 @@ A later `server/activate` can remove roles. Each removed role runs the same `cle ### Time Filter Slot -Role threads convert server timestamps through `SendspinClient::is_time_synced()` and `get_client_time()`: the sync task per chunk, the visualizer drain thread per frame. The source's chunks are converted the other way on the protocol task itself, through the stream connection's own filter, so they read no slot. Both resolve the primary admitted connection's `SendspinTimeFilter` through `ConnectionManager::time_filter()`, which reads the `PublishedPrimary` slot (`published_`, under the leaf `published_mutex_`) and never waits on the protocol task. `refresh_published_state()` writes that one slot, holding both the filter and the server information, whenever the primary connection changes, so it always names the primary connection's filter; a role thread holding the filter never holds the connection, whose destructor can join a transport thread. +Each connection's `SendspinTimeFilter` is a member of the connection, used on the protocol task only: its burst feeds it, and the source's chunks are converted the other way there, through the stream connection's own filter. Role threads convert server timestamps through `SendspinClient::is_time_synced()` and `get_client_time()`: the sync task per chunk, the visualizer drain thread per frame. Both read the primary admitted connection's clock through `ConnectionManager::clock()`: a `TimeTransform`, the filter's offset and drift as of its latest measurement, copied out of `published_` under the leaf `published_mutex_`, so a reader never waits on the protocol task and shares nothing with the connection, whose destructor can join a transport thread. `refresh_published_state()` (tick step 11) takes each admitted slot's transform and writes them, with the primary's slot, whenever one changed: a measurement, a new connection in the slot or a new primary. Each getter reads the slot once, so a caller that checks `is_time_synced()` and then calls `get_client_time()` can see two different connections across a server handoff. A drop or handoff commands the stream to end before it changes the slot, so the sync task leaves the stream before transferring such a chunk; the shutdown pass empties the slot before the role threads stop, and the 0 an empty slot returns reads as late. diff --git a/docs/playback-sync.md b/docs/playback-sync.md index 29ad4074..1e7f2fd1 100644 --- a/docs/playback-sync.md +++ b/docs/playback-sync.md @@ -4,13 +4,13 @@ This document explains how the library keeps audio in time with the server: esti ## Clock Synchronization -Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created once when the connection is set up and never replaced, and one `SendspinTimeBurst`. Only that connection's own measurements feed its filter: the protocol task hands a `server/time` reply to the burst of the connection it arrived on, and only when it answers that connection's `client/time` in flight. The role threads convert through the primary admitted connection's filter (`docs/internals.md`, "Time Filter Slot"). +Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created once when the connection is set up and never replaced, and one `SendspinTimeBurst`. Only that connection's own measurements feed its filter: the protocol task hands a `server/time` reply to the burst of the connection it arrived on, and only when it answers that connection's `client/time` in flight. The role threads convert through a copy of the primary admitted connection's filter transform (`docs/internals.md`, "Time Filter Slot"). `SendspinTimeBurst` (`src/time_burst.h`) collects measurements in NTP-style bursts: `time_burst_size` `client/time` exchanges whose lowest-round-trip measurement goes to the filter, then a pause of `time_burst_interval_ms` until the next burst (both in `SendspinClientConfig`). The protocol task runs each admitted connection's burst while that connection is operational, and high-performance networking is held for its duration so the round trips are not inflated by power saving: the burst sends its first `client/time` only once the main loop has delivered the request to the listener (`docs/internals.md`, "One Main Loop Drain"). Each `client/time` round trip is timed from the socket write, not from the time the message carries: `SendspinConnection::send_time_message()` hands `NoiseTransport::send_staged_json()` a hook that the transport runs immediately before writing the message's frame, and the echoed `client_transmitted` only identifies the frame a `server/time` answers (`SendspinConnection::claim_time_frame()`). Recording the write time before the write, never after it, keeps every scheduling delay on the side that lengthens the measured round trip, which `max_error` reports and the burst's lowest-round-trip selection discards. -The filter is a two-state `[offset, drift]` Kalman filter, tuned by `SendspinTimeFilter::Config`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`drift_significance_threshold`). Once `min_samples` measurements have accumulated, a residual larger than `adaptive_cutoff` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. Its `state_mutex_` lets the sync task and the visualizer drain thread convert timestamps while the protocol task updates it. +The filter is a two-state `[offset, drift]` Kalman filter, tuned by `SendspinTimeFilter::Config`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`drift_significance_threshold`). Once `min_samples` measurements have accumulated, a residual larger than `adaptive_cutoff` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. The protocol task alone updates and reads it; the sync task and the visualizer drain thread convert timestamps through the copy of its transform it publishes. The filter's first measurement gates playback: the sync task decodes no audio until the clock is synced. While the player role is active, it also gates the client's `client/state` reporting `available: true` (messaging.md "client/state"). diff --git a/src/client.cpp b/src/client.cpp index 05bd0361..b9a7f3db 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1194,15 +1194,15 @@ bool SendspinClient::is_connected() const { } bool SendspinClient::is_time_synced() const { - // See ConnectionManager::time_filter(). - auto filter = this->connection_manager_->time_filter(); - return filter != nullptr && filter->has_update(); + // See ConnectionManager::clock(). + const std::optional clock = this->connection_manager_->clock(); + return clock.has_value() && clock->synced; } int64_t SendspinClient::get_client_time(int64_t server_time) const { - // See ConnectionManager::time_filter(). - auto filter = this->connection_manager_->time_filter(); - return filter != nullptr ? filter->compute_client_time(server_time) : 0; + // See ConnectionManager::clock(). + const std::optional clock = this->connection_manager_->clock(); + return clock.has_value() ? clock->compute_client_time(server_time) : 0; } std::optional SendspinClient::get_server_information() const { diff --git a/src/connection.cpp b/src/connection.cpp index d3620a8b..b73629ee 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -74,14 +74,6 @@ SsErr SendspinConnection::send_lent_frame(OutboundRing& ring, void* item, size_t return err; } -// ============================================================================ -// Time filter -// ============================================================================ - -void SendspinConnection::init_time_filter() { - this->time_filter_ = std::make_shared(SendspinTimeFilter::Config{}); -} - void SendspinConnection::wake_protocol_task() const { if (this->inbound_task_ != nullptr) { this->inbound_task_->wake(); diff --git a/src/connection.h b/src/connection.h index d29f235e..12e09dbf 100644 --- a/src/connection.h +++ b/src/connection.h @@ -615,33 +615,21 @@ class SendspinConnection : public std::enable_shared_from_thispairing_finalized_ = false; } - /// @brief Gets the time filter for this connection - /// @return Pointer to the time filter, or nullptr if not initialized. - SendspinTimeFilter* get_time_filter() { - return this->time_filter_.get(); + /// @brief This connection's time filter. Protocol task only; other threads read its transform + /// through ConnectionManager::clock(). + SendspinTimeFilter& time_filter() { + return this->time_filter_; } - - /// @brief Returns a shared reference to this connection's time filter, for ConnectionManager's - /// time filter slot (see ConnectionManager::time_filter()) - /// @return The time filter, or nullptr if not initialized. - std::shared_ptr get_shared_time_filter() const { + const SendspinTimeFilter& time_filter() const { return this->time_filter_; } /// @brief Returns true if the time filter has received at least one measurement /// @return True if time synchronization has started, false otherwise. bool is_time_synced() const { - if (this->time_filter_ == nullptr) { - return false; - } - return this->time_filter_->has_update(); + return this->time_filter_.has_update(); } - /// @brief Initializes the time filter with Kalman parameters. Call once, before the connection - /// can enter a manager slot: ConnectionManager's time filter slot copies this filter at install - /// and never refreshes it. - void init_time_filter(); - /// @brief This connection's time burst, which feeds its time filter. Protocol task only: the /// burst sends its client/time frames there and is fed the server/time replies there. SendspinTimeBurst& time_burst() { @@ -1033,16 +1021,16 @@ class SendspinConnection : public std::enable_shared_from_this noise_handshake_; // Pointer fields - /// Time synchronization filter (Kalman-based). Shared so role threads can hold it without - /// holding this connection (ConnectionManager::time_filter()). - std::shared_ptr time_filter_; - /// Retained for re-handshake: pointer to the client identity supplied at /// init_noise_handshake(). Lifetime is owned by SendspinClient (outlives connections). const Identity* noise_identity_{nullptr}; diff --git a/src/connection_manager.cpp b/src/connection_manager.cpp index 6de9951b..7ce8bee7 100644 --- a/src/connection_manager.cpp +++ b/src/connection_manager.cpp @@ -317,9 +317,12 @@ void ConnectionManager::reap_finished(bool drop_one_opened) { // Any thread // ============================================================================ -std::shared_ptr ConnectionManager::time_filter() const { +std::optional ConnectionManager::clock() const { std::lock_guard lock(this->published_mutex_); - return this->published_.time_filter; + if (this->published_.primary_slot >= MAX_ADMITTED) { + return std::nullopt; + } + return this->published_.clocks[this->published_.primary_slot]; } std::optional ConnectionManager::server_information() const { @@ -339,7 +342,6 @@ bool ConnectionManager::on_new_connection(const std::shared_ptrinit_time_filter(); conn->time_burst().configure(this->client_->config_.time_burst_size, this->client_->config_.time_burst_interval_ms, this->client_->config_.time_burst_response_timeout_ms); @@ -440,7 +442,6 @@ void ConnectionManager::connect_to(const std::string& url) { client_conn->attach_inbound(this->client_->inbound_ring_.get(), this->client_->protocol_task_.get()); - client_conn->init_time_filter(); client_conn->time_burst().configure(this->client_->config_.time_burst_size, this->client_->config_.time_burst_interval_ms, this->client_->config_.time_burst_response_timeout_ms); @@ -1019,8 +1020,8 @@ uint32_t ConnectionManager::run_time_sync() { this->client_->request_high_performance(false); entry.high_performance_held = false; } - if (&entry == primary && conn->get_time_filter() != nullptr) { - this->client_->post_time_sync_error(conn->get_time_filter()->get_error()); + if (&entry == primary) { + this->client_->post_time_sync_error(conn->time_filter().get_error()); } } next = std::min(next, burst.ms_until_due(now_ms)); @@ -1037,21 +1038,36 @@ void ConnectionManager::refresh_published_state() { AdmittedEntry* primary = this->primary(); SendspinConnection* primary_conn = primary != nullptr ? primary->conn.get() : nullptr; const uint64_t primary_id = primary_conn != nullptr ? primary_conn->get_instance_id() : 0; - if (primary_id != this->published_primary_id_) { - // The slot changes only with the primary connection: its filter is fixed at creation and - // its server information is complete before admission (server/hello precedes it). + // The server information changes only with the primary connection: it is complete before + // admission (server/hello precedes it). + const bool primary_changed = primary_id != this->published_primary_id_; + std::optional info; + if (primary_changed) { this->published_primary_id_ = primary_id; - std::shared_ptr filter = - primary_conn != nullptr ? primary_conn->get_shared_time_filter() : nullptr; - std::optional info = - primary_conn != nullptr ? std::make_optional(primary_conn->get_server_information()) - : std::nullopt; - { - // Swapped under the leaf lock; what they replace is destroyed outside it. - std::lock_guard lock(this->published_mutex_); - this->published_.time_filter.swap(filter); + if (primary_conn != nullptr) { + info = primary_conn->get_server_information(); + } + } + // Each admitted slot's clock, which a measurement, the slot's connection or the primary moves. + // The protocol task is published_'s only writer, so it compares without the lock, and a tick + // that changed nothing takes none. + ClockSlots clocks{}; + for (size_t slot = 0; slot < MAX_ADMITTED; ++slot) { + if (this->admitted_[slot].conn != nullptr) { + clocks[slot] = this->admitted_[slot].conn->time_filter().transform(); + } + } + const size_t primary_slot = + primary != nullptr ? static_cast(primary - this->admitted_.data()) : MAX_ADMITTED; + if (primary_changed || clocks != this->published_.clocks || + primary_slot != this->published_.primary_slot) { + // Swapped under the leaf lock; the server information it replaces is destroyed outside it. + std::lock_guard lock(this->published_mutex_); + if (primary_changed) { this->published_.server_information.swap(info); } + this->published_.clocks = clocks; + this->published_.primary_slot = primary_slot; } // Only ever lowered here: a loss is reported as soon as the slots stop naming the connection, @@ -1109,7 +1125,7 @@ void ConnectionManager::shutdown() { this->nursery_.clear(); // A standing pairing window belongs to this run; a restart begins with it closed. this->close_pairing_window(); - // Empties the time filter slot before stop() stops the role threads: a role thread that reads + // Empties the published clocks before stop() stops the role threads: a role thread that reads // it from here converts to 0, which reads as late. this->refresh_published_state(); this->shutdown_ui_.code_was_emitted |= ui.code_was_emitted; @@ -1618,8 +1634,8 @@ void ConnectionManager::drop_connection(SendspinConnection* conn, const PairingUiSnapshot ui = snapshot_pairing_ui(conn); std::shared_ptr dropped = this->vacate_admitted(*entry); // Ahead of the slot refresh below: the teardown commands the stream to end before the - // time filter slot stops naming this connection's filter (see docs/internals.md "Time - // Filter Slot"). + // published clock stops being this connection's (see docs/internals.md "Time Filter + // Slot"). this->client_->cleanup_connection_state( static_cast(ALL_ROLES_MASK & ~this->roles_owned_by_others(nullptr))); this->refresh_published_state(); diff --git a/src/connection_manager.h b/src/connection_manager.h index 33fd3c68..e5b47677 100644 --- a/src/connection_manager.h +++ b/src/connection_manager.h @@ -25,6 +25,7 @@ #include "record_store.h" #include "sendspin/client.h" #include "sendspin/types.h" +#include "time_filter.h" #include #include @@ -44,7 +45,6 @@ class SendspinArenaAllocator; class SendspinClient; class SendspinConnection; class SendspinServerConnection; -class SendspinTimeFilter; class SendspinWsServer; /// @brief Converts a duration in seconds to microseconds at compile time. @@ -266,8 +266,8 @@ class ConnectionManager { /// - SendspinClient::cleanup_connection_state() resets the client-wide state (event ring, /// group, time-sync report, pairing notes) only when the teardown covers every role, /// which is keyed on no remaining connection owning one. - /// - The time filter and server information slots follow primary() (the player's owner, else - /// the first admitted), so a role owned by another connection converts with the wrong clock. + /// - clock() and the server information follow primary() (the player's owner, else the first + /// admitted), so a role owned by another connection converts with the wrong clock. /// - group/update, leave() and get_server_information() are singular: they follow primary(). /// - The artwork binary gate (SendspinClient::process_binary_message()) passes any admitted /// connection while none owns the role. @@ -372,15 +372,15 @@ class ConnectionManager { return this->connected_.load(std::memory_order_acquire); } - /// @brief Returns the time filter of the primary admitted connection (see primary()), or - /// nullptr when none is admitted. Any thread. + /// @brief Returns the clock of the primary admitted connection (see primary()), as of the + /// protocol task's last refresh_published_state(), or nullopt when none is admitted. Any + /// thread. /// /// Reads published_ behind the leaf published_mutex_, so a role thread converting /// timestamps (the sync task per chunk, the visualizer drain per frame) never waits on the - /// protocol task. Hands out the filter, never the connection: a connection's destructor can - /// join its transport thread, which must not happen on a role thread, while the filter's last - /// drop only frees memory. - std::shared_ptr time_filter() const; + /// protocol task. A copy of the filter's transform, so a reader shares nothing with the + /// connection or its filter. + std::optional clock() const; /// @brief Returns a copy of the primary admitted connection's server information, or nullopt /// when none is admitted. Any thread: reads a slot written at admission and cleared on the @@ -523,10 +523,10 @@ class ConnectionManager { /// burst waiting for its grant adds no deadline, since the grant wakes the task. uint32_t run_time_sync(); - /// @brief Refreshes what other threads read without a protocol-task lock: the time filter and - /// server-information slots (from primary()), and lowers the connected flag when no admitted - /// connection is operational. Called at the end of every tick and after every change to the - /// admitted array. + /// @brief Refreshes what other threads read without a protocol-task lock: each admitted slot's + /// clock, the primary() slot and its server information, and lowers the connected flag when no + /// admitted connection is operational. Called at the end of every tick and after every change + /// to the admitted array. void refresh_published_state(); /// @brief Publishes the connected flag (is_connected()) as it stands, raising it as well as @@ -992,17 +992,24 @@ class ConnectionManager { /// lowered by refresh_published_state() too), read from any thread. std::atomic connected_{false}; - /// @brief What other threads read of the primary admitted connection, written together - struct PublishedPrimary { - std::shared_ptr time_filter; + /// @brief Each admitted slot's clock (admitted_[slot]), nullopt for a free slot + using ClockSlots = std::array, MAX_ADMITTED>; + + /// @brief What other threads read of the admitted connections + struct PublishedState { + ClockSlots clocks{}; + /// The slot in clocks of the primary connection (primary()), MAX_ADMITTED for none. + size_t primary_slot{MAX_ADMITTED}; + /// The primary connection's server information. std::optional server_information; }; /// Guards published_. A leaf (docs/conventions.md): held only to copy or swap a member, so it - /// also serialises the role threads' time_filter() reads behind server_information() copies. + /// also serialises the role threads' clock() reads behind server_information() copies. mutable std::mutex published_mutex_; - /// Written by the protocol task (refresh_published_state()); read from any thread - /// (time_filter(), server_information()): role threads, the main loop, the consumer. - PublishedPrimary published_; + /// Written by the protocol task (refresh_published_state()), which, as its only writer, also + /// reads it without the lock; read from any thread (clock(), server_information()): role + /// threads, the main loop, the consumer. + PublishedState published_; }; } // namespace sendspin diff --git a/src/source_role.cpp b/src/source_role.cpp index 726ac5fd..8ed9e437 100644 --- a/src/source_role.cpp +++ b/src/source_role.cpp @@ -344,8 +344,7 @@ void SourceRole::Impl::send_chunks(SendspinConnection* owner) { // as possible, on the thread that feeds it. uint8_t* message = outbound_item_message(item); message[0] = SENDSPIN_BINARY_SOURCE_AUDIO; - host_to_be64(owner->get_time_filter()->compute_server_time(header.capture_time_us), - message + 1); + host_to_be64(owner->time_filter().compute_server_time(header.capture_time_us), message + 1); // The send chain owns the item from here on (OutboundRing "Lending"). A failure after // the encrypt closes the connection, which the loss pass that follows drops. (void)owner->send_app_binary_lent(*ring, item, capacity, header.data_len); diff --git a/src/time_burst.cpp b/src/time_burst.cpp index ab6e71d4..478f3ea9 100644 --- a/src/time_burst.cpp +++ b/src/time_burst.cpp @@ -109,9 +109,9 @@ bool SendspinTimeBurst::on_time_response(SendspinConnection* conn, const TimeRes // Check if burst is complete if (this->burst_index_ >= this->burst_size_) { - auto* time_filter = conn->get_time_filter(); - if (time_filter != nullptr && this->best_max_error_ < std::numeric_limits::max()) { - time_filter->update(this->best_offset_, this->best_max_error_, this->best_timestamp_); + if (this->best_max_error_ < std::numeric_limits::max()) { + conn->time_filter().update(this->best_offset_, this->best_max_error_, + this->best_timestamp_); SS_LOGV(TAG, "Burst complete, best max_error: %" PRId64 " us", this->best_max_error_); } this->last_burst_complete_time_ = platform_time_us() / US_PER_MS; @@ -169,9 +169,9 @@ bool SendspinTimeBurst::retire_message(SendspinConnection* conn, int64_t now_ms) if (this->burst_index_ < this->burst_size_) { return false; } - auto* time_filter = conn->get_time_filter(); - if (time_filter != nullptr && this->best_max_error_ < std::numeric_limits::max()) { - time_filter->update(this->best_offset_, this->best_max_error_, this->best_timestamp_); + if (this->best_max_error_ < std::numeric_limits::max()) { + conn->time_filter().update(this->best_offset_, this->best_max_error_, + this->best_timestamp_); SS_LOGV(TAG, "Burst complete (with retired messages), best max_error: %" PRId64 " us", this->best_max_error_); } diff --git a/src/time_burst.h b/src/time_burst.h index 94446922..a1cb449c 100644 --- a/src/time_burst.h +++ b/src/time_burst.h @@ -65,7 +65,7 @@ struct TimeBurstResult { * const int64_t now_ms = platform_time_us() / US_PER_MS; * TimeBurstResult result = burst.loop(conn, now_ms, burst.starts_burst(now_ms)); * if (result.burst_completed) { - * int64_t server_now = conn->get_time_filter()->compute_server_time(platform_time_us()); + * int64_t server_now = conn->time_filter().compute_server_time(platform_time_us()); * } * * // When a SERVER_TIME response arrives: diff --git a/src/time_filter.cpp b/src/time_filter.cpp index 2170b3c0..19fd2a40 100644 --- a/src/time_filter.cpp +++ b/src/time_filter.cpp @@ -17,7 +17,6 @@ #include #include #include -#include namespace sendspin { @@ -42,8 +41,6 @@ SendspinTimeFilter::SendspinTimeFilter(const Config& config) // ============================================================================ void SendspinTimeFilter::update(int64_t measurement, int64_t max_error, int64_t time_added) { - std::lock_guard lock(this->state_mutex_); - if (time_added <= this->last_update_) { // Skip non-monotonic timestamps (duplicates or out-of-order packets) // This protects against division by zero and backwards time progression @@ -144,34 +141,14 @@ void SendspinTimeFilter::update(int64_t measurement, int64_t max_error, int64_t } int64_t SendspinTimeFilter::compute_server_time(int64_t client_time) const { - // Transform: T_server = T_client + offset + drift * (T_client - T_last_update) - // Compute instantaneous offset accounting for linear drift: - // offset(t) = offset_base + drift * (t - t_last_update) - - std::lock_guard lock(this->state_mutex_); - const double dt = client_time - this->last_update_; - const double effective_drift = this->use_drift_ ? this->drift_ : 0.0; - - const int64_t offset = std::round(this->offset_ + effective_drift * dt); - return client_time + offset; + return this->transform().compute_server_time(client_time); } int64_t SendspinTimeFilter::compute_client_time(int64_t server_time) const { - // Inverse transform solving for T_client: - // T_server = T_client + offset + drift * (T_client - T_last_update) - // T_server = (1 + drift) * T_client + offset - drift * T_last_update - // T_client = (T_server - offset + drift * T_last_update) / (1 + drift) - - std::lock_guard lock(this->state_mutex_); - const double effective_drift = this->use_drift_ ? this->drift_ : 0.0; - - return std::round( - (static_cast(server_time) - this->offset_ + effective_drift * this->last_update_) / - (1.0 + effective_drift)); + return this->transform().compute_client_time(server_time); } void SendspinTimeFilter::reset() { - std::lock_guard lock(this->state_mutex_); this->count_ = 0; this->offset_ = 0.0; this->drift_ = 0.0; @@ -187,18 +164,45 @@ void SendspinTimeFilter::reset() { // ============================================================================ int64_t SendspinTimeFilter::get_covariance() const { - std::lock_guard lock(this->state_mutex_); return std::round(this->offset_covariance_); } int64_t SendspinTimeFilter::get_error() const { - std::lock_guard lock(this->state_mutex_); return std::round(sqrt(this->offset_covariance_)); } bool SendspinTimeFilter::has_update() const { - std::lock_guard lock(this->state_mutex_); return this->count_ >= 1; } +TimeTransform SendspinTimeFilter::transform() const { + return TimeTransform{.offset = this->offset_, + .drift = this->use_drift_ ? this->drift_ : 0.0, + .last_update = this->last_update_, + .synced = this->has_update()}; +} + +// ============================================================================ +// TimeTransform +// ============================================================================ + +int64_t TimeTransform::compute_server_time(int64_t client_time) const { + // Transform: T_server = T_client + offset + drift * (T_client - T_last_update) + // Compute instantaneous offset accounting for linear drift: + // offset(t) = offset_base + drift * (t - t_last_update) + const double dt = client_time - this->last_update; + const int64_t instantaneous_offset = std::round(this->offset + this->drift * dt); + return client_time + instantaneous_offset; +} + +int64_t TimeTransform::compute_client_time(int64_t server_time) const { + // Inverse transform solving for T_client: + // T_server = T_client + offset + drift * (T_client - T_last_update) + // T_server = (1 + drift) * T_client + offset - drift * T_last_update + // T_client = (T_server - offset + drift * T_last_update) / (1 + drift) + return std::round( + (static_cast(server_time) - this->offset + this->drift * this->last_update) / + (1.0 + this->drift)); +} + } // namespace sendspin diff --git a/src/time_filter.h b/src/time_filter.h index 0341fb5a..abdbff66 100644 --- a/src/time_filter.h +++ b/src/time_filter.h @@ -20,10 +20,31 @@ #include #include -#include namespace sendspin { +/// @brief A time filter's conversion between the client and server clocks, as of its latest +/// measurement: what threads other than the protocol task read of a connection's filter +/// (ConnectionManager::clock()). +struct TimeTransform { + /// Server minus client time at last_update, in microseconds. + double offset{0.0}; + /// Drift the conversions apply: the filter's estimate once significant, otherwise 0. + double drift{0.0}; + /// Client time of the latest measurement, in microseconds. + int64_t last_update{0}; + /// Whether the filter has taken at least one measurement. + bool synced{false}; + + /// @brief Converts a client timestamp to the equivalent server timestamp. + int64_t compute_server_time(int64_t client_time) const; + + /// @brief Converts a server timestamp to the equivalent client timestamp. + int64_t compute_client_time(int64_t server_time) const; + + bool operator==(const TimeTransform&) const = default; +}; + /// @brief Two-dimensional Kalman filter for NTP-style time synchronization between client and /// server. /// @@ -37,8 +58,8 @@ namespace sendspin { /// from network disruptions or server clock adjustments. /// /// All computations use double precision arithmetic to maintain microsecond-level accuracy over -/// extended periods. Thread-safe access to the current time transformation is provided via -/// std::mutex. +/// extended periods. A filter belongs to one connection and is used on the protocol task only; +/// other threads read its transform(). class SendspinTimeFilter { public: /// @brief Configuration parameters for the time synchronization filter. @@ -149,14 +170,14 @@ class SendspinTimeFilter { /// @return True if the filter has been updated with at least one time measurement. bool has_update() const; + /// @brief Returns the conversion as of the latest measurement. + TimeTransform transform() const; + protected: // ======================================== // Member variables // ======================================== - // Struct fields - mutable std::mutex state_mutex_; - // 64-bit fields const double adaptive_forgetting_cutoff; double drift_{0.0}; diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index bdcd1616..8a6a666b 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -430,9 +430,9 @@ constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake // server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 4; +constexpr size_t ADMISSION_ALLOCATIONS = 3; #else -constexpr size_t ADMISSION_ALLOCATIONS = 6; +constexpr size_t ADMISSION_ALLOCATIONS = 5; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 0; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_client_lifecycle.cpp b/tests/test_client_lifecycle.cpp index 7ec767c2..9c7e4e7d 100644 --- a/tests/test_client_lifecycle.cpp +++ b/tests/test_client_lifecycle.cpp @@ -3407,13 +3407,10 @@ struct ConnectionObservation { /// Connection stand-in that records where it was destroyed and how many goodbyes it was asked /// for. The tests drive the stream through the player's own handlers, so no message traffic -/// reaches it: it exists to carry the stream's time filter, and to be goodbyed and freed. Its -/// filter is created with it, as production does before a connection can enter a slot. +/// reaches it: it exists to carry the stream's time filter, and to be goodbyed and freed. class ObservedConnection : public StubConnection { public: - explicit ObservedConnection(ConnectionObservation* obs) : obs_(obs) { - this->init_time_filter(); - } + explicit ObservedConnection(ConnectionObservation* obs) : obs_(obs) {} ~ObservedConnection() override { this->obs_->destroyed_on = std::this_thread::get_id(); this->obs_->destroyed.store(true); @@ -3486,14 +3483,14 @@ constexpr int64_t SEEDED_SERVER_OFFSET_US = -10LL * 60 * 1000 * 1000; /// A stand-in connection whose time filter has taken one measurement of SEEDED_SERVER_OFFSET_US. std::shared_ptr make_synced_connection(ConnectionObservation* obs) { auto conn = std::make_shared(obs); - conn->get_time_filter()->update(SEEDED_SERVER_OFFSET_US, /*max_error=*/1000, - platform_time_us()); + conn->time_filter().update(SEEDED_SERVER_OFFSET_US, /*max_error=*/1000, platform_time_us()); return conn; } // The time filter slot follows the primary admitted connection's filter: a synced connection // converts with its offset, a vacated slot reads as unsynced, the slot never keeps a connection -// alive, and an unsynced newcomer installed over a synced one reads its own filter. +// alive, an unsynced newcomer installed over a synced one reads its own filter, and that +// newcomer's first measurement reaches the slot at the protocol task's next publish. TEST(ClientLifecycle, TheTimeFilterSlotFollowsTheAdmittedConnection) { ConnectionObservation dropped_obs; // All outlive the client ConnectionObservation replaced_obs; @@ -3515,8 +3512,14 @@ TEST(ClientLifecycle, TheTimeFilterSlotFollowsTheAdmittedConnection) { (void) replace_admitted(manager, make_synced_connection(&replaced_obs)); ASSERT_TRUE(client.is_time_synced()); - (void) replace_admitted(manager, std::make_shared(&newcomer_obs)); + auto newcomer = std::make_shared(&newcomer_obs); + (void) replace_admitted(manager, newcomer); EXPECT_FALSE(client.is_time_synced()) << "the newcomer read the replaced connection's filter"; + + newcomer->time_filter().update(SEEDED_SERVER_OFFSET_US, /*max_error=*/1000, platform_time_us()); + manager.refresh_published_state(); + EXPECT_TRUE(client.is_time_synced()) << "a measurement after admission never reached the slot"; + EXPECT_EQ(client.get_client_time(SERVER_TS_US), SERVER_TS_US - SEEDED_SERVER_OFFSET_US); } // The sync task converts chunks with the current connection's offset. The fed diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 5687ae4a..2e6eede7 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -1534,7 +1534,6 @@ TEST(TimeBurst, CountsOnlyTheReplyToItsPendingMessage) { ASSERT_TRUE(r.has_value()); DeferredWriteConnection conn; conn.set_noise_session(std::move(r->responder_session)); - conn.init_time_filter(); conn.set_client_hello_sent(true); conn.set_server_hello_received(true); auto reply = [](int64_t echo) { @@ -1577,7 +1576,6 @@ TEST(TimeBurst, TimedOutMessageIsRetired) { ASSERT_TRUE(r.has_value()); DeferredWriteConnection conn; conn.set_noise_session(std::move(r->responder_session)); - conn.init_time_filter(); conn.set_client_hello_sent(true); conn.set_server_hello_received(true); @@ -1917,7 +1915,6 @@ TEST(NoiseTransport, ASendFailureAfterTheEncryptDropsTheConnectionInItsTick) { auto conn = std::make_shared(); conn->set_json_arena(*client.json_arena_); conn->set_noise_session(std::move(r->responder_session)); - conn->init_time_filter(); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"controller@v1"}, @@ -1997,7 +1994,6 @@ TEST(TimeBurst, AnUnsentTimeMessageCountsAsTimedOut) { ASSERT_TRUE(r.has_value()); conn.set_noise_session(std::move(r->responder_session)); } - conn.init_time_filter(); conn.set_client_hello_sent(true); conn.set_server_hello_received(true); diff --git a/tests/test_source_role.cpp b/tests/test_source_role.cpp index 894bb951..71da176c 100644 --- a/tests/test_source_role.cpp +++ b/tests/test_source_role.cpp @@ -891,7 +891,6 @@ class SourceStandIn { conn->set_json_arena(*this->client->json_arena_); conn->set_noise_session(std::move(loopback->responder_session)); conn->set_noise_handshake_result("stand-in-server", PskCategory::LONG_TERM, "stand-in"); - conn->init_time_filter(); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"source@v1"}, @@ -912,7 +911,7 @@ class SourceStandIn { /// One measurement: the server clock runs SERVER_CLOCK_OFFSET_US ahead. static void sync(SendspinConnection& conn) { - conn.get_time_filter()->update(SERVER_CLOCK_OFFSET_US, 1000, platform_time_us()); + conn.time_filter().update(SERVER_CLOCK_OFFSET_US, 1000, platform_time_us()); } /// A server message on the current stand-in, as the protocol task dispatches it. @@ -1205,7 +1204,7 @@ TEST(SourceStream, CaptureGoesOutStampedOnTheServerClock) { ASSERT_EQ(chunk.size(), SOURCE_CHUNK_HEADER_SIZE + CHUNK_BYTES); EXPECT_EQ(chunk[0], SENDSPIN_BINARY_SOURCE_AUDIO); EXPECT_EQ(be64_to_host(chunk.data() + 1), - rig.conn().get_time_filter()->compute_server_time(capture_us)); + rig.conn().time_filter().compute_server_time(capture_us)); EXPECT_GT(be64_to_host(chunk.data() + 1), capture_us + SERVER_CLOCK_OFFSET_US / 2) << "the stamp was left on the client clock"; EXPECT_TRUE(std::equal(chunk.begin() + SOURCE_CHUNK_HEADER_SIZE, chunk.end(), pcm.begin())); @@ -2012,8 +2011,7 @@ TEST(SourceOpusStream, OpusIsAnnouncedOnlyWhenTheServerListsIt) { EXPECT_EQ(payload, std::vector(pcm.begin(), pcm.begin() + CHUNK_BYTES)); } EXPECT_EQ(be64_to_host(chunk.data() + 1), - rig.conn().get_time_filter()->compute_server_time(capture_us - - (opus ? 2500 : 0))); + rig.conn().time_filter().compute_server_time(capture_us - (opus ? 2500 : 0))); } } From fdd4f434826539dc76787f9ea48c637774ade572 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 10:51:45 -0500 Subject: [PATCH 2/2] Check that a later clock correction reaches the published slot The lifecycle test covered only the newcomer's first measurement, which flips synced, so a publish that fired only on that flip or on a primary change would have frozen readers at the first burst's clock unnoticed. A second measurement now has to move get_client_time() to its offset. --- tests/test_client_lifecycle.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tests/test_client_lifecycle.cpp b/tests/test_client_lifecycle.cpp index 9c7e4e7d..2fa4a895 100644 --- a/tests/test_client_lifecycle.cpp +++ b/tests/test_client_lifecycle.cpp @@ -3489,8 +3489,9 @@ std::shared_ptr make_synced_connection(ConnectionObservation // The time filter slot follows the primary admitted connection's filter: a synced connection // converts with its offset, a vacated slot reads as unsynced, the slot never keeps a connection -// alive, an unsynced newcomer installed over a synced one reads its own filter, and that -// newcomer's first measurement reaches the slot at the protocol task's next publish. +// alive, an unsynced newcomer installed over a synced one reads its own filter, and each of that +// newcomer's measurements, its first and a later correction, reaches the slot at the protocol +// task's next publish. TEST(ClientLifecycle, TheTimeFilterSlotFollowsTheAdmittedConnection) { ConnectionObservation dropped_obs; // All outlive the client ConnectionObservation replaced_obs; @@ -3516,10 +3517,20 @@ TEST(ClientLifecycle, TheTimeFilterSlotFollowsTheAdmittedConnection) { (void) replace_admitted(manager, newcomer); EXPECT_FALSE(client.is_time_synced()) << "the newcomer read the replaced connection's filter"; - newcomer->time_filter().update(SEEDED_SERVER_OFFSET_US, /*max_error=*/1000, platform_time_us()); + // Each measurement is stamped after the last: the filter skips one that is not. + const int64_t first_measured_at = platform_time_us(); + newcomer->time_filter().update(SEEDED_SERVER_OFFSET_US, /*max_error=*/1000, first_measured_at); manager.refresh_published_state(); EXPECT_TRUE(client.is_time_synced()) << "a measurement after admission never reached the slot"; EXPECT_EQ(client.get_client_time(SERVER_TS_US), SERVER_TS_US - SEEDED_SERVER_OFFSET_US); + + // A second measurement takes its offset as is, with no drift applied yet. + constexpr int64_t CORRECTED_OFFSET_US = SEEDED_SERVER_OFFSET_US + 5000; + newcomer->time_filter().update(CORRECTED_OFFSET_US, /*max_error=*/1000, + first_measured_at + 1000); + manager.refresh_published_state(); + EXPECT_EQ(client.get_client_time(SERVER_TS_US), SERVER_TS_US - CORRECTED_OFFSET_US) + << "a correction after the first measurement never reached the slot"; } // The sync task converts chunks with the current connection's offset. The fed