Repository navigation
fix(watch-together): stop a dropped socket reading as the host leaving - #487
Conversation
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
📝 WalkthroughWalkthroughVote-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. ChangesVote selection enforcement
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
internal/api/handlers/watch_together.gointernal/watchtogether/service.gointernal/watchtogether/vote_winner_test.go
| 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 | ||
| } |
There was a problem hiding this comment.
🗄️ 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 || trueRepository: 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 -SRepository: 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' || trueRepository: 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.goRepository: 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]>
|
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 The fix splits the commit path: public Tests. TOCTOU on the tally ( Open question for review — API compatibility. Also worth noting: the PR description still describes this as a one-line Verified: 🤖 Generated with Claude Code |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
internal/api/handlers/watch_together.gointernal/watchtogether/service.gointernal/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
| 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) |
There was a problem hiding this comment.
🎯 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.
| 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.
Problem
hostDisconnectTTLwas 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_leftreason 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:
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/watchtogethergreen. 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
409 Conflictresponses for invalid vote-room actions (including no votes yet / not the winner).