Skip to content

fix(playback): stop segment waits when the request ends - #2955

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:fix/segment-wait-on-disconnect
Oct 31, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:fix/segment-wait-on-disconnect

Conversation

@blurbery

@blurbery blurbery commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

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) is WaitForOpenSegment with ctx.Done() added to both of its selects. It returns ctx.Err() as soon as the request ends and leaves FFmpeg alone. WaitForOpenSegment stays as a wrapper that passes context.Background(), so its behaviour is unchanged. This follows WaitForManifestContext and fix(playback): stop transcode startup waits when the request ends #1499, which did the same for startup manifest waits.
  • The segment handlers on the native API, transcode nodes and jellycompat pass r.Context() to every segment wait.
  • RestartSegment returns ctx.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, because ResolveCopySeekAnchor watches the context; encoded restarts now do the same.
  • When the request context has ended, the handlers still answer with the 404 a timed-out wait gives. net/http also ends the context of an HTTP/1.1 client that only half-closed and is still reading, and writing nothing would reach that client as an empty 200 (the rule fix(apiv2): send the response to a client that half-closed its connection #2693 set for /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

  • Focused go test runs on internal/playback, internal/api/handlers, internal/transcodenode and internal/jellycompat for the segment waits, restarts and segment handlers: pass. CI runs the full gate.
  • internal/playback: a testing/synctest test cancels the request 50 ms into a 30 s wait, once while FFmpeg runs and once while it restarts, and requires context.Canceled at 50 ms.
  • internal/playback: a restart through TranscodeManager.RestartSegmentLocked for an ended request returns context.Canceled and 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.
  • Half-closed client, scratch test not in this PR: a raw TCP client sends the segment GET and calls CloseWrite while FFmpeg hasn't started. At a54a465 it got 200 OK with 0 bytes; at 9dd1ea8 it gets 404 Not Found after about 0.1 ms.
  • Full validation gate: not run locally. CI passed on 9dd1ea8 (ci / CI result).

Benchmarks

Measured end to end with a scratch test that is not part of this PR. It starts an httptest server running HandleGetTranscodeSegment for a running transcode with a stub FFmpeg that never writes output, so every request for seg_00000.ts waits 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.

  • Commits: parent db95c13 and this branch (a54a465), each built once with go test -c. The parent build used the parent's transcode.go, playback.go, server.go and streams.go. The branch binary was built before the restart error-log condition was narrowed, a line this measurement never reaches.
  • Environment: macOS on Apple M5 Pro, Go 1.27.1. Three runs each.
Handlers still running 1 s after the clients left Handler return after the clients left (min / median / max) Goroutines 1 s after
Before, run 1 50 of 50 11.797 s / 11.798 s / 11.798 s 56
Before, run 2 50 of 50 11.799 s / 11.800 s / 11.800 s 56
Before, run 3 50 of 50 11.796 s / 11.797 s / 11.797 s 56
After, run 1 0 of 50 0 ms / 0 ms / 1 ms 6
After, run 2 0 of 50 0 ms / 0 ms / 1 ms 6
After, run 3 0 of 50 0 ms / 1 ms / 1 ms 6

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 local httptest harness with a stub FFmpeg that never writes output, so seg_00000.ts waits on FFmpeg's startup. The same GET .../segment/seg_00000.ts request is cancelled 50 ms into the wait, on the parent commit db95c13 and on this branch's head 9dd1ea8:

Before (db95c13bd): handler returned after 12.002s; response written: 404 {"error":"not_found","message":"Segment not found"}
After (9dd1ea8f9):  handler returned after 52ms; response written: 404 {"error":"not_found","message":"Segment not found"}

The same route over a real TCP connection from a client that sends the GET and then half-closes its side (CloseWrite) while it keeps reading, so net/http ends the request context:

Before (19f59ef6f, this PR's base):  404 Not Found after 12.004s, 52 body bytes {"error":"not_found","message":"Segment not found"}
81e986189 (before the review fix):   200 OK after 1ms, 0 body bytes
After (9dd1ea8f9):                   404 Not Found after 1ms, 52 body bytes {"error":"not_found","message":"Segment not found"}

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/v1 contract, /api/v2 and jellycompat answer connected clients exactly as before, and silo-apple and silo-android need no change.

  • If a player retries a segment while its first request is still queued behind another restart, the first request no longer restarts FFmpeg when it gets the lock. The retry may then wait one more cycle before it restarts FFmpeg itself. Copy-mode sessions already behaved this way.
  • Abandoned requests get their 404 at once instead of after the wait. The activity log records it as 404, as before.
  • A client that half-closes its side after each request also arrives with an ended context, so a restart its segment needs would be skipped on every retry. Browsers, AVPlayer and ExoPlayer don't half-close; this is left as a maintainer decision on the review thread.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5; claude-sonnet-5-5 for one read-only code search
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: a separate agent, given only the diff, reviewed it for connected-client parity, every call site, what can cancel a request context, the restart lock, the node, API and jellycompat paths, and conflicts with open PRs. It found that skipping the restart error log after a client left also hid real restart failures; the log now skips only the request's own cancellation. It also raised the feat(playback): restart keyframe-planned copy streams mid-stream #1770 interaction and the queued-retry case, both described above.

Note

Stop segment waits when their HTTP request ends

  • Adds 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 timeout
  • playback.TranscodeSession.RestartSegment now returns early with the context error when already canceled, without starting FFmpeg
  • Updates segment handlers in playback.go, streams.go, and server.go to pass the HTTP request context to the new waits
  • Behavioral Change: when the request context ends, the handlers return the existing segment-not-found (404) response and no longer log a context-canceled restart as a restart failure

Macroscope summarized 9dd1ea8.

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@silo-kody

silo-kody Bot commented Oct 23, 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 ❌

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 511b4dda-b79f-4a4f-968a-f3211acf0dbd
📥 Commits

Reviewing files that changed from the base of the PR and between 4096b8d and 9dd1ea8.

📒 Files selected for processing: 7
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_test.go
  • internal/jellycompat/streams.go
  • internal/playback/restart_locked_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_manifest_test.go
  • internal/transcodenode/server.go
  • Autofix · 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 23, 2026

Copy link
Copy Markdown

The queued-seek recovery path can change playback timing: an abandoned request no longer restarts FFmpeg at the stale position before the newer seek (internal/playback/transcode.go). The Evidence section says there is no user-visible change; add a before-and-after recording of the same seek sequence on the affected playback surface, including the build or commit, to show this timing difference.

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

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@blurbery

Copy link
Copy Markdown
Contributor Author

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 Quick104 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.

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.

Comment thread internal/api/handlers/playback.go Resolved
// 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 {

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

blurbery and others added 2 commits October 23, 2026 15:04
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]>
@Quick104
Quick104 force-pushed the fix/segment-wait-on-disconnect branch from a54a465 to 9dd1ea8 Compare October 23, 2026 19:06
@silo-kody

silo-kody Bot commented Oct 23, 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

Copy link
Copy Markdown
Contributor

Review summary

Reviewed 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

  • A half-closed client got an empty 200 for a segment (inline thread, fixed in 9dd1ea8). net/http ends the request context of an HTTP/1.1 client that only half-closed and is still reading, so returning without writing reached that client as 200 OK with no body. All three handlers now answer with the 404 a timed-out wait gives. The wait still stops at once. TestGetTranscodeSegment_StopsWaitingWhenRequestEnds now expects the 404.

Left for the maintainers

  • Maintainer decision: the restart skip also applies to a half-closed client (inline thread on RestartSegment). A client that half-closes after every request would have each restart skipped, so its seeks beyond the produced window would never land. I don't know of an HLS player that does this. I left the skip as written. The alternative is to make the lifecycle lock wait context-aware and keep the restart unconditional once the lock is held, which would also free the goroutines queued behind a restart.

Verification

  • New tests, run with fails-on-base: the handler test and TestRestartSegmentLocked_SkipsRequestThatEnded fail on the base (a 12 s wait; FFmpeg restarted for an ended request) and pass on the head. The synctest wait test calls the new method, so it doesn't build on the base.
  • A scratch half-close test (not committed) sends the segment GET and then CloseWrite. At a54a465 it got 200 OK with 0 bytes. At 9dd1ea8 it gets 404 Not Found straight away. On the base it waited 12 s for the 404.
  • Focused tests pass in internal/playback, internal/api/handlers, internal/transcodenode, internal/jellycompat and internal/transcodeproxy. lint-changed, the size ratchet, the bidi check and the local-path check pass after the rebase.
  • A cross-provider review (Codex gpt-6.1-sol, one round) found no defects. It checked the API-to-node relay, including the hung-node failover from fix(playback): move a transcode off a node that hangs #2579, and found that it doesn't cancel a node request while the player still waits.

Validated features

No 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

  • Overlap with perf(playback): stop at the newest segment when reading transcode progress #2954: both PRs touch internal/playback/transcode.go and transcode_manifest_test.go, in different functions. A three-way merge of the two branches has no conflicts, so they can merge in either order.
  • jellycompat gets the same change as the native API.
  • Apple and Android need no change. The server answers connected clients as before, and a client that left never sees the response.
  • User manual: unaffected. No setting, default or described behavior changes.

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 WaitForManifestContext pattern. Readiness: tests that fail on the base back the fix. What keeps it below 9 is the open decision on the restart skip for half-closed clients.

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

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 (internal/api/handlers/playback.go, internal/jellycompat/streams.go, and the transcode-node relay path in internal/transcodenode/server.go). The Evidence section's after excerpt says no response and identifies a54a46558; at the current head, 9dd1ea8, ended contexts are mapped to ErrSegmentNotFound and a 404 is written. Please replace the stale after excerpt with before-and-after results for the same half-closed request, showing the response and elapsed time on the affected client-facing surface(s), and naming the baseline and current commits.

Suggested fix: No code diff; update the Evidence section to show the final behavior from 9dd1ea8 and compare it with the baseline.

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

Posted via Macroscope — Visible change evidence

@blurbery

Copy link
Copy Markdown
Contributor Author

@macroscopeapp The Evidence section now shows the final behaviour at 9dd1ea8 next to the base and 81e9861: a client that half-closes gets the 404 straight away instead of after the 12 s wait.

@Quick104
Quick104 merged commit 87d35eb into Silo-Server:main Oct 31, 2026
20 checks passed
@blurbery
blurbery deleted the fix/segment-wait-on-disconnect branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants