Skip to content

fix(watch-together): stop a dropped socket reading as the host leaving - #487

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
RXWatcher:feat/watch-together-host-grace
Jul 27, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
RXWatcher:feat/watch-together-host-grace

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

hostDisconnectTTL was 15 seconds. That is not "how long before we assume the host left" — an explicit leave and an explicit close both tear the room down immediately, so this timer only ever covers a host who has not said they are going.

At 15s any transient drop read as a departure. A host who backgrounded the app, hit a brief network blip, or simply moved to a screen where the client did not hold the socket open lost the room for everybody, mid-conversation, with a host_left reason nobody could explain.

Change

Two minutes. Long enough to survive a reconnect or an app switch; short enough that a genuinely departed host does not leave a room sitting open all evening. The janitor still reaps idle rooms independently, and both explicit paths still close immediately.

Why now

This is one half of a pair. Silo-Server/silo-android#106 moves the room's websocket out of screen scope so a member can stay in a room while browsing for something to suggest — which is what a vote room needs its members to do.

The two are complementary rather than redundant, and neither is sufficient alone:

  • The client change stops us reporting "host left" when the host merely navigated. That is the bug; papering over it with a longer timeout alone would leave the room silently disconnected while it looked fine.
  • This server change covers the drops the client cannot prevent — backgrounding, connectivity, process death — where 15 seconds is simply too tight a window to reconnect in.

Reviewing either alone invites the wrong question ("why hoist if the TTL is generous?" / "why 2 minutes if navigation no longer drops the socket?"). They answer different failure modes.

Testing

internal/watchtogether green. The existing suite already overrides this value where it matters (service.hostDisconnectTTL = time.Hour), so no test asserted the old constant.

Not exercised against a real disconnect. The value change is trivially correct in isolation; what is unverified is the end-to-end behaviour it exists to support, which needs two devices in a room with one of them backgrounding.

AI-use disclosure

Written by Claude Opus 5 (Claude Code) working with @RXWatcher, who described the flow — create a room, leave it, find something to suggest, come back — that this 15s timeout made impossible.

Summary by CodeRabbit

  • New Features
    • Added vote-based winner validation when promoting suggestions.
    • Vote-mode rooms now select playback based on the winning suggestion.
  • Bug Fixes
    • Prevented direct content selection in vote-mode rooms.
    • Added deterministic tie-breaking for equal vote counts.
    • Added clear 409 Conflict responses for invalid vote-room actions (including no votes yet / not the winner).
  • Tests
    • Added coverage for winner selection and vote-mode gating behavior.
  • Chores
    • Increased the host-disconnect grace period to two minutes.

RXWatcher and others added 3 commits July 26, 2026 16:58
selection_mode has been stored, normalized and published since the
feature landed, and nothing has ever read it. A "vote" room behaved
exactly like a host_pick one: members could suggest and vote, the tally
was recorded and broadcast, and then the host promoted whatever they
liked regardless of it.

In a vote room the host now starts the winner rather than choosing it.
Promoting anything other than the leading suggestion is refused, because
being able to overrule the tally makes the mode host_pick with extra
steps and turns the vote counts on everyone else's screen into
decoration.

The winner is the head of the repository's existing ordering
(vote_count DESC, created_at ASC): most votes, ties to whoever suggested
first — deterministic, and re-suggesting a title cannot jump the queue.

A room where nobody has voted has no winner and says so, rather than
quietly promoting the oldest suggestion as though a vote had happened.

host_pick rooms are untouched: the host still promotes freely.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Gating PromoteSuggestion left SelectItem wide open: it is host-only but
was not gated by selection mode, so the host of a vote room could set any
title directly and bypass the vote entirely. Enforcing the tally on one
path and not the other makes the vote counts on everyone else's screen
decoration.

A vote room now refuses a direct selection outright. The winner is the
only way in.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
hostDisconnectTTL was 15 seconds, which treated any transient drop as a
departure. An explicit leave and an explicit close already tear the room
down immediately, so this timer only ever covers a host who has NOT said
they are going — and at 15s a host who backgrounded the app, moved
between screens, or hit a brief network blip lost the room for everyone
with a "host_left" nobody could explain.

Two minutes survives a reconnect or an app switch, and is short enough
that a genuinely departed host does not leave a room open all evening.
The janitor still reaps idle rooms independently.

This matters for what the clients are growing into: a room you stay in
while you browse for something to suggest. A client that drops its socket
when the lobby leaves composition should cost you a reconnect, not the
room.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Vote-mode rooms now reject direct selection, require promotion of the computed vote winner, and return specific HTTP conflict responses. Winner resolution, tie behavior, and selection-mode gates are tested. Host disconnect handling now uses a two-minute default TTL.

Changes

Vote selection enforcement

Layer / File(s) Summary
Selection contracts and gating
internal/watchtogether/service.go
Adds voting errors, blocks direct selection in vote rooms, and uses a named two-minute host disconnect TTL.
Winner resolution and promotion
internal/watchtogether/service.go, internal/watchtogether/vote_selection_test.go, internal/watchtogether/vote_winner_test.go
Resolves winners from ordered suggestions, restricts promotion to the winner, preserves host-pick behavior, and tests empty votes, ties, and selection outcomes.
Vote conflict responses
internal/api/handlers/watch_together.go
Maps vote-related service errors to distinct 409 Conflict response codes and messages.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HandlePromoteSuggestion
  participant PromoteSuggestion
  participant VoteWinner
  Client->>HandlePromoteSuggestion: promote suggestion
  HandlePromoteSuggestion->>PromoteSuggestion: validate promotion
  PromoteSuggestion->>VoteWinner: resolve winner
  VoteWinner-->>PromoteSuggestion: winner or no votes
  PromoteSuggestion-->>HandlePromoteSuggestion: success or winner error
  HandlePromoteSuggestion-->>Client: 200 or 409 response
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the host-disconnect timeout change, which is a real part of the PR, though it omits the newer vote-room selection work.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/watchtogether/service.go`:
- Around line 895-897: Update the internal selection flow around SelectItem and
PromoteSuggestion so verified vote winners can be promoted without returning
ErrVoteRoomSelection. Preserve the public direct-selection guard, but have
PromoteSuggestion use a private shared transition after winner validation
instead of calling the guarded SelectItem path.
- Around line 1914-1924: Update PromoteSuggestion and the VoteWinner/SelectItem
persistence flow to use a repository-conditioned promotion tied to the
suggestion’s current tally or selection revision, so the write fails when a
concurrent vote changes the ordering before promotion commits. Preserve the
existing non-vote path and return the appropriate conflict/error when the
condition is not met; add a concurrent vote/promotion test covering this race.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d065393-8e46-44fb-95b6-7c3481fc81e8

📥 Commits

Reviewing files that changed from the base of the PR and between 99d2056 and 2baa52d.

📒 Files selected for processing (3)
  • internal/api/handlers/watch_together.go
  • internal/watchtogether/service.go
  • internal/watchtogether/vote_winner_test.go

Comment thread internal/watchtogether/service.go Resolved
Comment on lines +1914 to +1924
s.mu.Lock()
isVoteRoom := live.room.SelectionMode == RoomSelectionModeVote
s.mu.Unlock()
if isVoteRoom {
winner, err := s.VoteWinner(ctx, roomID)
if err != nil {
return Snapshot{}, err
}
if winner.ID != suggestion.ID {
return Snapshot{}, ErrNotVoteWinner
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate service.go =="
fd -a 'service\.go$' . | sed 's#^\./##' | rg 'internal/watchtogether/service.go|watchtogether' || true

echo "== read relevant lines =="
if [ -f internal/watchtogether/service.go ]; then
  wc -l internal/watchtogether/service.go
  sed -n '1860,1955p' internal/watchtogether/service.go | nl -ba -v1860
fi

echo "== search VoteWinner/Promote/Snapshot relevant symbols =="
rg -n "VoteWinner|Promote|Suggestion|RoomSelectionModeVote|ErrNotVoteWinner|AddVote|Vote" internal/watchtogether -S || true

Repository: Silo-Server/silo-server

Length of output: 344


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== relevant promotion code =="
sed -n '1860,1945p' internal/watchtogether/service.go

echo "== relevant symbols and usages =="
rg -n "VoteWinner|Promote|Suggestion|RoomSelectionModeVote|ErrNotVoteWinner|AddVote|Vote" internal/watchtogether/service.go -S

echo "== lock/schema snippets around tally/revision if present =="
rg -n "tally|revision|selection|VoteWinner|roomID" internal/watchtogether/service.go -S

Repository: Silo-Server/silo-server

Length of output: 12270


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== SelectItem implementation =="
sed -n '840,940p' internal/watchtogether/service.go

echo "== Vote/Winner implementation =="
sed -n '1780,1970p' internal/watchtogether/service.go

echo "== store interfaces/types for selection revision and voting =="
rg -n "type .*SuggestionStore|AddVote|RemoveVote|ListSuggestions|CreateSuggestion|GetSuggestion|UpdateSelection|SelectionRevision|selection_revision|Generation|ExpectedGeneration" internal -S -g '*.go'

echo "== find store implementations =="
git ls-files internal | rg 'suggestion|watchtogether|selection|store' || true

Repository: Silo-Server/silo-server

Length of output: 44807


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== vote winner tests =="
sed -n '1,240p' internal/watchtogether/vote_winner_test.go

echo "== service tests around suggestion/vote/promote/select =="
rg -n "PromoteSuggestion|ErrNotVoteWinner|SelectionModeVote|AddVote|Unvote|SelectItem|VoteRoom" internal/watchtogether/service_test.go internal/watchtogether -S

echo "== UpdateSelection SQL update =="
sed -n '180,260p' internal/watchtogether/repository.go

echo "== suggestion repository vote implementation =="
sed -n '1,185p' internal/watchtogether/suggestion_repository.go

Repository: Silo-Server/silo-server

Length of output: 14783


Atomically link vote-win promotion to the persisted tally.

PromoteSuggestion calls VoteWinner after fetching the room, then later SelectItem updates selection_revision against the room generation. A concurrent vote can make another suggestion pass the winner before the update runs, persisting a promotion that no longer matches the current vote ordering. Add a repository-conditioned promotion path that ties the write to the suggestion/tally revision, and cover it with a concurrent vote/promotion test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/watchtogether/service.go` around lines 1914 - 1924, Update
PromoteSuggestion and the VoteWinner/SelectItem persistence flow to use a
repository-conditioned promotion tied to the suggestion’s current tally or
selection revision, so the write fails when a concurrent vote changes the
ordering before promotion commits. Preserve the existing non-vote path and
return the appropriate conflict/error when the condition is not met; add a
concurrent vote/promotion test covering this race.

Source: Coding guidelines

The vote gate landed on both doors into a room's selection, but promoting
the winner walks through SelectItem to commit — so the gate meant to stop
the host bypassing the vote also stopped the vote itself. Vote rooms could
not start playback by any route.

Split the commit path: SelectItem keeps the gate for direct requests, and
PromoteSuggestion goes through the internal path once it has confirmed the
suggestion is the winner. Map ErrVoteRoomSelection in the promote handler
too, so a future regression there reads as a conflict rather than a 500.

Add service-level tests for both gates — the previous tests only covered
the pure winnerFrom helper, which is why the suite stayed green while vote
rooms were non-functional.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor

Pushed 769c28b to this branch (maintainer edit) — it fixes a blocker in the vote-gating half of the diff and adds the tests for it.

Vote rooms could not start playback by any route. The gate landed on both doors into a room's selection, but PromoteSuggestion walks through SelectItem to commit, so the guard meant to stop the host bypassing the vote also stopped the vote itself. Direct select was gated, and promote — the only intended path — was gated by the same check.

The fix splits the commit path: public SelectItem keeps the gate for direct requests; PromoteSuggestion goes through an internal selectItem(..., viaVote) once it has confirmed the suggestion is the winner. ErrVoteRoomSelection is now also mapped in HandlePromoteSuggestion — unreachable after the fix, but there so a regression in that path reads as a conflict instead of a 500.

Tests. internal/watchtogether/vote_selection_test.go covers promote-the-winner starts the room, promote-a-runner-up → ErrNotVoteWinner, promote-before-any-votes → ErrNoVotesCast, direct select in a vote room → ErrVoteRoomSelection, and host_pick untouched by either gate. Confirmed the first one fails against the pre-fix code. The existing vote_winner_test.go only exercised the pure winnerFrom helper, which is why the suite stayed green while vote rooms were broken.

TOCTOU on the tally (VoteWinner reads unlocked, SelectItem commits after): documented rather than closed. The host presses start on the standings the room could see, and closing the window means holding the room lock across a suggestion-store read, which stalls every other room for a worst case of one vote. Reasoning is in the comment above the check.

Open question for review — API compatibility. PUT /rooms/{id}/selection used to succeed in a vote room and now returns 409. That is a previously-succeeding request that now fails on an existing /api/v1 endpoint, which the additive-only rule in CLAUDE.md points at. I left the gate in because it is the point of the change, and the exposure looks small: the web client never calls it in vote mode (WatchTogetherRoomPage.tsx:451 routes vote rooms to "suggest"), and selection_mode is already on the room response so clients have the feature-detection signal. Someone should confirm silo-apple and silo-android do not call /selection directly in a vote room — if either does, this needs a coordinated client change before it ships.

Also worth noting: the PR description still describes this as a one-line hostDisconnectTTL change, but the diff also hard-gates selection in vote rooms. Worth updating the body so reviewers know to look at that half.

Verified: go test -count=1 -race ./internal/watchtogether/ passes; gofmt clean on both touched packages. Not run: make lint (golangci-lint not installed locally) and go build ./... (fails on the pre-existing web/embed.go missing dist, unrelated).

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/watchtogether/vote_selection_test.go`:
- Around line 130-140: Update TestHostPickRoomIsUntouchedByTheVoteGates to
create separate fresh service fixtures for the SelectItem and PromoteSuggestion
assertions. Keep each operation running against its own initial host-pick lobby
so the promotion check is independent of SelectItem’s room mutation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0f766230-437e-46c7-bde1-6e4ef22d9e51

📥 Commits

Reviewing files that changed from the base of the PR and between 2baa52d and 769c28b.

📒 Files selected for processing (3)
  • internal/api/handlers/watch_together.go
  • internal/watchtogether/service.go
  • internal/watchtogether/vote_selection_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/api/handlers/watch_together.go
  • internal/watchtogether/service.go

Comment on lines +130 to +140
func TestHostPickRoomIsUntouchedByTheVoteGates(t *testing.T) {
unvoted := []Suggestion{{ID: "a", RoomID: "room-1", ContentID: "movie-winner", VoteCount: 0}}
service, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)

if _, err := service.SelectItem(context.Background(), "room-1", 7, "host", SelectItemInput{
ContentID: "movie-winner",
}); err != nil {
t.Fatalf("SelectItem() error = %v, want a host_pick room to select directly", err)
}
if _, err := service.PromoteSuggestion(context.Background(), "room-1", "a", 7, "host"); err != nil {
t.Fatalf("PromoteSuggestion() error = %v, want a host_pick room to promote freely", err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Isolate the host-pick operations.

SelectItem mutates the room before PromoteSuggestion runs, so the promotion assertion is performed against a potentially playing room rather than a fresh lobby. Use separate service fixtures for the two assertions; otherwise this test can fail for an unrelated lifecycle precondition or stop validating promotion from the initial state.

Suggested adjustment
-	service, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)
+	directService, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)

-	if _, err := service.SelectItem(context.Background(), "room-1", 7, "host", SelectItemInput{
+	if _, err := directService.SelectItem(context.Background(), "room-1", 7, "host", SelectItemInput{
 		ContentID: "movie-winner",
 	}); err != nil {
 		t.Fatalf("SelectItem() error = %v, want a host_pick room to select directly", err)
 	}
-	if _, err := service.PromoteSuggestion(context.Background(), "room-1", "a", 7, "host"); err != nil {
+
+	promoteService, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)
+	if _, err := promoteService.PromoteSuggestion(context.Background(), "room-1", "a", 7, "host"); err != nil {
 		t.Fatalf("PromoteSuggestion() error = %v, want a host_pick room to promote freely", err)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestHostPickRoomIsUntouchedByTheVoteGates(t *testing.T) {
unvoted := []Suggestion{{ID: "a", RoomID: "room-1", ContentID: "movie-winner", VoteCount: 0}}
service, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)
if _, err := service.SelectItem(context.Background(), "room-1", 7, "host", SelectItemInput{
ContentID: "movie-winner",
}); err != nil {
t.Fatalf("SelectItem() error = %v, want a host_pick room to select directly", err)
}
if _, err := service.PromoteSuggestion(context.Background(), "room-1", "a", 7, "host"); err != nil {
t.Fatalf("PromoteSuggestion() error = %v, want a host_pick room to promote freely", err)
func TestHostPickRoomIsUntouchedByTheVoteGates(t *testing.T) {
unvoted := []Suggestion{{ID: "a", RoomID: "room-1", ContentID: "movie-winner", VoteCount: 0}}
directService, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)
if _, err := directService.SelectItem(context.Background(), "room-1", 7, "host", SelectItemInput{
ContentID: "movie-winner",
}); err != nil {
t.Fatalf("SelectItem() error = %v, want a host_pick room to select directly", err)
}
promoteService, _ := newVoteRoomService(t, RoomSelectionModeHostPick, unvoted)
if _, err := promoteService.PromoteSuggestion(context.Background(), "room-1", "a", 7, "host"); err != nil {
t.Fatalf("PromoteSuggestion() error = %v, want a host_pick room to promote freely", err)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/watchtogether/vote_selection_test.go` around lines 130 - 140, Update
TestHostPickRoomIsUntouchedByTheVoteGates to create separate fresh service
fixtures for the SelectItem and PromoteSuggestion assertions. Keep each
operation running against its own initial host-pick lobby so the promotion check
is independent of SelectItem’s room mutation.

@Quick104
Quick104 merged commit 172beb9 into Silo-Server:main Jul 27, 2026
3 checks passed
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