You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(playback): serialize transcode session shutdown with restarts - #2524
Related issue: N/A
Validation tasks: none
Other clients: N/A (no client-visible change)
Closing a transcode session could leave FFmpeg running. If a seek or segment-recovery restart was in progress when the session closed, for example during API or transcode-node shutdown, the close stopped the old FFmpeg while the restart started a new one and recorded it on the session after the close finished. The session was gone but its FFmpeg kept running, and the restart hook could re-arm the throttler on it.
The close read the session's cancel function and done channel without the session lock and without waiting for the restart, which is also a data race the race detector reports on main.
Approach
TranscodeSession gets a terminal closing state. Close and CloseProcess set it, wait for a restart in flight, and only then read which FFmpeg to stop. A restart that begins after that is refused with an error that wraps ErrSessionSuperseded, which callers already handle. One already in flight stops before it cleans output or starts FFmpeg, or, if the close began while FFmpeg was starting, kills the FFmpeg it started instead of recording it. A closing session does not start a throttler.
Shutdown does not take the per-session lifecycle lock. A restart holds that lock through its restart hook, and the hook can block on the FFmpeg context that only Close cancels, such as the throttler's settings read during a database stall. Close already waits for a restart in flight, and shutdown removes the session from the map first, so no new restart starts.
Affects internal/playback and internal/transcodenode only; no API, client or Jellyfin-compatible change.
Validation
The race is proven by deterministic tests and the race detector, not by a live reproduction.
New tests pause a restart at a fixed point with a test log sink and a marker throttler, then close the session (no sleeps). They cover a close during a restart, a restart after close, and a restart hook arming the throttler after close. All fail on main and pass with the fix, including with -race -count=3.
TestStartShutdownCleanup_DoesNotWaitForARestartHook blocks a restart hook on its FFmpeg context. Shutdown cleanup hangs on an earlier head of this branch that took the lifecycle lock, and finishes with the fix.
With the race detector on, an unsynchronized close during a restart reports a data race on cancel and done on main, and none with the fix.
go test -race ./internal/transcodenode/... passes. In ./internal/playback/..., TestPrepareSubtitleFilterInputStagesTextTrack and TestCopyRemuxSubtitleRenditionRealFFmpeg fail locally with FFmpeg 9.0.1; the first fails the same way on main.
The race did not reproduce live. On a dev sandbox with a transcode node, built from main, a forced Jellyfin-compatible HLS transcode on the node was made to restart with a far-segment seek while the node was shut down 0 to 50 ms around the restart. No FFmpeg outlived shutdown. The window is a few milliseconds: once Close removes the output directory, a racing restart fails on chdir, so FFmpeg only leaks if it starts before that. CloseProcess keeps the directory, so it has no such guard.
Closing a session now waits for a restart in progress on it, usually for the restart's tone-map validation (a 20-second budget) and the old FFmpeg's exit. The source stat and hash reads in that validation ignore the budget, so a storage stall during a tone-map restart can hold the close until the storage answers. A restart refused during close is reported as superseded, the same result as restarting a session that was already removed.
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 (T3 Code)
Tool(s): Claude Code subagents; OpenAI Codex via T3 delegated tasks
Involvement: Fully AI-generated; human verification pending
Adversarial review: gpt-6.1-sol found the race while reviewing the transcode-node work in the stacked thin-node PRs and reproduced it with a controlled interleaving three times; claude-opus-5-5 confirmed the lock ordering. This PR ports only the fix to main, and its tests fail on main without it.
Fix TranscodeSession shutdown races with in-flight restarts
shutdown now marks the session as closing under the mutex, waits for any in-flight restart, then cancels and waits for the current generation in transcode.go
restart refuses to run once closing has begun, returning errSessionClosing (matching ErrSessionSuperseded). If FFmpeg already started, it is canceled and reaped rather than published
StartThrottler skips arming a throttler after shutdown begins
Shutdown cleanup in transcode_manager.go closes sessions without the lifecycle lock, so a blocked restart hook cannot stall cleanup
Behavioral Change: restarts and throttler starts racing a Close/CloseProcess now return ErrSessionSuperseded instead of possibly leaving a live generation; covered by new tests in transcode_close_test.go
The change marks transcode sessions as closing during shutdown, coordinates closure with in-flight restarts, and serializes manager and node shutdown with per-session lifecycle operations. Tests cover restart races and shutdown lock behavior.
Changes: Transcode lifecycle shutdown
Layer / File(s)
Summary
Coordinate session closure with restarts internal/playback/transcode.go, internal/playback/transcode_close_test.go
Shutdown marks a session as closing, waits for an in-flight restart, and cancels the current process. Restarts are rejected after closure begins, and a replacement process started during closure is canceled and reaped. Tests cover closure during and after restart, including throttler startup.
Serialize shutdown callers with lifecycle operations internal/playback/transcode_manager.go, internal/playback/transcode_manager_test.go, internal/transcodenode/server.go, internal/transcodenode/server_test.go
Manager cleanup and node shutdown hold the session lifecycle lock while closing sessions. Tests verify that shutdown waits for the lock before removing the session output directory.
sequenceDiagram
participant Shutdown
participant TranscodeSession
participant Restart
participant FFmpeg
Shutdown->>TranscodeSession: Mark closing and wait for restart
Restart->>FFmpeg: Start process
FFmpeg-->>Restart: Process started
Restart->>FFmpeg: Cancel if session is closing
Shutdown->>FFmpeg: Cancel current generation
Loading
Suggested labels:impact: playback
Suggested reviewers:coffeeknyte
Merge Risk: Low · up to 0e262
Shutdown may take longer while it starts and then stops an unnecessary replacement process. This is a bounded concern that can be addressed before merge or accepted as follow-up work.
Security architecture risk: Low · up to 0e262
The change strengthens shutdown cleanup without changing access permissions. No introduced security weakness was identified. Shutdown now waits for active work, but its behavior under production shutdown deadlines has not been established.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
inferred — The changed control concerns session-keyed process and output ownership on the executing transcode node. No expansion of request authority or independently addressable session scope was identified. Tenant isolation and host-level process privileges were not established by the available evidence.
Trust Boundaries and Controls
observed — Existing manifest and segment routes remain bearer-protected. Their session-denial checks and request-to-recovery path are unchanged. Reconstruction rechecks shutdown admission before spawning, while restart helpers reject stale session pointers.
Resilience and Maintainability Implications
observed — Shutdown waits for restart completion and process reaping without holding the session mutex needed by cleanup. This preserves process-generation ownership before output removal, but also makes completion dependent on in-flight work finishing; the restart validation budget is not a demonstrated bound on total shutdown duration.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title clearly and concisely identifies the main change: serializing transcode session shutdown with restarts.
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description is specific to the changeset. It explains the race where Close and CloseProcess stop FFmpeg while a restart starts a new one. It names the closing state, the ErrSessionSuperseded handl…
Full details: Description check
Explanation
The description is specific to the changeset. It explains the race where Close and CloseProcess stop FFmpeg while a restart starts a new one. It names the closing state, the ErrSessionSuperseded handling, the throttler change, the shutdown lock-ordering decision, and the tests that cover them. It also gives validation and risk notes.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
silo-triageBot
added
bug
Something isn't working
go
Pull requests that update go code
priority: P2
Limited scope, workaround exists, or polish
triaged
High-confidence review completed; does not mean fixed, validated, or accepted for release.
labels
Oct 15, 2026
The reason will be displayed to describe this comment to others. Learn more.
Reviewed dd20eb69ab647e18602a85248c828e4495d74aff. One shutdown blocker found: manager cleanup waits for a lifecycle lock that a stalled restart hook can release only after Close cancels its process context. The inline finding includes the production path and controlled reproduction.
The supplied lifecycle tests pass under the race detector and fail on the merge base. The additional reproduction uses the production throttler helper with a settings read that honors context cancellation; it blocks on this head and passes with only the old manager file restored. No real database outage or live playback session was used.
The linked comments contain conditional stop, failover and recovery evidence, with build qualifications recorded in the review analysis. Those paths need rechecking; normal playback was not recertified here. Direct board enumeration was unavailable because the review credential lacks read:project.
Reviewed with Codex (gpt-6.1-sol) using independent xhigh review and verification passes.
Closing a transcode session read its cancel func and done channel
without regard to a restart in progress. A seek or segment recovery
that had already stopped the old FFmpeg could then start a new one and
publish it after the close had cancelled and waited on the old
generation. The close returned with FFmpeg running on a session that
was gone, and the restart hook could re-arm its throttler.
Closing now marks the session closing, waits for an in-flight restart
and only then reads the generation to stop. A restart that begins
after that is refused as superseded; one already in flight kills the
FFmpeg it started instead of publishing it. A closing session arms no
throttler. Server shutdown on the core and on transcode nodes closes
each session under its lifecycle lock, the same lock restarts hold.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The shutdown lock tests poll the lifecycle lock's reference count while
shutdown runs on another goroutine. Main's forbidigo rule now requires a
reasoned nolint on such polls.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check s.closing before the replacement process starts.
If shutdown begins while a restart runs, that restart still runs cleanStaleOutputForRestart, reserves the GPU device, and starts FFmpeg. The late check then stops the new process. The final state is correct, but shutdown spends this extra work before it can finish.
Add an early check after the old process has stopped and before the new generation is published:
Keep the late check after cmd.Start(). Closing can begin during that call.
Review info
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: 20760a96-bc9d-4eb9-ad4d-ea1c46cacb12
Commits
Reviewing files that changed from the base of the PR and between dd20eb6 and 0e26226.
Files selected for processing: 5
internal/playback/transcode.go
internal/playback/transcode_manager.go
internal/playback/transcode_manager_test.go
internal/transcodenode/server.go
internal/transcodenode/server_test.go
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
…hooks
Shutdown cleanup took each session's lifecycle lock before closing it. A
restart holds that lock through its restart hook, and the hook can block on
the FFmpeg context that only Close cancels, as the throttler's settings read
does when the database stalls, so shutdown never reached Close. Close already
waits for a restart in flight and the session is out of the map, so drop the
lock from both the API and transcode-node shutdown loops.
A restart that sees the session closing after it validated or stopped the
previous generation now stops there instead of cleaning output and starting an
FFmpeg it would kill.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
🤖 Claude Code (claude-opus-5-5)
I reproduced the defect on current main. With the race detector on, shutdown() reads s.cancel and s.done without s.mu while restart() writes them (transcode.go reads at 3334/3335/3342, writes at 3688/3735/3745). The PR's five new tests also fail on main for the reasons the description gives. The session-level closing flag fixes both.
Three findings. The existing thread on transcode_manager.go covers the first; the other two are inline below. I'm fixing all three in a commit on this branch, so nobody needs to change them by hand. The same push merges current main into the branch, which has changed transcode.go four times since this PR was rebased.
The defect is real on current main. shutdown() reads the session's cancel and done without s.mu while restart() writes them, and nothing stops a restart from publishing a new FFmpeg after Close. The race detector reports the race on main, and the PR's close tests fail there for the reasons the description gives. Nothing on main or in the other open PRs that touch transcode.go (#4057, #3496, #4054, #1770) already does this.
Changes from this review (commit 1642052286, which comes after a merge of current main):
Shutdown cleanup no longer takes the per-session lifecycle lock, on the API server or on the transcode node. A restart holds that lock through its restart hook, and the hook can block on the FFmpeg context that only Close cancels, so shutdown could hang. Close already waits for a restart in flight, and the session is out of the map, so the lock added nothing. TestStartShutdownCleanup_DoesNotWaitForARestartHook hangs on 0e26226 and passes now. The two tests that asserted the lock are removed.
restart() also checks closing before it cleans output or starts FFmpeg, so a restart caught mid-flight no longer starts and then kills an FFmpeg. This also covers CodeRabbit's nitpick.
Left for the maintainers to settle
Closing a session waits for a restart in flight. The tone-map source check in that restart does a stat and hash reads that ignore its 20-second budget, so a storage stall during a tone-map restart can hold the close, and shutdown with it, until the storage answers. The FFmpeg reading the same file is likely stuck in that case too. The PR's Risks section now says so. Making that check cancellable would be a separate change in internal/tonemap.
Segment requests that hit a restart refused during close get a 500 from the native and Jellyfin handlers, the same as an existing superseded restart. The transcode node returns 404.
Validated features: I couldn't read the board. From the Validation issues, the only passed cases this reaches are #1177 C3 and #1178 C2 (losing a worker). Only graceful node shutdown runs this code, and after this review's change it no longer waits on the lifecycle lock. Their results don't change. Validation tasks: none stands.
User manual: unaffected (internal teardown behavior, no settings or visible change). Other clients: N/A. No API or client-visible change; jellycompat uses the same TranscodeSession, so it gets the fix.
Verification: Go tests with -race, including the PR's close tests 3/3 on this head, internal/transcodenode passing, and the race and early-close probes described on the evidence page. Not reproduced live.
Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green)
Fit: it fixes a teardown race at the session boundary that owns it, with no new surface, and it matters most for the cluster case where nodes shut down mid-stream. Readiness: tests that fail on main back the fix, and the review fixes have their own failing-first test. It isn't 9 because of the storage-stall wait above, which a maintainer should accept or send to a follow-up, and because nobody has run it live.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codeimpact: playbackCan't play, stalls, or wrong mediapriority: P2Limited scope, workaround exists, or polishsize/L200–499 added + deleted lines (all files); change volume, not priority.triagedHigh-confidence review completed; does not mean fixed, validated, or accepted for release.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: none
Other clients: N/A (no client-visible change)
Closing a transcode session could leave FFmpeg running. If a seek or segment-recovery restart was in progress when the session closed, for example during API or transcode-node shutdown, the close stopped the old FFmpeg while the restart started a new one and recorded it on the session after the close finished. The session was gone but its FFmpeg kept running, and the restart hook could re-arm the throttler on it.
The close read the session's cancel function and done channel without the session lock and without waiting for the restart, which is also a data race the race detector reports on main.
Approach
TranscodeSessiongets a terminal closing state.CloseandCloseProcessset it, wait for a restart in flight, and only then read which FFmpeg to stop. A restart that begins after that is refused with an error that wrapsErrSessionSuperseded, which callers already handle. One already in flight stops before it cleans output or starts FFmpeg, or, if the close began while FFmpeg was starting, kills the FFmpeg it started instead of recording it. A closing session does not start a throttler.Shutdown does not take the per-session lifecycle lock. A restart holds that lock through its restart hook, and the hook can block on the FFmpeg context that only
Closecancels, such as the throttler's settings read during a database stall.Closealready waits for a restart in flight, and shutdown removes the session from the map first, so no new restart starts.Affects
internal/playbackandinternal/transcodenodeonly; no API, client or Jellyfin-compatible change.Validation
The race is proven by deterministic tests and the race detector, not by a live reproduction.
-race -count=3.TestStartShutdownCleanup_DoesNotWaitForARestartHookblocks a restart hook on its FFmpeg context. Shutdown cleanup hangs on an earlier head of this branch that took the lifecycle lock, and finishes with the fix.cancelanddoneon main, and none with the fix.go test -race ./internal/transcodenode/...passes. In./internal/playback/...,TestPrepareSubtitleFilterInputStagesTextTrackandTestCopyRemuxSubtitleRenditionRealFFmpegfail locally with FFmpeg 9.0.1; the first fails the same way on main.Closeremoves the output directory, a racing restart fails onchdir, so FFmpeg only leaks if it starts before that.CloseProcesskeeps the directory, so it has no such guard.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-2524/
Risks
Closing a session now waits for a restart in progress on it, usually for the restart's tone-map validation (a 20-second budget) and the old FFmpeg's exit. The source
statand hash reads in that validation ignore the budget, so a storage stall during a tone-map restart can hold the close until the storage answers. A restart refused during close is reported as superseded, the same result as restarting a session that was already removed.Checklist
AI Disclosure
🤖 Generated with Claude Code
Note
Fix
TranscodeSessionshutdown races with in-flight restartsshutdownnow marks the session as closing under the mutex, waits for any in-flight restart, then cancels and waits for the current generation in transcode.gorestartrefuses to run once closing has begun, returningerrSessionClosing(matchingErrSessionSuperseded). If FFmpeg already started, it is canceled and reaped rather than publishedStartThrottlerskips arming a throttler after shutdown beginsClose/CloseProcessnow returnErrSessionSupersededinstead of possibly leaving a live generation; covered by new tests in transcode_close_test.goMacroscope summarized 1642052.