Skip to content

fix(playback): keep node-served sessions alive while media flows - #2156

Merged
Quick104 merged 3 commits into
mainfrom
fix/playback-node-activity
Oct 8, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/playback-node-activity

Conversation

@Quick104

@Quick104 Quick104 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #666 (the reverse case, where progress reports keep a session alive after its media stops; not changed here)
Validation tasks: none passed yet; could reach #1177 C3 and #1206 C2 (session cleanup), both not run

Casting from the Android app to a Google Cast TV stops about five minutes after the phone goes to sleep. The Cast receiver never reports playback progress; the phone does. When the phone stops reporting, the idle sweep expires the session as abandoned, and the node stops the transcode while the TV is still playing.

With this change, the node that serves the media records that the client is still receiving it, and the idle sweep counts that as activity. The session now ends about five minutes after the TV stops fetching media, not five minutes after the phone stops reporting.

Approach

  • The proxy records delivery from its egress metering writer as media bytes reach the client. Playback handlers (direct play, remux, HLS playlists and segments, on both the token and grant routes) mark their response with noteDelivery. Only a 2xx response that sends bytes counts, so HEAD, failed relays, unsatisfiable ranges and empty responses don't, and a long progressive response keeps counting while it flows. Subtitles, themes and downloads are not marked.
  • Each node writes silo:playback-delivery:{session_id} to Redis at most once per session every 20 seconds, off the request path. Records expire after six minutes. The node’s Redis client honors each write’s two-second context deadline on its sockets, including when the URL disables socket timeouts, so stalled writes release their connections.
  • On every sweep, CleanInactive reads the records of all remote-transport sessions and treats the latest delivery as activity. The delivery time comes from the record's remaining TTL, which Redis counts on its own clock, so node and API clocks don't need to agree. Reading every remote session, not only those about to expire, keeps a delivering stream counted toward stream limits between sweeps and lets the paused grace run from its last delivery.
  • If Redis can't be read in time, the sweep falls back to the session's other activity, such as progress reports, as before. It does not hold sessions open, because an outage would then keep every remote session alive with no bound. The lookup uses its own Redis client whose sockets honor the sweep's deadline, so a Redis that stops answering can't hold the sweep or a connection, even when the URL disables socket timeouts.
  • Paused state still comes only from progress reports. Sessions created through jellycompat aren't marked as remote-transport, so they don't read these records yet.
  • There is no API, schema, or client change. Protocol doc §2.5 describes the record.

Validation

  • Go (1.26.5, Linux): go build ./..., gofmt, go vet ./..., and make lint-changed (0 issues) pass. The full Go suite passed 173 packages and failed TestRunStatsWithRealFFmpeg in internal/mediasample with FFmpeg 6.1.1 (a frame at 11.003 seconds falls outside the expected window). The same test fails on the original PR head, f71625a.
  • Focused delivery, remote-session, and compatibility activity tests pass with -race against Redis 7.0.15. Database tests were not run against a live database.
  • Web: lint, format, build, bundle budget, and make test-web passed before the Redis write timeout fix; that fix changes Go startup, a Go test, and the protocol documentation.
  • Contracts and docs: all make verify-* targets in the gate and the committed-router check pass.
  • The regression test for stalled writes runs without Redis and verifies that the delivery writer closes its connection and releases the pool slot. It fails with the ordinary Redis client and passes with the client that honors context deadlines.
  • The proxy and sweep tests run without Redis, so CI runs them. The Redis-backed tests (writing and reading records, the mounted proxy recording a segment and skipping HEAD and failed segments) ran against Redis 7 with -race; CI has no Redis, so they skip there like the repo's other Redis tests.
  • Device checks under Evidence predate the Redis write timeout fix; that fix was verified with tests.
  • Not tested on a device: direct play and progressive remux through a node (tests only), and a phone that actually sleeps; the sender app was force-stopped instead.

Evidence

Before (main) After (this branch)
The phone stops reporting progress. The server expires the session about 5 minutes later and the TV stops playing. Silo force-stopped on the phone: the TV keeps playing and the session stays alive for 11.5 minutes with no progress reports. After the TV stops, the session ends 5 minutes 10 seconds after its last media request.

Surface and build: Silo Android 0.3.11 on a Pixel casting a server-transcoded HLS stream to the Google Cast Default Media Receiver on an Onn 4K, through a remote node. The phone run used an earlier revision of this branch that recorded delivery per request. The media delivery implementation was checked against the same TV with a scripted Cast sender on an isolated test deployment with a proxy and a transcode node. With no progress reports, the session stayed alive for 11 minutes, then ended 5 minutes 7 seconds after the TV stopped.

Risks

  • Proxy and transcode node Redis operations now honor the caller’s context deadline; delivery writes supply two seconds.
  • Redis load: one SET per active node-served session every 20 seconds, plus one pipelined PTTL per sweep (every 15 seconds) covering the remote-transport sessions on that API replica.
  • A client that keeps fetching media keeps its session alive, as intended. That includes a paused player that keeps polling an HLS playlist.
  • During a rolling deploy, nodes without this change don't write records, and those sessions expire as they do today.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code and OpenAI Codex, running in T3 Code
  • Tool(s): Claude Code; OpenAI Codex (review and implementation); pychromecast (scripted Cast sender)
  • Model(s): claude-opus-5-5[1m]; gpt-6.1-sol (review and implementation)
  • Involvement: Fully AI-generated, at a maintainer's request; the maintainer has not yet reviewed the diff
  • Adversarial review: OpenAI Codex (gpt-6.1-sol) reviewed the complete diff and reproduced the node Redis write timeout defect. Tests cover response eligibility, session activity, write throttling, and stalled Redis reads and writes. A failed delivery lookup falls back to other activity; Jellyfin compatibility sessions do not use these delivery records.

🤖 Generated with Claude Code

Note

Keep node-served playback sessions alive via Redis delivery records

  • Proxy nodes now record media delivery per playback session in Redis via Tracker.RecordDelivery, at most once per 20 seconds per session, with a 6-minute expiry. Only 2xx responses with positive body bytes count; HEAD requests and failed relays are excluded (delivery.go, delivery.go).
  • API nodes read these records during idle sweeps with SessionManager.refreshDeliveryActivity, so remote-transport sessions served by a proxy node are not expired while media still flows. A failed lookup falls back to normal activity instead of protecting sessions (session.go).
  • Adds NewDeadlineRedisClientForRole so delivery reads and writes honor context deadlines and do not hold connections on stalled Redis servers (redis.go).
  • Risk: Tracker.Cleanup no longer deletes delivery records on shutdown; they expire on their own 6-minute lifetime. Integration tests need SILO_TEST_REDIS_URL set.

Macroscope summarized f9ad016.

A session whose media a proxy node serves stayed alive only on its client's
progress reports. A Google Cast receiver pulls media itself but never reports
progress; its sender phone does. When the phone slept, the API reaped the
session five minutes later and the TV stopped mid-playback.

Proxy nodes now record playback delivery in Redis
(silo:playback-delivery:{session_id}) as media bytes reach the client: only
2xx playlist, segment, and progressive responses that send bytes count, and a
long progressive response keeps counting while it flows. Each node writes at
most once per 20 seconds per session, off the request path.

On every sweep the API reads the records of its remote-transport sessions and
counts a live record as activity at the time it was written, derived from the
record's TTL so node and API clocks need not agree. Merging on every sweep,
not only for sessions about to expire, keeps delivering streams counted
toward stream limits and lets the paused grace run from the last delivery.
Records live six minutes, longer than the five-minute remote grace, so a
session ends five minutes after its last delivery. A failed Redis read falls
back to the other activity, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-08T19:49:24.870864Z f9ad016 New commits
🔒 Security Review ✅ Completed 2026-10-08T19:49:54.051718Z f9ad016 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104 Quick104 added priority: P1 Core-path bug; painful workaround — next after P0 impact: playback Can't play, stalls, or wrong media labels Oct 8, 2026 — with Cursor
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5ad9b314-ea01-4c88-bb50-017929efb956
📥 Commits

Reviewing files that changed from the base of the PR and between 6bdbb7d and 849ebba.

📒 Files selected for processing (14)
  • cmd/silo/main.go
  • docs/architecture/playback-protocol-v3.md
  • internal/nodesessions/delivery.go
  • internal/nodesessions/delivery_test.go
  • internal/nodesessions/tracker.go
  • internal/playback/session.go
  • internal/playback/session_activity.go
  • internal/playback/session_remote_transport_test.go
  • internal/proxy/delivery.go
  • internal/proxy/delivery_activity_test.go
  • internal/proxy/delivery_test.go
  • internal/proxy/egress.go
  • internal/proxy/mediagrant.go
  • internal/proxy/server.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

Proxy media responses now record successful delivery activity in Redis. Playback session cleanup reads these records to refresh remote-transport session activity. The change also adds delivery-record expiry, write throttling, tests, and architecture documentation.

Changes

Playback delivery activity

Layer / File(s) Summary
Redis delivery records
internal/nodesessions/delivery.go, internal/nodesessions/tracker.go, internal/nodesessions/delivery_test.go
The tracker writes delivery records to Redis with a six-minute expiry and throttles writes per session. RecentDeliveries reads live records, and tests cover timing, expiry, pruning, and lookup deadlines.
Proxy response delivery capture
internal/proxy/delivery.go, internal/proxy/egress.go, internal/proxy/mediagrant.go, internal/proxy/server.go, internal/proxy/delivery_test.go, internal/proxy/delivery_activity_test.go
Playback-serving paths mark requests for delivery tracking. The metered response writer records delivery when a marked response sends body bytes with a status below 300. Tests cover response cases and mounted proxy paths.
Remote-session activity refresh
internal/playback/session.go, internal/playback/session_activity.go, internal/playback/session_remote_transport_test.go, cmd/silo/main.go, docs/architecture/playback-protocol-v3.md
Session cleanup refreshes remote-transport activity from delivery records before expiring sessions. Application setup installs the reader when API Redis is available. Tests cover refresh and expiry behavior; the architecture documentation describes the tracking behavior.

Priority: ➖ Normal

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Proxy
  participant Tracker
  participant Redis
  participant SessionManager
  Proxy->>Tracker: RecordDelivery(sessionID)
  Tracker->>Redis: Write delivery key with expiry
  SessionManager->>Redis: RecentDeliveries(active session IDs)
  Redis-->>SessionManager: Delivery timestamps
  SessionManager->>SessionManager: Refresh remote-session activity before cleanup
Loading

Merge Risk: ⚪ Minimal · up to 849eb

No actionable issue remains that should block merging. Normal validation can proceed, with Redis-backed tests and device scenarios still subject to the reported testing limits.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 74.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 13 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description check ✅ Passed The description clearly explains the playback session cleanup issue, Redis delivery tracking approach, validation, evidence, and risks. It is directly related to the changeset.
Title check ✅ Passed The title clearly and concisely identifies the main change: keeping node-served playback sessions active while media continues to flow.
Full details: Docstring Coverage

Explanation

Docstring coverage is 74.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 13 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@macroscopeapp

macroscopeapp Bot commented Oct 8, 2026

Copy link
Copy Markdown

The playback effect—Cast playback continuing after progress reports stop, then ending about five minutes after media delivery stops—has only a written before/after description. Add a recording that demonstrates this timing; the PR already names the surface and build.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

Comment thread internal/nodesessions/delivery.go Resolved
… deadline

The idle sweep waits on the node delivery lookup. The API's shared Redis
client takes its socket timeouts from the URL, which may disable them, so a
Redis that stopped answering could hold the lookup, and with an abandoned
lookup a pooled connection, indefinitely.

The lookup now uses its own client whose sockets honor the caller's context
deadline (cache.NewDeadlineRedisClientForRole), so a stalled read ends at the
sweep's deadline and frees the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-kody

silo-kody Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104
Quick104 merged commit d01d2f3 into main Oct 8, 2026
18 of 19 checks passed
@Quick104
Quick104 deleted the fix/playback-node-activity branch October 8, 2026 19:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact: playback Can't play, stalls, or wrong media priority: P1 Core-path bug; painful workaround — next after P0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant