Skip to content

state: move stream configuration into client state - #270

Merged
chrisuthe merged 10 commits into
mainfrom
chrisuthe/state-stream-configuration-in-client-state
Sep 17, 2026
Merged

chrisuthe merged 10 commits into
mainfrom
chrisuthe/state-stream-configuration-in-client-state

Conversation

@chrisuthe

@chrisuthe chrisuthe commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Implements merged spec PRs Sendspin/spec#175, #176, #181, #195 and #204, and folds in the per-client role-configuration fixes that go with them.

What changes

  • stream/request-format is gone (Controller role has no seek support: seek/seek_relative, position_ms/offset_ms, and seek_max_ms are all missing #195). Removed from the wire, the message vocabulary and the source-generated serializer; an inbound message of that type now deserializes to null. StreamRequestFormatMessage is deleted.

    Was Now
    RequestPlayerFormatAsync(codec, sampleRate, channels, bitDepth) SetPlayerFormatPreferenceAsync(AudioFormat?)
    RequestArtworkFormatAsync(channel, source, format, mediaWidth, mediaHeight) SetArtworkChannelAsync(channel, source, format, width, height)
    RequestVisualizerFormatAsync(types, rateMax, spectrum) SetVisualizerConfigurationAsync(types, rateMax, spectrum)

    Each new method updates the client's own role configuration and resends the whole client/state, so the configuration and the message describing it cannot disagree.

  • client/state is the full state (Run the test suite on net8.0 as well as net10.0 #175). Server-side merging is removed: every message carries the complete state of each object it includes, and role objects follow active_roles. ClientStateMessage collapses to a single Create(...) factory; CreateInitial, CreateAvailability and CreatePlayerState are removed. PlayerStatePayload.OutputDelayMs is an int.

  • Visualizer configuration moves (Zeroize handshake and CPace key material #176/Stop blaming the server version for an abnormal listen-path close #181). types, rate_max and spectrum move out of client/hello into the client/state visualizer object; visualizer@v1_support keeps only buffer_capacity. ClientCapabilities.VisualizerSupport becomes VisualizerRoleSupport, one app-facing type spanning both wire objects.

  • Artwork moves. artwork@v1_support is removed from client/hello; the channel list is reported in client/state. ArtworkChannelSpec becomes ArtworkChannelState with Width/Height (was MediaWidth/MediaHeight), and channel defaults are applied consistently.

  • Binary gating (Provisional-connection timeout sends goodbye reason 'handshake_timeout', outside the spec's closed reason set #204). A role's inbound binary data is dropped until that role's client/state object has been sent.

  • Concurrency fix. Per-client role configuration is guarded by a lock, so concurrent Set*Async calls cannot interleave a partially updated client/state.

Breaking behaviour

  • Request*FormatAsync, StreamRequestFormatMessage, ClientStateMessage.CreateInitial/CreateAvailability/CreatePlayerState, ClientCapabilities.VisualizerSupport, ArtworkChannelSpec and ClientHelloMessage.Create(…, artworkSupport, …) no longer compile.
  • Servers relying on client/state merging will see full-state messages; servers sending stream/request-format are ignored.
  • Binary frames for a role that has not yet reported its client/state object are dropped rather than delivered.

Docs: README and MIGRATION-10.0.0.md gain §17 (stream/request-format removal and role configuration in client/state), the full-state rule, the visualizer/artwork moves and the binary gate.

Tests

dotnet build
  Build succeeded. 0 Error(s)

dotnet test tests/Sendspin.SDK.Tests/Sendspin.SDK.Tests.csproj
  net8.0   Passed! - Failed: 0, Passed: 1136, Skipped: 0, Total: 1136
  net10.0  Passed! - Failed: 0, Passed: 1138, Skipped: 0, Total: 1138

New: ClientStateFullStateTests, RoleConfigOwnershipTests, RoleStateBinaryGatingTests. ClientStateAvailableTests and ClientStateDeltaTests are removed with delta/merge semantics.

Stack

  1. chrisuthe/protocol-remove-management-namespace — management namespace removal (Clear the concurrency and timing residue in SendspinConnection #183)
  2. chrisuthe/pairing-records-and-pair-methods — pairing wire and record semantics (Storage hardening follow-ups from the secure-storage slice #178/Narrow or justify the remaining catch (Exception) sites off the peer-input path #179/Answer every management request, including wrong-kind payloads #189/Clear the concurrency and timing residue in SendspinConnection #183)
  3. this PR — base is (2), not main

This is the stack tip: its tree is the fully integrated, tested state. Merge in order.

Closes #278 — artwork dimensions are width/height on the wire in ClientStateMessage.cs and StreamStartArtwork.cs; the media_width/media_height objects in ClientHelloMessage.cs and StreamRequestFormatMessage.cs are deleted by this PR.

Implements merged spec PRs Sendspin/spec#175, #176, #181, #195 and #204, and
folds in the per-client role-configuration fixes that go with them.

- Remove stream/request-format (#195) from the wire, the message vocabulary
  and the source-generated serializer. RequestPlayerFormatAsync,
  RequestArtworkFormatAsync and RequestVisualizerFormatAsync are replaced by
  SetPlayerFormatPreferenceAsync, SetArtworkChannelAsync and
  SetVisualizerConfigurationAsync, each of which updates the client's own
  role configuration and resends the whole client/state, so the state and
  the message describing it cannot disagree.
- client/state carries the full state of every object it includes (#175):
  server-side merging is gone, role objects follow active_roles, and
  ClientStateMessage collapses to a single Create(...) factory.
  CreateInitial, CreateAvailability and CreatePlayerState are removed and
  PlayerStatePayload.OutputDelayMs is an int.
- Visualizer runtime configuration (types, rate_max, spectrum) moves out of
  client/hello into the client/state visualizer object (#176/#181);
  visualizer@v1_support keeps only buffer_capacity, and
  ClientCapabilities.VisualizerSupport becomes VisualizerRoleSupport.
- artwork@v1_support is removed from client/hello; the channel list is
  reported in client/state. ArtworkChannelSpec becomes ArtworkChannelState
  with Width/Height, and artwork channel defaults are applied consistently.
- Gate a role's inbound binary data until that role's client/state object has
  been sent (#204).
- Guard the per-client role configuration with a lock so concurrent
  Set*Async calls cannot interleave a partially updated client/state.

Docs: README and the v10 migration guide gain the request-format removal, the
full-state rule, the visualizer/artwork moves and the binary gate.

Tests: net8.0 1136/1136 and net10.0 1138/1138 passing; dotnet build clean.

Stacked on chrisuthe/pairing-records-and-pair-methods.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Empty artwork configuration can emit a spec-invalid channel array, and the noted documentation errors remain unresolved.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Moves stream and role configuration into full client/state messages in line with the updated Sendspin specification.

Changes:

  • Replaces stream/request-format with state-based configuration APIs.
  • Moves artwork and visualizer configuration into per-client state.
  • Adds binary gating, configuration synchronization, tests, and migration guidance.
File summaries
File Description
tests/Sendspin.SDK.Tests/Protocol/PlayerTimingSerializationTests.cs Updates full-state timing serialization tests.
tests/Sendspin.SDK.Tests/Protocol/MessageSerializerTests.cs Verifies handling of the removed message type.
tests/Sendspin.SDK.Tests/Protocol/ClientStateFullStateTests.cs Adds full-state wire coverage.
tests/Sendspin.SDK.Tests/Protocol/ClientStateDeltaTests.cs Removes obsolete delta-state tests.
tests/Sendspin.SDK.Tests/Protocol/ClientStateAvailableTests.cs Removes superseded availability tests.
tests/Sendspin.SDK.Tests/Client/SendspinClientServiceVisualizerTests.cs Tests visualizer state configuration.
tests/Sendspin.SDK.Tests/Client/SendspinClientServicePlayerFormatTests.cs Tests player format preferences.
tests/Sendspin.SDK.Tests/Client/SendspinClientServiceOutputDelayTests.cs Updates output-delay assertions.
tests/Sendspin.SDK.Tests/Client/SendspinClientServiceErrorStateTests.cs Adapts error-state expectations.
tests/Sendspin.SDK.Tests/Client/SendspinClientServiceArtworkTests.cs Tests artwork state and reconfiguration.
tests/Sendspin.SDK.Tests/Client/RoleStateBinaryGatingTests.cs Adds role binary-gating coverage.
tests/Sendspin.SDK.Tests/Client/RoleConfigOwnershipTests.cs Tests configuration isolation and concurrency.
tests/Sendspin.SDK.Tests/Client/PairingQuiescenceTests.cs Updates pairing-state coverage.
tests/Sendspin.SDK.Tests/Client/MediaDisplaySchedulingTests.cs Uses the new visualizer configuration type.
tests/Sendspin.SDK.Tests/Client/InitialClientStateGatingTests.cs Updates initial full-state gating assertions.
tests/Sendspin.SDK.Tests/Client/ClientHelloSupportRoleGatingTests.cs Verifies revised hello support objects.
tests/Sendspin.SDK.Tests/Client/ClientAvailabilityTests.cs Updates availability transition tests.
tests/Sendspin.SDK.Tests/Client/AvailabilityTrackerRaceTests.cs Adapts availability typing.
src/Sendspin.SDK/README.md Documents the new APIs; artwork-role and 24-bit format examples need correction.
src/Sendspin.SDK/Protocol/MessageSerializerContext.cs Removes obsolete serializer metadata.
src/Sendspin.SDK/Protocol/MessageSerializer.cs Removes request-format deserialization.
src/Sendspin.SDK/Protocol/Messages/VisualizerMessages.cs Narrows hello visualizer support.
src/Sendspin.SDK/Protocol/Messages/StreamStartArtwork.cs Updates artwork state references.
src/Sendspin.SDK/Protocol/Messages/StreamRequestFormatMessage.cs Deletes the retired message model.
src/Sendspin.SDK/Protocol/Messages/MessageTypes.cs Removes the retired message type.
src/Sendspin.SDK/Protocol/Messages/ClientStateMessage.cs Defines complete role-state payloads.
src/Sendspin.SDK/Protocol/Messages/ClientHelloMessage.cs Removes artwork hello support.
src/Sendspin.SDK/Protocol/Messages/ArtworkSources.cs Updates channel-state documentation.
src/Sendspin.SDK/MIGRATION-10.0.0.md Documents migration; ownership guidance contradicts per-client copying.
src/Sendspin.SDK/Client/VisualizerRoleSupport.cs Adds unified visualizer configuration.
src/Sendspin.SDK/Client/SendSpinClient.cs Implements state composition and gating, but permits an invalid empty artwork channel array.
src/Sendspin.SDK/Client/ISendSpinClient.cs Replaces format-request APIs.
src/Sendspin.SDK/Client/ClientCapabilities.cs Updates artwork and visualizer capabilities.
Review details

Suppressed comments (6)

src/Sendspin.SDK/Client/SendSpinClient.cs:998

  • The binary gate is opened before the state send is even submitted to the transport. Both transports can await their send lock, so a queued or failed send leaves a window where inbound role data is accepted although the server has not received the role object. Mark the role only after SendAsync completes successfully.
        MarkRoleStateSent(message.Payload);

src/Sendspin.SDK/Client/SendSpinClient.cs:2378

  • Changing active_roles never invalidates _roleStateSent; that set is otherwise cleared only on a new connection and only ever gains entries. After artwork is deactivated and later reactivated, its old readiness therefore lets binary frames through before the fresh state required for reactivation is sent. Clear the readiness snapshot before reannouncing the new full state.
            activeRolesChanged = !LastServerHello.ActiveRoles.ToHashSet(StringComparer.Ordinal)
                .SetEquals(payload.ActiveRoles);

            LastServerHello.ActiveRoles = payload.ActiveRoles;

src/Sendspin.SDK/Client/SendSpinClient.cs:991

  • Each builder independently reads the mutable LastServerHello.ActiveRoles. A concurrent server/activate can replace that list between these calls, producing one state message that combines objects from the old and new role sets (including an inactive role or omitting an active one). Snapshot the active roles once under synchronization shared with activation updates and build every object from that snapshot.
            available: available,
            player: BuildPlayerState(),
            source: BuildSourceState(),
            artwork: BuildArtworkState(),
            visualizer: BuildVisualizerState());

src/Sendspin.SDK/Client/SendSpinClient.cs:957

  • The runtime setter rejects types containing spectrum without a spectrum object, but the initial VisualizerRoleSupport path bypasses that invariant and serializes the same protocol error here. A client configured that way can have its connection closed during its first state send. Validate the constructor-supplied copy with the same rule before the handshake/state send.
        return new VisualizerStatePayload
        {
            Types = new List<string>(support.Types),
            RateMax = support.RateMax,
            Spectrum = support.Spectrum,

src/Sendspin.SDK/README.md:735

  • This collection initializer adds to ClientCapabilities.Roles rather than replacing its default list, which already contains artwork@v1; the sample therefore advertises the role twice and does not create the artwork-only configuration it appears to show. Assign a new list instead.
    Roles = { "artwork@v1" },

src/Sendspin.SDK/README.md:658

  • This example throws with the documented default capabilities: default FLAC is advertised as 48 kHz, 2-channel, 16-bit (BitDepth = null is normalized to 16), while this requests 24-bit and the new method rejects formats that were not advertised. Use 16-bit here or show the matching 24-bit AudioFormats configuration first.
    Codec = "flac", Channels = 2, SampleRate = 48000, BitDepth = 24,
  • Files reviewed: 33/33 changed files
  • Comments generated: 2
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Sendspin.SDK/MIGRATION-10.0.0.md Resolved
chrisuthe and others added 4 commits September 9, 2026 15:31
Harden role-state publication and correct artwork, visualizer, and migration behavior.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Do not advertise artwork in the interop harness while aiosendspin 9.1.1 still requires the retired artwork@v1_support hello field.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Base automatically changed from chrisuthe/pairing-records-and-pair-methods to main September 16, 2026 19:42
…lient state

Bring PR #269's current tip onto PR #270's client-state stream configuration:
the shared pairing-record store lock, live-record PSK collection over open and
adopted clients, lockout key migration, long-term capacity accounting, the
server/activate format rejection for static/PSK methods, pairing-code
presentation, the migration-guide fixes, and the aiosendspin 10.0.0-draft
interop pin.

Interop: take #269's interop.yml and pair-method patch script verbatim. #270's
three 9.1.1-era interop workarounds are obsolete under #269's 10.0.0-draft pin,
which accepts the current wire and runs the static-pin scenario: the redundant
patch step and the static-pin skip are dropped. The Program.cs artwork opt-out
is left in place.
…amples

The collection initializer without new() appends to the five-role default, so
the visualizer and source snippets advertised player@v1 twice. Match the
artwork example and reset the role set with new().
@chrisuthe chrisuthe added the upstream Tracks spec or aiosendspin changes label Sep 16, 2026
main advanced past #270's branch point: #269 landed (fe3b263) and #275 and
#281 followed. #281 (830368e, forward-port of #280) folds the player's output
latency into both reported leads (required_lead_time_ms and min_buffer_ms) from
the first client/state on, re-reporting on OutputLatencyChanged and debouncing
unchanged repeats.

Reconcile with #270's single full-state client/state path so the structure
carries #281's behaviour: BuildPlayerState sources both lead values from
ReportedLeads(); SendClientStateAsync keeps the _lastReported* dedupe in step
with the leads it puts on the wire (read back from the built player object);
the OutputLatencyChanged subscription re-sends the full client/state. #281's
AudioPipeline / IAudioPipeline / ClientCapabilities.ExpectedOutputLatencyMs and
its live-lead tests are taken as-is. #281 and #275 tests pass unchanged.
@chrisuthe

Copy link
Copy Markdown
Member Author

Round-1 suppressed comments, decisions:

  • SendSpinClient.cs ~998 (binary gate marked before SendAsync completes): declined. A conformant server cannot send a role's binary before it has received that role's client/state object, and the send-failure rollback already exists.
  • ~2378 (_roleStateSent not invalidated on active_roles change): Fixed in 7abb229
  • ~991 (builders read mutable ActiveRoles without a snapshot): Fixed in 7abb229
  • ~957 (constructor-supplied VisualizerRoleSupport bypasses the spectrum validation): Fixed in 7abb229
  • README ~735 (appending Roles initializer): Fixed in 7abb229 and 6fd38c5 (the two remaining examples)
  • README ~658 (24-bit FLAC example): Fixed in 7abb229

Since round 1 the branch also merged the current main (b62f8ab), reconciling #281's lead-value reporting into the full-state client/state path; #281's tests pass unchanged. net8.0 1157/1157, net10.0 1159/1159.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

State-send ordering, readiness gating, failure rollback, and advertised-format validation have unresolved correctness races.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (2)

src/Sendspin.SDK/Client/SendSpinClient.cs:1044

  • MarkRoleStateSent runs before SendAsync has acquired the transport's send lock. If another frame is in flight when an activation adds a role, this state can remain queued while the dictionary already opens the role gate, so binary arriving before the server has received the object is accepted—the opposite of the #204 requirement. Mark readiness only after a successful send, and tie the completion to the current connection/activation generation so a stale send cannot reopen a reset gate.
        var claimedFamilies = MarkRoleStateSent(message.Payload);

src/Sendspin.SDK/Client/SendSpinClient.cs:1051

  • This records availability as sent before the transport write, but the failure path only rolls back role claims. If a concurrent availability flip is captured by a reconfiguration send that fails, PublishAvailabilityAsync sees the same value in _lastAvailabilitySent and suppresses its retry, leaving the server with the old availability. Preserve the previous tracker value and restore it conditionally on send failure, as the availability publisher already does.
        lock (_availabilityLock)
        {
            _lastAvailabilitySent = available;
        }
  • Files reviewed: 36/36 changed files
  • Comments generated: 2
  • Review effort level: Balanced

@chrisuthe

Copy link
Copy Markdown
Member Author

Round-2 suppressed comments, decisions:

  • SendSpinClient.cs ~1044 (readiness marked before the transport send lock): declined, same reason as round 1. A conformant server cannot send a role's binary before it has received that role's client/state; the send-failure rollback covers the throw path.
  • ~1051 (_lastAvailabilitySent recorded before the write, retry suppressed if a reconfiguration send fails during an availability flip): declined. A failed transport send means a dead connection, and the reconnect path resends the full state.

The concurrent-setter ordering finding (~1037) is accepted; fix incoming.

Two concurrent Set*Async calls each update their role config under
_roleConfigLock then send the full client/state. The lock keeps a snapshot
whole, but the two could snapshot in one order and hand their frames to the
transport in the other, landing the older snapshot last and overwriting the
newer role's configuration on the server. Guard snapshot-through-enqueue in
SendClientStateAsync with a SemaphoreSlim(1,1) held until SendAsync has been
awaited, so the transport takes frames in snapshot order. Every client/state
send routes through that method.

The gate makes two client/state sends in flight at once impossible by
construction, so the two #114 availability-race tests that forced that overlap
are rewritten to the serialized model, keeping their names, #114 references and
wire assertions. Adds a concurrent-setter test asserting the last accepted
client/state reflects both updates.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Binary readiness, visualizer validation, artwork defaults, and player-state synchronization have unresolved correctness issues.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (3)

Previously missed (3) — in code that hasn't changed since the last review.

src/Sendspin.SDK/Client/ClientCapabilities.cs:356

  • This validator silently accepts Roles containing visualizer@v1 when VisualizerRoleSupport is null. CreateClientHelloMessage then advertises the role but omits its required visualizer@v1_support object, and no visualizer state object can be sent, so a strict server can reject the hello. Reject that contradictory configuration here (or filter the role from supported_roles).
    src/Sendspin.SDK/Client/SendSpinClient.cs:941
  • This full-player snapshot is not synchronized with its multi-field writers. SendPlayerStateAsync updates volume and mute separately, and UpdateTimingAsync updates the two timing values separately; a concurrent artwork, visualizer, or availability send can therefore serialize a hybrid player state that never existed as one requested update. Protect player updates and this snapshot with one lock, or replace the mutable fields with an immutable snapshot.
    src/Sendspin.SDK/Client/SendSpinClient.cs:1541
  • Re-enabling a valid disabled channel can still produce an invalid state. For example, an initial ArtworkChannelState { Source = None, Format = null, Width = null, Height = null } is valid while disabled, but setting only source: Album preserves all three nulls even though the artwork spec requires them for an active source. Restore the channel defaults when no retained value exists.
  • Files reviewed: 36/36 changed files
  • Comments generated: 1
  • Review effort level: Balanced

_logger.LogInformation("Sending initial client/state:\n{Json}", MessageSerializer.Serialize(message));
}

var claimedFamilies = MarkRoleStateSent(message.Payload);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Declined (third time, same reason): a conformant server cannot send a role's binary before it has received that role's client/state object; the send-failure rollback covers the throw path, and no round 4 will be requested.

@chrisuthe

Copy link
Copy Markdown
Member Author

Round-3 suppressed comments, decisions:

  • SendSpinClient.cs ~941 (player snapshot not synchronized with the two-field writers): declined. Every writer's own full-state send follows immediately through the same serialized path, so a one-message hybrid is superseded before anything can act on it.
  • ClientCapabilities.cs ~356 (visualizer@v1 listed without VisualizerRoleSupport): accepted, fix incoming.
  • SendSpinClient.cs ~1541 (re-enabling an artwork channel with only a source leaves format/size null): accepted, fix incoming.

This was the third and last Copilot round for this PR.

…k channel

Two Copilot round-3 findings in code this PR introduced:

- ClientCapabilities advertising visualizer@v1 in Roles without a
  VisualizerRoleSupport emitted a client/hello that listed the role but omitted
  its required visualizer@v1_support object. ValidateVisualizerRoleSupport now
  rejects it at construction, alongside the existing spectrum check.

- SetArtworkChannelAsync re-enabling an app-supplied disabled channel (source
  none, format/size nulled) with a source alone kept the nulls, so the wire
  carried an active source without the format/width/height the spec requires. It
  now falls back to ArtworkChannelState's own defaults when the new source is
  active, the same defaults the gap filler keeps.

A test each. The two declined findings (gate-before-send, hybrid player
snapshot) are unchanged.
@chrisuthe

Copy link
Copy Markdown
Member Author

Round-3 accepted items (ClientCapabilities.cs ~356 visualizer role without its support object; SendSpinClient.cs ~1541 artwork channel defaults on re-enable): Fixed in 9514971

Three Copilot rounds complete; no further round will be requested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

upstream Tracks spec or aiosendspin changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Artwork dimensions still use the pre-rename media_width/media_height, which a strict server rejects

2 participants