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(jellycompat): replace the upstream session when a play switches version - #4572
Closes#750
Related issue: N/A
Validation tasks: none passed that this reaches; it touches #1246 C1 and #1206 C1 (both not yet run)
Other clients: Apple N/A (no client-visible change; native clients use the native API); Android N/A (same); Roku N/A (same)
When a Jellyfin client plays one version of a movie or episode and then requests another version under the same play, Silo kept the first version's upstream session as long as the play method stayed the same. A play lists every version when PlaybackInfo is called without a MediaSourceId, or when a Static=true direct play starts without PlaybackInfo, and an ID-less direct play binds to the started play for that item. In those cases:
Direct play and remux streamed the second version's file under a session bound to the first. Now Playing, the admin playback log and watch progress recorded the wrong version.
HLS refused the second version's master playlist with 503 ("transcode recipe does not match the selected media source") and ended the play.
With this change a request for another version retires the old upstream session, the same way a play-method switch already does, and starts one for the requested file.
Approach
ensureUpstreamPlayback now reuses the play's upstream session only when it streams the requested file as well as the requested method. Otherwise it stops the old session, closes its transcode, drops its node recipe and records it as replaced. The compare-and-swap that attaches the new session adopts a concurrent winner only when the winner streams the same file. A play stored before its upstream file was recorded (file ID 0) keeps the old method-only rule.
Only the requests that open a stream (progressive stream and HLS master playlist) may switch a play. Child playlists, segments and progress-report revives now use ensureBoundUpstreamPlayback, which reuses or rebuilds the current upstream but answers 409 instead of replacing it. A late playlist or report for the old version therefore can't switch the play back. Child requests and progressive requests that name no version (or name the item ID) follow the version the play streams instead of the first one listed. A request whose freshly attached session a concurrent switch replaced also answers 409 and stops its session. A switching request attributes its bytes to the new session, not the retired one.
The replaced end reason's descriptions (admin API doc, /api/v2 field description, generated OpenAPI and web types) now mention version switches. No contract shape changes.
Not addressed: when the old upstream's native session lives on another API replica, the switch still can't stop that replica's copy or its remote transcode until stale cleanup. That gap already existed for method switches. Reconstruction and remote-node adoption keep the file identity because they act only on an upstream that already streams the requested file.
Validation
Unit tests in internal/jellycompat: a same-method version switch for direct, remux and HLS transcode; concurrent starts of two versions (CAS loser and a replacement after attach); child playlist and revive requests that name a version or method the play left; a reaped upstream of the same version still resuming; the child-source default. Each fails on the code before the matching fix.
go build ./..., gofmt, go mod tidy -diff, go vet ./...: pass.
make lint-changed (golangci-lint v2.15.0) and make lint-router-recovery: 0 issues.
go test for internal/jellycompat, internal/playback, internal/apiv2, internal/api/handlers: pass.
DB contracts: every internal/jellycompat contract passes. Backup, S3 and AI-subtitle contracts skip here because this machine lacks their services; this change doesn't touch them.
Web lint/build/tests not run: the only web change is a regenerated description string in web/src/api/v2/schema.ts.
Evidence
Checked on a local build with a synthetic movie that has two versions (1080p and 720p H.264), using curl with Jellyfin client headers. The same steps ran on origin/main and on this branch, against the same database.
# Before (origin/main)
PlaybackInfo without MediaSourceId -> both versions under one PlaySessionId
GET /Videos/{id}/stream?static=true&mediaSourceId=<1080p>&PlaySessionId=P -> 206, bytes match the 1080p file
GET /Videos/{id}/stream?static=true&mediaSourceId=<720p>&PlaySessionId=P -> 206, bytes match the 720p file
native session after the 720p request: media_file_id=2 (1080p), same session id
admin playback history for that session: media_file_id=2, end_reason=stopped
Static=true direct play without PlaybackInfo or PlaySessionId, 1080p then 720p
native session after the 720p request: media_file_id=2 (1080p), same session id
HLS, both versions under one PlaySessionId
master.m3u8 1080p -> 200, segment 0 is 1920x1080
master.m3u8 720p -> 503, play ended
log: "compat transcode unavailable" error="transcode recipe does not match the selected media source"
# After (this branch)
direct play, same PlaySessionId: native session after the 720p request: new session id, media_file_id=1 (720p)
Static=true, no PlaySessionId: native session after the 720p request: new session id, media_file_id=1 (720p)
HLS: master.m3u8 720p -> 200, child playlist -> 200, segment 0 is 1280x720
HLS, then the 1080p child playlist again -> 503 "The child HLS request belongs to an obsolete playback route";
720p segment 1 -> 200, 1280x720, 720p session untouched
same version, three range requests under one PlaySessionId: one session throughout
Re-checked live after merging main (head 8f42d031b): direct play, Static=true and HLS version switches each start a new upstream session for the requested file, a late segment for the old version answers 503, and the retired session's history row keeps its own file with end_reason=replaced.
A client that requests two versions of one play at the same moment now gets a 409 on the request that loses, and retries. Before, it continued on the wrong file. Plays started before this build without a recorded upstream file keep the old behavior until they end.
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 how I checked a change nobody sees.
AI Disclosure
Harness: Claude Code (via T3 Code); Codex CLI for code review
Adversarial review: four rounds of dual-code-review (gpt-6.2-sol, gpt-6.2-astra, Claude Opus, Claude Fable), each on the newest changes. Round 1 found that a late child playlist or progress-report revive could switch the play back, that a replaced attach could serve under the other version's session, that a switching request's bytes went to the retired session, and that the replaced descriptions were stale; all fixed. Round 2 found races where a child playlist or revive passed its checks before a concurrent switch, and a leaked session after a replaced attach; fixed with the bound entry point. Round 3 found that the master manifest's second upstream check could undo a newer switch; fixed, with test gaps closed. Round 4 found no correctness issues. Left open: the cross-replica stop gap described above, and a stale report's position applied to a revived session (the next report corrects it).
Note
Replace upstream session when a play switches media version
The compat upstream router now tracks which media file each play's upstream session streams. An upstream is reused only when both the play method and the bound media file match the request; otherwise the old session is retired (recorded with the replaced end reason) and a new one starts.
New ensureBoundUpstreamPlayback path serves requests that follow an already opened stream. It rejects requests naming a different method or file with an upstream-replaced error instead of switching the play (streams.go).
Child HLS and progressive requests without a media-source ID now select the version bound to the upstream file, instead of the first listed source. Revives also prefer the bound source.
The large ensureUpstream flow is split into helpers: reuseUpstream, reconstructUpstream, retireUpstream, and startCompatUpstream. Concurrent starts adopt a winner only when method and file both match.
Behavioral Change: bound requests (late playlists, stale revives, tone-mapped manifests) naming an old version now return service-unavailable or upstream-replaced errors instead of silently switching the play; the replaced end reason now also covers version switches in docs and schemas.
…ersion
A Jellyfin play kept its upstream session whenever the play method stayed
the same, even when the request named another version of the item. Direct
play and remux then streamed the new file under a session bound to the old
one, so Now Playing and history showed the wrong version, and an HLS
request for the other version was refused and ended the play.
Reuse the upstream session, and adopt a concurrent winner, only when it
streams the requested file; otherwise retire it like a method switch.
…buted
A version switch is now made only by the master manifest or a progressive
stream request. A late child playlist or segment for the old version is
refused instead of retiring the version being watched, and one without a
MediaSourceId follows the version the play streams. A progress report that
revives a reaped upstream restores the bound version rather than the one a
stale report names. A request whose attached session a concurrent switch
replaced answers 409 instead of serving under the newer version's session,
and a switching request attributes its bytes to the new session.
The ensureUpstreamPlayback reuse and retire branches move into helpers.
Child HLS playlists and report revives now go through
ensureBoundUpstreamPlayback, which reuses or rebuilds the play's upstream
but answers errUpstreamReplaced instead of replacing it. A child playlist
or a revive that raced a switch can no longer switch the play back.
A request whose attached session a concurrent switch replaced also stops
that session, which a switch on another replica could not.
…tching back
The master manifest ensures the upstream twice: once to attach its version,
then again before starting the local transcode. Only the first may replace
the play's upstream now, so a master for an older version that a newer
switch overtook gets 409 instead of undoing the newer one.
Jellycompat playback routing now tracks the media file bound to an upstream session during reuse, replacement, and revival. Tests cover version switches and concurrent starts. Playback-history descriptions now include Jellyfin version switches as a reason for session replacement.
Jellycompat compares the requested media file with the file bound to the upstream session. It replaces mismatched sessions when allowed and rejects stale requests. Tests cover source switches, concurrent starts, and requests that must not replace the active session.
Bound-source routing and revival internal/jellycompat/streams.go, internal/jellycompat/playback_report_liveness_test.go, internal/jellycompat/routing_policy_test.go
Child HLS source selection and playback revival prefer the source bound to the play. Tests cover source selection and revival after the upstream session is absent.
sequenceDiagram
participant JellyfinClient
participant ensureUpstreamPlayback
participant NativePlaybackSession
JellyfinClient->>ensureUpstreamPlayback: Request playback method and media source
ensureUpstreamPlayback->>NativePlaybackSession: Start replacement session when source or method differs
NativePlaybackSession-->>ensureUpstreamPlayback: Return started session
ensureUpstreamPlayback-->>JellyfinClient: Return errUpstreamReplaced when request is stale
Loading
Possibly related PRs
Silo-Server/silo-server#3191: Adds the replaced end reason for play-method switches. This PR extends the same end-reason descriptions to version switches.
Suggested labels:go, api-v2
Suggested reviewers:quick104, blurbery
Merge Risk: Moderate · up to 8f42d
Jellyfin version switching now replaces the upstream session correctly. In rare concurrent switches, a late manifest failure can delete the newer version's play record. Switches across replicas can also leave an orphaned or still-running old transcode until stale cleanup reclaims it. These are narrow edge cases, but they should be fixed or explicitly accepted before merge.
Security architecture risk: Low · up to 8f42d
The change keeps playback tied to the selected version, but a failed version switch can leave the old session marked as ended while still allowing it to resume. The inspected paths limit this risk to the affected play; they do not show expanded access to another user’s playback.
Retained concerns
Low · reliability · inferred: A same-method version switch can retire the old upstream and finish it as replaced before the new session attaches. If the new start fails, the stored binding and recipe still name the old upstream. A request for the original version can reconstruct that ID after successful local retirement, even if node-recipe deletion succeeded. This extends the base method-switch failure mode to version switches and can leave live playback inconsistent with its recorded end state.
Security review details
Security Blast Radius
inferred — The new replacement reach is a different negotiated file on the same compatibility play. The inspected opening routes retain token-scoped play resolution and source selection, so the evidence supports a per-play lifecycle risk rather than expanded cross-owner access.
Trust Boundaries and Controls
observed — Reconstruction checks the recipe’s session ID and rejects a nonzero caller whose user ID differs from the recipe owner. Reconstructed sessions still pass per-user admission limits; those checks do not distinguish a missing session from one deliberately retired by a failed switch.
Hardening Proposals
proposed — Make retirement visible to reconstruction through the same stored binding used for attach. A failed or interrupted switch should either preserve the original session as active or durably mark it as retired, so recovery cannot reopen an ID already finished as replaced.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: a play that switches to another media version now replaces the upstream session. The jellycompat fix in streams.go and the related tests match this title.
Linked Issues check
Directly linked issue #750 has four coding requirements. (1) Media-file identity in every reuse and compare-and-swap decision: the whole-PR summary states that reuse requires both play method and sour…
Out of Scope Changes check
The whole-PR summary lists changes to internal/jellycompat (streams.go, routing and liveness tests), documentation (docs/admin-api.md), the replaced end-reason comments and descriptions (internal/play…
Description check
The description states the problem (a Jellyfin client requesting another version under the same play kept the first version's upstream session), the approach (reuse only when method and media file bot…
Full details: Linked Issues check
Explanation
Directly linked issue #750 has four coding requirements. (1) Media-file identity in every reuse and compare-and-swap decision: the whole-PR summary states that reuse requires both play method and source file to match, and that CAS adoption of a concurrent winner requires the same file. The head source confirms the bound-route guard requireCompatChildHLSRoute checks upstreamServesSource(playSession, source). (2) Close and recreate on a differing source: the summary states that a version switch stops the old session, closes its transcode, drops its node recipe, and starts a session for the requested file. (3) Identity through reconstruction and remote-node adoption: the summary states that reconstruction rebuilds from the recipe only for an upstream that already streams the requested file, and that a non-reconstructable session is cleared for replacement. (4) Tests for direct, remux, HLS transcode, and concurrent two-version starts: the summary lists routing_policy_test.go and playback_report_liveness_test.go cases for each. The cross-replica stop gap and the file-ID-0 legacy rule are documented limits, not #750 acceptance criteria. Limit: the streams.go diff could not be read (changed blobs unavailable), and the full file read was truncated before ensureUpstream. The PASS relies on the PR summary and the partial head source, not a full read of the reuse predicate.
Full details: Out of Scope Changes check
Explanation
The whole-PR summary lists changes to internal/jellycompat (streams.go, routing and liveness tests), documentation (docs/admin-api.md), the replaced end-reason comments and descriptions (internal/playback/session.go, internal/apiv2/admin_playback_history.go, internal/api/handlers/playback_admin_store.go), and generated artifacts (contracts/api/v2/openapi.json, web/src/api/v2/schema.ts). The description-only changes update the replaced end-reason text to name version switches, which follows from the behavior change. The PR states no contract shape changes, and the summaries list no exported declaration changes. No unrelated behavior change appears in the summaries. Limit: the streams.go diff was not readable, so this verdict relies on the summary for that file.
Full details: Description check
Explanation
The description states the problem (a Jellyfin client requesting another version under the same play kept the first version's upstream session), the approach (reuse only when method and media file both match, retire and restart otherwise), validation steps, evidence, and risks. It is specific and directly related to the changeset in internal/jellycompat, internal/apiv2, docs, and the OpenAPI/web schema files.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
🤖 Claude Code (claude-opus-5-5)
Three findings on 5799ca6. A Codex gpt-6.2-sol review ran alongside mine, and these are the parts of it I could trace in the code. I'm fixing the first one in a commit on this branch, so there's no need to change it yourself. The other two are maintainer decisions. I'll cover the rest in the summary comment.
The reason will be displayed to describe this comment to others. Learn more.
Low, maintainer decision: a progressive HEAD for another version now switches the play.
The router sends HEAD /Videos/{id}/stream to HandleVideoStream, which calls ensureUpstreamPlayback before it serves headers. On main, a HEAD for B while A was playing with the same method reused A and changed nothing. Now it retires A and binds the play to B without sending any media. The master manifest already avoids this (headMasterManifest: "Like Jellyfin's, that HEAD starts nothing"). When a GET follows the probe, the play switches anyway, so the harm needs a client that probes a version it doesn't play. The options are a header-only HEAD path for progressive streams like the master manifest's, or accepting this and filing a follow-up. It isn't a one-line fix, because the code after the ensure (route resolution, proxy redirect) assumes the bound session.
The reason will be displayed to describe this comment to others. Learn more.
Low, maintainer decision: an older master manifest can publish its route over a newer version's.
Sequence: A's master passes this bound ensure. Then B's master retires A and records B's recipe and route. Then A resumes and calls recordNodeRoutingAssignment, which writes RoutingAssignment without checking that the upstream is still A's. If A copies video and B encodes it, B's child requests fail requireCompatChildHLSRoute with 503. On main the second version's master was refused outright, so two masters for different versions couldn't both get this far. The window is narrow: two versions' master requests have to overlap. A repair would carry the expected upstream ID into route publication and answer 409 when it no longer matches. That's broader than this PR, so it could also be a follow-up.
…rsion
A progressive request that names no version, or names the item ID, fell
back to the first listed version. With version switches now retiring the
upstream, such a request could stop the version the play streams and
switch it back. Follow the bound version instead, as child HLS requests
do; an explicit MediaSourceId still switches.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewed head: 8f42d031b, which is ecece59 with current main merged in. The first review covered ecece59 on 2026-11-19.
Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green)
Fit: this fixes a real Jellyfin-compatibility bug. Under one play, a second version streamed under the first version's session, so Now Playing, the playback log and watch progress showed the wrong version, and over HLS the switch ended the play. The fix sits where upstream reuse is decided and extends the existing method-switch path instead of adding a second one. Readiness: the approach holds, the new tests fail on the base for the reported reasons, and the behavior now checks out live on the merged head. Two low-severity concurrency questions remain for the maintainers.
Since the first review
Merged main into the branch (8f42d031b). The only conflicts were the generated end_reason descriptions in internal/apiv2/admin_playback_history.go and web/src/api/v2/schema.ts. I kept main's text, reapplied this PR's "or version" wording, and regenerated both files. The diff against main is unchanged: the same nine files.
An ID-less or item-alias progressive request could retire the version the play streams and switch it back to the first listed one. Fixed in ecece59: such requests now follow the bound version, as child HLS requests already did, and an explicit MediaSourceId still switches.
Left for the maintainers
A progressive HEAD for another version switches the play without sending media. The master manifest already avoids this. Options: a header-only HEAD path for progressive streams, or a follow-up issue.
When two versions' master manifests overlap, the older one can publish its route over the newer one's, and the newer one's child requests then get 503. A repair would make route publication check the upstream ID. It could land here or as a follow-up.
The cross-provider round also raised gaps that main already has for play-method switches. This PR makes them reachable for version switches too, and its Approach and Risks sections name most of them. Neither has been reproduced:
A delayed Stopped or audio-change report that names the old version still acts on the new upstream.
A replacement that fails to start leaves the play pointing at the retired session until the next request.
A request whose transcode start or manifest build fails after a version switch rebound the play tears the play down from its stale snapshot, which can end the replacement (CodeRabbit, streams.go:3208). A guard would tear down only while the play still binds the request's upstream.
Earlier bot threads: the author's answers to the Kody and CodeRabbit findings hold against the code. The cross-replica stop gap and the unfenced reconstruction are both pre-existing and belong in separate changes.
Verification
Live, on a sandbox built from 8f42d031b, using a synthetic movie with 1080p and 720p versions and Jellyfin client headers:
Direct play under one PlaySessionId: the 720p request streams the 720p file under a new upstream session for that file. Repeated range requests stay on that session.
Static=true without PlaybackInfo or PlaySessionId: the 720p request streams the 720p file, and the play's only upstream session is on that file.
HLS: the 720p master answers 200 with 1280x720 segments under a new session. A late 1080p segment answers 503 "obsolete playback route", and the 720p session keeps serving.
After Playing/Progress reports, the retired 1080p session's history row keeps the 1080p file with end_reason=replaced.
I didn't rebuild main for a before run. The author's before/after runs in the PR body cover it.
Tests: five of the seven new tests fail on bd40bd9 for the reported reasons. TestBoundRequestsNeverReplaceTheUpstream and TestChildHLSSourceFollowsTheStreamedVersion call functions this PR adds, so they don't build on the base and aren't counted. The progressive case added in ecece59 fails on 5799ca6.
On the merged tree: go build ./..., go vet, and go test for internal/jellycompat, internal/playback, internal/apiv2 and internal/api/handlers pass. So do make verify-apiv2-openapi, verify-apiv2-web-types and verify-apiv2-contract (0 changes), and make lint-changed reports 0 issues.
Cross-provider review: one round with Codex gpt-6.2-sol (xhigh) on 5799ca6. It raised five findings; the fixed one and the two open questions above came from it. The merge changed none of the PR's own code, so I didn't run another round.
None affected. The change touches #1246 and #1206, but none of their cases has been run yet. The PR's Validation tasks: line is accurate.
Other checks
User manual: unaffected. This changes internal session handling, not a setting or documented behavior.
Clients: no Apple, Android, or Roku change; this is jellycompat only.
coderabbitaiBot
added
api-v2
API v2 / Huma migration program (epic #135); long-running, stacked by phase
go
Pull requests that update go code
labels
Nov 19, 2026
Resolve the generated end_reason description in admin_playback_history.go
and web/src/api/v2/schema.ts to main's versions, then reapply this branch's
"or version" wording and regenerate.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (1)
Minor · Guard the teardown after a failed manifest build so it does not delete a play… · streams.go:3208
internal/jellycompat/streams.go:3208 Minor · Stability & Availability · Quick win
Guard the teardown after a failed manifest build so it does not delete a play that now binds another upstream.
When BuildSourceAlignedPlaybackManifest fails at line 3208, the teardown uses the snapshot read before the request. teardownPlaySession deletes the play by playSession.ID without checking the current binding. If a version switch rebinds the play to another file while this build waits on a real manifest, the stale request deletes the replacement stream's play record. Make this build-error path tear down only while the play still binds playSession.UpstreamSessionID. Otherwise, return the error and leave the current binding alone. Keep the existing setup-error exclusions as they are.
Source: Learnings
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: 38bdc4aa-9090-4920-992a-1a5991e0c9dd
Commits
Reviewing files that changed from the base of the PR and between ecece59 and 8f42d03.
Files selected for processing: 7
contracts/api/v2/openapi.json
docs/admin-api.md
internal/api/handlers/playback_admin_store.go
internal/apiv2/admin_playback_history.go
internal/jellycompat/streams.go
internal/playback/session.go
web/src/api/v2/schema.ts
Files skipped from review as they are similar to previous changes: 4
internal/api/handlers/playback_admin_store.go
internal/apiv2/admin_playback_history.go
internal/playback/session.go
web/src/api/v2/schema.ts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.
Re CodeRabbit's outside-diff note on streams.go:3208 (review on 8f42d031b): the trace holds at source level. ensureTranscodeManifestWithToneMapMode tears down from the snapshot ensureBoundUpstreamPlayback returned, and stageCompatStop stages the stop on playSession.ID, not on a re-read binding. If a version switch rebinds the play while this request waits on its transcode, the stale request's failure can end the replacement's play.
The two teardown calls are on main unchanged. This PR doesn't touch them, and on main the same race exists for a play-method switch. The PR makes it reachable for version switches as well. That's the same family as the stale-request cases in the review summary, and it hasn't been reproduced. The transcode-start branch is partly covered: when the switch has already stopped the old native session, the start fails with errCompatUpstreamSessionGone, which skips the teardown. The manifest-build branch at 3208 has no such exclusion. I've listed it with those cases for the maintainers to place here or in a follow-up. The likely guard is to tear down only while the stored play still binds playSession.UpstreamSessionID.
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
api-v2API v2 / Huma migration program (epic #135); long-running, stacked by phasebugSomething isn't workinggoPull requests that update go codeimpact: playbackCan't play, stalls, or wrong mediapriority: P2Limited scope, workaround exists, or polishsize/XL500–999 added + deleted lines (all files); change volume, not priority.
2 participants
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
Closes #750
Related issue: N/A
Validation tasks: none passed that this reaches; it touches #1246 C1 and #1206 C1 (both not yet run)
Other clients: Apple N/A (no client-visible change; native clients use the native API); Android N/A (same); Roku N/A (same)
When a Jellyfin client plays one version of a movie or episode and then requests another version under the same play, Silo kept the first version's upstream session as long as the play method stayed the same. A play lists every version when PlaybackInfo is called without a
MediaSourceId, or when aStatic=truedirect play starts without PlaybackInfo, and an ID-less direct play binds to the started play for that item. In those cases:With this change a request for another version retires the old upstream session, the same way a play-method switch already does, and starts one for the requested file.
Approach
ensureUpstreamPlaybacknow reuses the play's upstream session only when it streams the requested file as well as the requested method. Otherwise it stops the old session, closes its transcode, drops its node recipe and records it asreplaced. The compare-and-swap that attaches the new session adopts a concurrent winner only when the winner streams the same file. A play stored before its upstream file was recorded (file ID 0) keeps the old method-only rule.Only the requests that open a stream (progressive stream and HLS master playlist) may switch a play. Child playlists, segments and progress-report revives now use
ensureBoundUpstreamPlayback, which reuses or rebuilds the current upstream but answers 409 instead of replacing it. A late playlist or report for the old version therefore can't switch the play back. Child requests and progressive requests that name no version (or name the item ID) follow the version the play streams instead of the first one listed. A request whose freshly attached session a concurrent switch replaced also answers 409 and stops its session. A switching request attributes its bytes to the new session, not the retired one.The
replacedend reason's descriptions (admin API doc,/api/v2field description, generated OpenAPI and web types) now mention version switches. No contract shape changes.Not addressed: when the old upstream's native session lives on another API replica, the switch still can't stop that replica's copy or its remote transcode until stale cleanup. That gap already existed for method switches. Reconstruction and remote-node adoption keep the file identity because they act only on an upstream that already streams the requested file.
Validation
internal/jellycompat: a same-method version switch for direct, remux and HLS transcode; concurrent starts of two versions (CAS loser and a replacement after attach); child playlist and revive requests that name a version or method the play left; a reaped upstream of the same version still resuming; the child-source default. Each fails on the code before the matching fix.go build ./...,gofmt,go mod tidy -diff,go vet ./...: pass.make lint-changed(golangci-lint v2.15.0) andmake lint-router-recovery: 0 issues.go testforinternal/jellycompat,internal/playback,internal/apiv2,internal/api/handlers: pass.internal/jellycompatcontract passes. Backup, S3 and AI-subtitle contracts skip here because this machine lacks their services; this change doesn't touch them.make verify-apiv2-openapi,verify-apiv2-web-types,verify-apiv2-contract(0 changes),verify-apiv2-fixtures,verify-route-inventory,verify-local-paths,TestCommittedArtifactMatchesRouter: pass.web/src/api/v2/schema.ts.Evidence
Checked on a local build with a synthetic movie that has two versions (1080p and 720p H.264), using curl with Jellyfin client headers. The same steps ran on
origin/mainand on this branch, against the same database.Re-checked live after merging main (head
8f42d031b): direct play,Static=trueand HLS version switches each start a new upstream session for the requested file, a late segment for the old version answers 503, and the retired session's history row keeps its own file withend_reason=replaced.Evidence: https://evidence.siloserver.org/r/silo-server/pr-4572/
Risks
A client that requests two versions of one play at the same moment now gets a 409 on the request that loses, and retries. Before, it continued on the wrong file. Plays started before this build without a recorded upstream file keep the old behavior until they end.
Checklist
AI Disclosure
replaceddescriptions were stale; all fixed. Round 2 found races where a child playlist or revive passed its checks before a concurrent switch, and a leaked session after a replaced attach; fixed with the bound entry point. Round 3 found that the master manifest's second upstream check could undo a newer switch; fixed, with test gaps closed. Round 4 found no correctness issues. Left open: the cross-replica stop gap described above, and a stale report's position applied to a revived session (the next report corrects it).Note
Replace upstream session when a play switches media version
The compat upstream router now tracks which media file each play's upstream session streams. An upstream is reused only when both the play method and the bound media file match the request; otherwise the old session is retired (recorded with the
replacedend reason) and a new one starts.ensureBoundUpstreamPlaybackpath serves requests that follow an already opened stream. It rejects requests naming a different method or file with an upstream-replaced error instead of switching the play (streams.go).ensureUpstreamflow is split into helpers:reuseUpstream,reconstructUpstream,retireUpstream, andstartCompatUpstream. Concurrent starts adopt a winner only when method and file both match.replacedend reason now also covers version switches in docs and schemas.Macroscope summarized 8f42d03.