Repository navigation
fix(streaming): stop killing healthy streams at the server WriteTimeout - #361
Conversation
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]>
📝 WalkthroughWalkthroughStreaming 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. ChangesStreaming deadline handling
Estimated code review effort: 4 (Complex) | ~45 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (12)
docs/design/2026-07-09-streaming-write-deadline.mdinternal/api/handlers/downloads.gointernal/api/handlers/ebook_convert_serve.gointernal/api/handlers/ebook_reader.gointernal/api/handlers/playback.gointernal/api/middleware/metrics.gointernal/api/middleware/request_logger.gointernal/api/middleware/stream_deadline_chain_test.gointernal/httpstream/rolling_deadline.gointernal/httpstream/rolling_deadline_test.gointernal/playback/directplay.gointernal/playback/remux.go
| srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| sw := newRollingDeadlineWriter(w, 2*time.Second, 0 /* bump every write */) |
There was a problem hiding this comment.
🎯 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.
| 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") | ||
| } |
There was a problem hiding this comment.
🎯 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.
| // 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} |
There was a problem hiding this comment.
🎯 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.
| // 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.
There was a problem hiding this comment.
💡 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)) |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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 👍 / 👎.
| sw := httpstream.NewRollingDeadlineWriter(w) | ||
| if err := h.svc.ServeFile(r.Context(), sw, r, userID, profileID, deviceID, id, filter); err != nil { |
There was a problem hiding this comment.
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 👍 / 👎.
…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]>
Problem
cmd/silo/main.gosetsWriteTimeout: 120son the main API server. Go'sWriteTimeoutis 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 withduration_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 setWriteTimeout: 0for 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:http.ResponseController.SetWriteDeadline(semantics: "must make progress every 180s" instead of "must finish in 120s"). Window overridable viaSILO_STREAM_WRITE_STALL_TIMEOUT.WriteTimeout: 0.ReadFromdelegates in bounded slices sohttp.ServeContentkeeps itssendfilefast path for direct play.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
statusWriterand request-loggerrequestStatusWriterdidn't implementUnwrap, sohttp.ResponseControllercouldn't traverse to the connection and the wrapper silently self-disabled (the first dev deploy proved this the hard way). Both now implementUnwrap, 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;ReadFrompath completes past WriteTimeout.internal/api/middleware: chain-integration guard test../internal/playbackand./internal/api/handlerssuites pass.Validation on dev
duration_ms=120000stream entries since deploy.docs/design/2026-07-09-streaming-write-deadline.md.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests