Repository navigation
fix(playback): stop segment waits when the request ends - #2955
Conversation
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 41 minutes. View limit details
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 |
|
The queued-seek recovery path can change playback timing: an abandoned request no longer restarts FFmpeg at the stale position before the newer seek ( Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
|
Fair point on the queued-seek timing. I've changed the Evidence section to say that's the one effect a user could notice and that I have no recording of it. A connected player gets the same responses as before. The server-side effect is covered by the restart test (an ended request no longer starts FFmpeg) and the end-to-end measurement in Benchmarks (abandoned handlers return within 1 ms instead of running on for about 12 s). |
Quick104
left a comment
There was a problem hiding this comment.
Review of a54a465. The change is small and does what it says: the context-aware wait follows WaitForManifestContext, every caller of RestartSegment passes the request context, and the wait never decided a restart on main, so ending it early skips nothing. I found one defect, which I'm fixing in a commit on this branch, and one trade-off for the maintainers. Details are inline.
| // player that seeks again abandons it. Restarting for it would move FFmpeg | ||
| // to a position nobody wants and delay the restart the player now waits | ||
| // on. Once started, a restart runs to completion (see restart). | ||
| if err := ctx.Err(); err != nil { |
There was a problem hiding this comment.
Maintainer decision: the restart skip also applies to a half-closed client. For the same net/http reason, a client that half-closes after each request reaches RestartSegment with a context that has already ended. When its segment needs a restart (a seek beyond the produced window, a stale or exited FFmpeg), the restart is skipped on that request and on every retry, so that client's seek never lands. On main the restart runs no matter what. I don't know of an HLS player that half-closes. Browsers, AVPlayer and ExoPlayer don't, so I've left this as written and raised it with the maintainers rather than asking you to change it. Making the lifecycle lock wait itself context-aware would be an alternative that also frees the goroutines queued behind a restart, but that's a larger change than this PR needs.
There was a problem hiding this comment.
I agree with leaving it as written. I don't know of an HLS player that half-closes either, and making the lifecycle lock wait context-aware is a bigger change than this PR needs. If you'd like the goroutines queued behind a restart freed as well, I'm happy to do that as a follow-up.
The segment handlers waited up to 12 or 30 seconds for FFmpeg to write a missing segment even after the client had gone, polling every 100 ms and then writing a 404 to a closed connection. hls.js aborts in-flight segment loads on every seek and quality switch, so scrubbing left a burst of these waits behind, on the API server and on transcode nodes behind a relay. WaitForOpenSegmentContext ends the wait with the request context, and the native API, transcode node and jellycompat segment handlers pass r.Context() to every segment wait. When the request has ended they return without writing a response, as the manifest path does. RestartSegment also returns before starting a restart for a request that has already ended. Its callers hold the per-session lifecycle lock, so a request abandoned while it waited behind another restart no longer moves FFmpeg to a position nobody wants. A restart that has started still runs to completion.
net/http ends the request context of an HTTP/1.1 client that only half-closed its side and is still reading. The segment handlers returned without writing in that case, which reaches such a client as an empty 200. Answer 404, as a timed-out wait does; a client that has left drops the write. The wait still stops as soon as the context ends. Co-Authored-By: Claude Opus 5.5 <[email protected]>
a54a465 to
9dd1ea8
Compare
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Review summaryReviewed head: 9dd1ea8 (a54a465 plus one review fix; the branch was rebased onto current main and force-pushed with a lease). The change is sound and small. Segment waits on the native API, jellycompat and transcode nodes now end with the request. An ended request queued on the lifecycle lock no longer restarts FFmpeg at a position nobody wants. A connected client gets the same answers as before. Addressed
Left for the maintainers
Verification
Validated featuresNo passed case on the v1.0.0 board reaches this change. The cases the body names, #1149 C2 and #1148 C3, are not run yet. Validation tasks: none. Other checks
Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green) Fit: the PR stops a server from spending polling and FFmpeg restarts on requests that players abandon during seeks and quality switches. That matters most on small hosts and busy clusters. It adds no settings or API surface, and it follows the existing |
|
A half-closed HTTP/1.1 segment request can now receive a 404 as soon as its wait ends, instead of waiting for the timeout ( Suggested fix: No code diff; update the Evidence section to show the final behavior from Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
Problem
Related issue: N/A
Validation tasks: none passed yet. This reaches the seek paths of #1149 C2 and #1148 C3, both not run.
When a player gives up on a segment request, Silo keeps working on it. The segment handlers wait for FFmpeg to write a missing segment for up to 12 seconds, or 30 seconds for a keyframe-planned copy stream or after a seek restart. The wait (
TranscodeSession.WaitForOpenSegment) took no context. It polled every 100 ms until the timeout even after the client had gone, then wrote a 404 or 500 to a closed connection.hls.js aborts in-flight segment loads on every seek and quality switch, so scrubbing through a transcode leaves a burst of these waits behind. With a transcode node, the API cancels its relay request when the client leaves, but the node's handler kept waiting as well.
A second cost sits behind the per-session lifecycle lock. Segment restarts for one session run one at a time, and a request waiting for that lock does not notice its client leaving. When the user seeks again, the abandoned request still gets the lock in turn, kills FFmpeg and restarts it at a position nobody wants, and the restart for the newest seek waits behind it.
This change ends segment waits with the request, and does not start a restart for a request that has already ended.
Approach
WaitForOpenSegmentContext(ctx, name, timeout)isWaitForOpenSegmentwithctx.Done()added to both of its selects. It returnsctx.Err()as soon as the request ends and leaves FFmpeg alone.WaitForOpenSegmentstays as a wrapper that passescontext.Background(), so its behaviour is unchanged. This followsWaitForManifestContextand fix(playback): stop transcode startup waits when the request ends #1499, which did the same for startup manifest waits.r.Context()to every segment wait.RestartSegmentreturnsctx.Err()before it resolves or starts a restart when the request has already ended. Callers hold the lifecycle lock around it, so the check runs after the wait for the lock. A restart that has started still runs to completion, detached from the request as before. Copy-mode restarts already stopped for an ended request, becauseResolveCopySeekAnchorwatches the context; encoded restarts now do the same./api/v2). A client that has gone drops the write. A restart skipped for that reason is not logged as an error, but every other restart failure still is.The 100 ms poll interval is unchanged. #2541 changes it in the same functions, and the two merge cleanly.
On main, every recovery decision that waits sets
RestartOnTimeout=false, so ending a wait early never skips a restart. #1770 adds a planned-stream decision that waits 12 s and then restarts. With this change that restart happens only if the requester stays for the whole wait. The web player does, since it allows 45 s per segment load, unless the user seeks or switches quality first.Validation
go testruns oninternal/playback,internal/api/handlers,internal/transcodenodeandinternal/jellycompatfor the segment waits, restarts and segment handlers: pass. CI runs the full gate.internal/playback: atesting/synctesttest cancels the request 50 ms into a 30 s wait, once while FFmpeg runs and once while it restarts, and requirescontext.Canceledat 50 ms.internal/playback: a restart throughTranscodeManager.RestartSegmentLockedfor an ended request returnscontext.Canceledand leaves FFmpeg unstarted. On the parent commit it starts FFmpeg.internal/api/handlers: a segment request that has ended while its segment would wait for FFmpeg's startup answers 404 at once. On main it waits 12 s first; without the half-close fix it wrote nothing (status = 200 ""). The node and jellycompat handlers get the same change and no test of their own.GETand callsCloseWritewhile FFmpeg hasn't started. At a54a465 it got200 OKwith 0 bytes; at 9dd1ea8 it gets404 Not Foundafter about 0.1 ms.ci / CI result).Benchmarks
Measured end to end with a scratch test that is not part of this PR. It starts an
httptestserver runningHandleGetTranscodeSegmentfor a running transcode with a stub FFmpeg that never writes output, so every request forseg_00000.tswaits on FFmpeg's startup (12 s). 50 clients connect. Once all 50 handlers are inside the wait, the test waits another 200 ms, then cancels every client request. It records when each handler returns and how many are still running a second later.go test -c. The parent build used the parent'stranscode.go,playback.go,server.goandstreams.go. The branch binary was built before the restart error-log condition was narrowed, a line this measurement never reaches.Before the change, each abandoned handler kept polling until its 12 s wait expired, then wrote a 404 to the closed connection. The 30 s waits behave the same way, for longer. Limitations: this is a local loopback server, not a transcode node behind the API relay, a real FFmpeg or a real player. The restart change is covered by the restart test above, not by this measurement.
Evidence
Surface: native API segment route (
HandleGetTranscodeSegment), run in a localhttptestharness with a stub FFmpeg that never writes output, soseg_00000.tswaits on FFmpeg's startup. The sameGET .../segment/seg_00000.tsrequest is cancelled 50 ms into the wait, on the parent commit db95c13 and on this branch's head 9dd1ea8:The same route over a real TCP connection from a client that sends the
GETand then half-closes its side (CloseWrite) while it keeps reading, so net/http ends the request context:A player that is still connected gets the same responses as before. The one effect a user could notice is timing: after several quick seeks on an encoded transcode, the last seek's restart no longer waits behind restarts for requests the player already abandoned. I have no recording of that; the restart test and the measurement above show the server side.
Risks
Low. Nothing changes for a request whose client is still connected, so the frozen
/api/v1contract,/api/v2and jellycompat answer connected clients exactly as before, andsilo-appleandsilo-androidneed no change.Checklist
AI Disclosure
Note
Stop segment waits when their HTTP request ends
playback.TranscodeSession.WaitForOpenSegmentContext, which selects on the caller context during running and restarting waits and returns the context error instead of waiting for the 30-second timeoutplayback.TranscodeSession.RestartSegmentnow returns early with the context error when already canceled, without starting FFmpegMacroscope summarized 9dd1ea8.