Skip to content

fix(streaming): stop killing healthy streams at the server WriteTimeout - #361

Merged
Quick104 merged 1 commit into
mainfrom
fix/streaming-write-deadline
Jul 10, 2026
Merged

Quick104 merged 1 commit into
mainfrom
fix/streaming-write-deadline

Conversation

@Quick104

@Quick104 Quick104 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

cmd/silo/main.go sets WriteTimeout: 120s on the main API server. Go's WriteTimeout is an absolute deadline from request start, not an idle timeout — every streaming response still being written at T+120s is killed mid-body with a clean connection close. Server log signature: path=/api/v1/stream/ entries with duration_ms=120000.

Live impact (root-caused on an Apple TV, 2026-07-09): every direct-stream of a 15.3 GB MKV died at exactly 120s. The client's byte-cursor reconnect absorbed most kills invisibly, but when one landed during backpressure parking or a demuxer resync, the client's retry budget exhausted and it did a full player teardown — a ~5s visible stop, roughly every 5–10 minutes, plus (on older client builds) audio desync seeded by the restart. Both compat listeners (jellycompat, ABS) already set WriteTimeout: 0 for exactly this reason; the main listener serving first-party clients was never aligned.

Fix

Rolling per-write deadline instead of timeout removal — new internal/httpstream.RollingDeadlineWriter:

  • Pushes the connection's write deadline forward on progress via http.ResponseController.SetWriteDeadline (semantics: "must make progress every 180s" instead of "must finish in 120s"). Window overridable via SILO_STREAM_WRITE_STALL_TIMEOUT.
  • Stalled/zombie connections are still reaped within the window — we deliberately do not set WriteTimeout: 0.
  • ReadFrom delegates in bounded slices so http.ServeContent keeps its sendfile fast path for direct play.
  • Deadline bumps rate-limited to one per 15s, not one per 32 KB chunk.

Wired into the five long-response paths on the main listener: direct play, remux, offline downloads, the transcode-node proxy, and ebook serving. The server-level 120s guard is unchanged for every other route.

Middleware Unwrap fixes: the metrics statusWriter and request-logger requestStatusWriter didn't implement Unwrap, so http.ResponseController couldn't traverse to the connection and the wrapper silently self-disabled (the first dev deploy proved this the hard way). Both now implement Unwrap, and a middleware-chain integration test (stream_deadline_chain_test.go) assembles the real chain (RequestLogger → Metrics → Compress) around a streaming handler with a 1s server WriteTimeout — it fails on truncation if a future wrapper breaks the chain again.

Tests

  • internal/httpstream: stream survives server WriteTimeout (regression test for the bug); unwrapped stream is still killed (guard intact); stalled client reaped within window; ReadFrom path completes past WriteTimeout.
  • internal/api/middleware: chain-integration guard test.
  • Full ./internal/playback and ./internal/api/handlers suites pass.

Validation on dev

  • Sustained range-GETs at playback rate: 200s / 512 MB direct and 300s / 768 MB via CDN with no early close (both previously died at ~120s).
  • Zero duration_ms=120000 stream entries since deploy.
  • Design doc: docs/design/2026-07-09-streaming-write-deadline.md.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Long-running media streams, downloads, remuxed playback, and ebook transfers can now continue beyond the server’s fixed write timeout while data is actively being delivered.
    • Stalled connections are still terminated after a bounded inactivity period.
    • Streaming behavior remains compatible with range requests and efficient file transfers.
  • Documentation

    • Added design and rollout guidance for rolling streaming write deadlines.
  • Tests

    • Added coverage for prolonged streaming, stalled clients, middleware compatibility, and file-transfer behavior.

The main API server's WriteTimeout (120s) is an absolute deadline from
request start, so every streaming response still being written at T+120s
was cut mid-body with a clean close. Clients saw multi-GB direct streams
truncate every two minutes; the Apple client's cursor-resume reconnect
absorbed most kills silently, but one landing during backpressure or a
demuxer resync exhausted its retry budget and forced a full player
teardown (visible stop + historical audio desync seeding).

Fix: internal/httpstream.RollingDeadlineWriter pushes the connection's
write deadline forward with progress via http.ResponseController — a
response that keeps moving lives indefinitely, a stalled one is still
reaped within the window (180s default, SILO_STREAM_WRITE_STALL_TIMEOUT
to override). ReadFrom delegates in bounded slices so http.ServeContent
keeps its sendfile fast path. Wired into direct play, remux, downloads,
the transcode-node proxy, and ebook serving; the server-level 120s guard
stays for every other route.

The metrics and request-logger response writers now implement Unwrap —
without it http.ResponseController cannot traverse to the connection and
SetWriteDeadline fails, silently disabling the fix (exactly what the
first dev deploy showed). A middleware-chain integration test locks the
whole path down against future wrappers missing Unwrap.

Validated on dev: 200s/512MB direct and 300s/768MB via CDN sustained
range-GETs (previously dying at 120s), zero duration_ms=120000 stream
entries since deploy.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Streaming responses now use rolling per-write deadlines through a new response-writer wrapper. Middleware exposes underlying writers, selected download, ebook, playback, and remux paths adopt the wrapper, and tests cover progress, stalled clients, fast paths, and middleware traversal.

Changes

Streaming deadline handling

Layer / File(s) Summary
Deadline design contract
docs/design/2026-07-09-streaming-write-deadline.md
Defines rolling deadline semantics, affected streaming paths, unchanged routes, tests, validation, and rollout.
Rolling deadline writer and tests
internal/httpstream/rolling_deadline.go, internal/httpstream/rolling_deadline_test.go
Adds configurable deadline rolling, ReadFrom support, flushing and unwrapping, with timeout and stalled-client regression tests.
Middleware traversal
internal/api/middleware/metrics.go, internal/api/middleware/request_logger.go, internal/api/middleware/stream_deadline_chain_test.go
Adds Unwrap methods and verifies streaming survives the production middleware chain.
Streaming handler integration
internal/api/handlers/downloads.go, internal/api/handlers/ebook_*.go, internal/api/handlers/playback.go, internal/playback/directplay.go, internal/playback/remux.go
Applies rolling deadline writers to file, ebook, playback proxy, direct-play, and remux streaming responses.

Estimated code review effort: 4 (Complex) | ~45 minutes

🚥 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 clearly summarizes the main fix: preventing healthy streaming responses from being cut off by the server WriteTimeout.
Docstring Coverage ✅ Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/streaming-write-deadline

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

@Quick104
Quick104 merged commit fb16058 into main Jul 10, 2026
1 check passed
@Quick104
Quick104 deleted the fix/streaming-write-deadline branch July 10, 2026 03:07

@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: 3

🤖 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/httpstream/rolling_deadline_test.go`:
- Around line 118-125: Update the test around the handlerDone select to record
the handler start time, then replace the fixed 30-second timeout with an
assertion that fails once the configured 1-second rolling deadline exceeds a
small tolerance such as 3 seconds. Preserve the existing non-nil error check and
use the elapsed time to verify the stalled client is reaped promptly.
- Around line 25-26: The tests for newRollingDeadlineWriter always use a zero
step and do not cover rate-limit suppression. Add a fake writer implementing
SetWriteDeadline, then verify the first deadline bump occurs, a subsequent bump
within a nonzero step is suppressed, and a later write after the step advances
bumps the deadline again; update the related test cases as well.
- Around line 128-137: Update TestReadFromPreservesCompletion so the slowReader
transfer exceeds readFromChunk (64 MiB) and takes longer than the configured
server timeout, while remaining practical for the test suite. Increase totalSize
and/or the per-read delay accordingly, ensuring the source requires multiple
ReadFrom slices and validates inter-slice deadline extension and successful
completion.
🪄 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: 9c44dbb4-e2cd-4db4-863d-5ef823b704a4

📥 Commits

Reviewing files that changed from the base of the PR and between c25ad81 and 54d75b9.

📒 Files selected for processing (12)
  • docs/design/2026-07-09-streaming-write-deadline.md
  • internal/api/handlers/downloads.go
  • internal/api/handlers/ebook_convert_serve.go
  • internal/api/handlers/ebook_reader.go
  • internal/api/handlers/playback.go
  • internal/api/middleware/metrics.go
  • internal/api/middleware/request_logger.go
  • internal/api/middleware/stream_deadline_chain_test.go
  • internal/httpstream/rolling_deadline.go
  • internal/httpstream/rolling_deadline_test.go
  • internal/playback/directplay.go
  • internal/playback/remux.go

Comment on lines +25 to +26
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newRollingDeadlineWriter(w, 2*time.Second, 0 /* bump every write */)

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

Cover the rate-limit branch.

Every wrapped test sets step to 0, so deadline bumps occur on every write. Add a fake writer with SetWriteDeadline and assert first bump, suppression within a nonzero step, and a later bump.

Also applies to: 91-91, 135-135

🤖 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/httpstream/rolling_deadline_test.go` around lines 25 - 26, The tests
for newRollingDeadlineWriter always use a zero step and do not cover rate-limit
suppression. Add a fake writer implementing SetWriteDeadline, then verify the
first deadline bump occurs, a subsequent bump within a nonzero step is
suppressed, and a later write after the step advances bumps the deadline again;
update the related test cases as well.

Comment on lines +118 to +125
select {
case err := <-handlerDone:
if err == nil {
t.Fatal("handler finished 256MB into a non-reading client without error")
}
case <-time.After(30 * time.Second):
t.Fatal("stalled client was never reaped by the rolling deadline")
}

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

Assert the configured stall bound.

This permits a 30-second completion for a 1-second window, so a materially delayed reap still passes. Record the handler start time and fail after a small tolerance (for example, 3 seconds).

🤖 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/httpstream/rolling_deadline_test.go` around lines 118 - 125, Update
the test around the handlerDone select to record the handler start time, then
replace the fixed 30-second timeout with an assertion that fails once the
configured 1-second rolling deadline exceeds a small tolerance such as 3
seconds. Preserve the existing non-nil error check and use the elapsed time to
verify the stalled client is reaped promptly.

Comment on lines +128 to +137
// TestReadFromPreservesCompletion exercises the io.ReaderFrom path used by
// http.ServeContent (sendfile) under a server WriteTimeout shorter than the
// transfer, with a source large enough to require multiple bounded slices.
func TestReadFromPreservesCompletion(t *testing.T) {
const totalSize = 8 << 20

srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newRollingDeadlineWriter(w, 2*time.Second, 0)
sw.WriteHeader(http.StatusOK)
src := &slowReader{r: io.LimitReader(neverEnding('x'), totalSize), delay: 200 * time.Microsecond}

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

Exercise multiple ReadFrom slices.

totalSize is 8 MiB, below readFromChunk (64 MiB), and the configured read delay only adds roughly 51 ms—below the 1-second server timeout. The test therefore cannot validate either inter-slice deadline bumps or timeout survival.

Proposed test adjustment
- const totalSize = 8 << 20
+ const totalSize = readFromChunk + 32<<10

- src := &slowReader{r: io.LimitReader(neverEnding('x'), totalSize), delay: 200 * time.Microsecond}
+ src := &slowReader{r: io.LimitReader(neverEnding('x'), totalSize), delay: time.Millisecond}
📝 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
// TestReadFromPreservesCompletion exercises the io.ReaderFrom path used by
// http.ServeContent (sendfile) under a server WriteTimeout shorter than the
// transfer, with a source large enough to require multiple bounded slices.
func TestReadFromPreservesCompletion(t *testing.T) {
const totalSize = 8 << 20
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newRollingDeadlineWriter(w, 2*time.Second, 0)
sw.WriteHeader(http.StatusOK)
src := &slowReader{r: io.LimitReader(neverEnding('x'), totalSize), delay: 200 * time.Microsecond}
// TestReadFromPreservesCompletion exercises the io.ReaderFrom path used by
// http.ServeContent (sendfile) under a server WriteTimeout shorter than the
// transfer, with a source large enough to require multiple bounded slices.
func TestReadFromPreservesCompletion(t *testing.T) {
const totalSize = readFromChunk + 32<<10
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newRollingDeadlineWriter(w, 2*time.Second, 0)
sw.WriteHeader(http.StatusOK)
src := &slowReader{r: io.LimitReader(neverEnding('x'), totalSize), delay: time.Millisecond}
🤖 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/httpstream/rolling_deadline_test.go` around lines 128 - 137, Update
TestReadFromPreservesCompletion so the slowReader transfer exceeds readFromChunk
(64 MiB) and takes longer than the configured server timeout, while remaining
practical for the test suite. Increase totalSize and/or the per-read delay
accordingly, ensuring the source requires multiple ReadFrom slices and validates
inter-slice deadline extension and successful completion.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54d75b9e51

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

var total int64
for {
s.bump()
n, err := rf.ReadFrom(io.LimitReader(r, readFromChunk))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Roll the deadline before a whole 64 MiB slice completes

For http.ServeContent/download responses that take the ReadFrom path, this only bumps the connection deadline before each 64 MiB transfer and then waits for that whole ReadFrom call to return. A healthy client or throttled download moving slower than about 64 MiB per 180 s (~3 Mbps with the default window) can spend longer than the stall window inside this single call, so the write deadline expires even though bytes are still flowing; low-bitrate audio/ebooks or slow WAN downloads can still be cut mid-stream. Use smaller bounded reads or otherwise refresh the deadline based on actual progress within the slice.

Useful? React with 👍 / 👎.

var total int64
for {
s.bump()
n, err := rf.ReadFrom(io.LimitReader(r, readFromChunk))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve sendfile when slicing ServeContent reads

When this writer is used under http.ServeContent, io.CopyN has already wrapped the file in an *io.LimitedReader; wrapping it in another io.LimitReader here means the underlying net/http sendfile path sees the inner limited reader instead of the original file and falls back to userspace copying. That defeats the stated zero-copy preservation for direct-play/download/ebook file responses under load; slice by reusing or adjusting the existing limiter rather than nesting another one.

Useful? React with 👍 / 👎.

Comment on lines +404 to +405
sw := httpstream.NewRollingDeadlineWriter(w)
if err := h.svc.ServeFile(r.Context(), sw, r, userID, profileID, deviceID, id, filter); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wrap the direct-download serving path as well

This only wraps /downloads/{id}/file, but the same handler still exposes GET/HEAD /direct-download in internal/api/router.go:2340 and HandleDirectDownload passes the original w into h.svc.ServeDirect, which reaches the same serveLocalFile/http.ServeContent path for full media files. Browser direct downloads of large media therefore remain subject to the 120 s server WriteTimeout; putting the rolling writer in the shared service serving path or wrapping both handlers would cover both download routes.

Useful? React with 👍 / 👎.

Quick104 added a commit that referenced this pull request Jul 10, 2026
…ut (#361)

The main API server's WriteTimeout (120s) is an absolute deadline from
request start, so every streaming response still being written at T+120s
was cut mid-body with a clean close. Clients saw multi-GB direct streams
truncate every two minutes; the Apple client's cursor-resume reconnect
absorbed most kills silently, but one landing during backpressure or a
demuxer resync exhausted its retry budget and forced a full player
teardown (visible stop + historical audio desync seeding).

Fix: internal/httpstream.RollingDeadlineWriter pushes the connection's
write deadline forward with progress via http.ResponseController — a
response that keeps moving lives indefinitely, a stalled one is still
reaped within the window (180s default, SILO_STREAM_WRITE_STALL_TIMEOUT
to override). ReadFrom delegates in bounded slices so http.ServeContent
keeps its sendfile fast path. Wired into direct play, remux, downloads,
the transcode-node proxy, and ebook serving; the server-level 120s guard
stays for every other route.

The metrics and request-logger response writers now implement Unwrap —
without it http.ResponseController cannot traverse to the connection and
SetWriteDeadline fails, silently disabling the fix (exactly what the
first dev deploy showed). A middleware-chain integration test locks the
whole path down against future wrappers missing Unwrap.

Validated on dev: 200s/512MB direct and 300s/768MB via CDN sustained
range-GETs (previously dying at 120s), zero duration_ms=120000 stream
entries since deploy.

Co-authored-by: Claude Fable 5 <[email protected]>
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.

1 participant