Repository navigation
feat(playback): unified restart-resilient playback (native + jellycompat) - #174
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughImplements "TR-lease" restart-resilient playback by introducing a ChangesTR-lease Restart-Resilient Playback
Sequence Diagram(s)sequenceDiagram
participant Client
participant ProxyServer
participant PlaybackHandler
participant TranscodeManager
participant RedisLeaseStore
participant FFmpegProcess
Note over Client,FFmpegProcess: Normal playback start
Client->>PlaybackHandler: POST /playback/start
PlaybackHandler->>TranscodeManager: RegisterTranscodeSession(sessionID, ts)
PlaybackHandler-->>Client: stream_url with ?st=<signedRecipeToken>
Note over Client,FFmpegProcess: Server restart → session lost from memory
Client->>ProxyServer: GET /stream/{token}/manifest
ProxyServer->>RedisLeaseStore: Allowed(sessionID)
RedisLeaseStore-->>ProxyServer: true
ProxyServer->>PlaybackHandler: GET /manifest?st=<token>
PlaybackHandler->>TranscodeManager: LoadOrReconstructSession(sessionID, userID, card)
TranscodeManager-->>PlaybackHandler: SessionLoaded (reconstructed)
PlaybackHandler->>TranscodeManager: ReconstructTranscode(sessionID, -1, card)
TranscodeManager->>FFmpegProcess: StartTranscode(opts from RecipeCard)
FFmpegProcess-->>TranscodeManager: TranscodeSession
PlaybackHandler-->>Client: manifest
Note over Client,FFmpegProcess: Admin Stop → deny stream
PlaybackHandler->>RedisLeaseStore: Deny(sessionID)
Client->>ProxyServer: GET next segment
ProxyServer->>RedisLeaseStore: Allowed(sessionID)
RedisLeaseStore-->>ProxyServer: false
ProxyServer-->>Client: 403 stream access revoked
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
docs/superpowers/specs/unified-playback-reconstruct.md (1)
62-62: 💤 Low valueAdd language identifiers to fenced code blocks for markdown linting compliance.
Lines 62, 88, 100, 129, and 169 contain fenced code blocks without language specifications. Per markdownlint (MD040), these should declare a language:
textfor ASCII diagrams,yamlfor YAML examples, etc.🔧 Proposed fixes for fenced code blocks
Line 62 (ASCII diagram):
- ``` + ```text ┌──────────────────────────────────────────┐Line 88 (ASCII diagram):
- ``` + ```text Watching here Bucket filled to hereLine 100 (ASCII diagram):
- ``` + ```text SERVER: UP ───────────────✕ DOWN (≤60s) ✕──────────────── UP againLine 129 (ASCII diagram):
- ``` + ```text Client: "GET seg_00200 for session X" (+ its normal login auth)Line 169 (ASCII diagram):
- ``` + ```text internal/api/handlers.PlaybackHandler ─┐Line 366 (YAML example):
- ```yaml + ```yaml services:(This one already has
yamlidentifier, no change needed.)Also applies to: 88-88, 100-100, 129-129, 169-169
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/superpowers/specs/unified-playback-reconstruct.md` at line 62, The fenced code blocks at lines 62, 88, 100, 129, and 169 are missing language identifiers, which violates markdownlint MD040 compliance. Update each of these fenced code block opening markers by adding the `text` language identifier (change from ``` to ```text) since they contain ASCII diagrams. The code block at line 366 already has the `yaml` identifier so no changes are needed there. This ensures all code blocks declare their language type as required by markdownlint rules.Source: Linters/SAST tools
internal/playback/recipecard.go (1)
54-56: 🏗️ Heavy liftResolve the
HWAccel/HWDevicecontract mismatch.The comment states these values are re-resolved from live config, but the code serializes and replays them from the card. Please align one source of truth; otherwise reconstructed sessions can keep stale hardware config after restart.
One concrete direction (live-config wins)
func NewRecipeCard(userID int, profileID string, mediaFileID int, transcodeNodeURL string, opts TranscodeOpts) RecipeCard { return RecipeCard{ @@ - HWAccel: opts.HWAccel, - HWDevice: opts.HWDevice, SubtitleTrackIndex: opts.SubtitleTrackIndex, @@ -func (c RecipeCard) TranscodeOpts(outputDir, ffmpegPath string, logSink FFmpegLogSink) TranscodeOpts { +func (c RecipeCard) TranscodeOpts(outputDir, ffmpegPath, hwAccel, hwDevice string, logSink FFmpegLogSink) TranscodeOpts { return TranscodeOpts{ @@ - HWAccel: c.HWAccel, - HWDevice: c.HWDevice, + HWAccel: hwAccel, + HWDevice: hwDevice,Also applies to: 73-74, 129-130
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/playback/recipecard.go` around lines 54 - 56, The comment indicates that HWAccel and HWDevice should be re-resolved from live config during reconstruction rather than pinned to the recipe card, but the code currently serializes these values from the card. Remove the HWAccel and HWDevice fields from serialization in the recipe card to ensure they are always fetched from live config on reconstruct. This applies to the serialization logic (around lines 73-74) where these fields are being written to the card and the deserialization logic (around lines 129-130) where they are being read back. By eliminating these fields from the card, operators' hardware configuration changes will apply correctly to reconstructed sessions without stale cached values persisting after restart.internal/jellycompat/router.go (1)
101-109: 💤 Low valueConsider adding transcode directory to cleanup log messages for consistency.
The native handler logs
"dir", deps.Config.Playback.TranscodeDirin both warn and info messages, which aids debugging. The jellycompat path omits this. Minor inconsistency.🔧 Suggested improvement
playbackHandler.RecipeStore = playback.NewPostgresRecipeStore(deps.DB) if cleaned, err := playbackHandler.CleanupOrphanedTranscodes(); err != nil { - slog.Warn("jellycompat transcode cleanup failed", "error", err) + slog.Warn("jellycompat transcode cleanup failed", "dir", playbackHandler.TranscodeDir, "error", err) } else if cleaned > 0 { - slog.Info("jellycompat transcode cleanup removed orphaned dirs", "count", cleaned) + slog.Info("jellycompat transcode cleanup removed orphaned dirs", "dir", playbackHandler.TranscodeDir, "count", cleaned) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/jellycompat/router.go` around lines 101 - 109, The slog.Warn and slog.Info calls in the transcode cleanup section of the playbackHandler.CleanupOrphanedTranscodes() block are missing the transcode directory information in their log output. Add the transcode directory field to both logging statements for consistency with the native handler approach. Include "dir" and deps.Config.Playback.TranscodeDir as additional parameters in both the slog.Warn call (which logs the error case) and the slog.Info call (which logs the successful cleanup case) to provide better debugging context about which directory was being processed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/playback.go`:
- Around line 1415-1426: The recipe card persisted in HandleStartPlayback and
HandleStartTranscode does not get updated when audio tracks are changed via
HandleChangeAudioTrack, causing stale AudioTrackIndex and TranscodeAudio values
to be used after server restart. In the HandleChangeAudioTrack function (lines
1810-1835), after updating the in-memory session state with the new audio track
information, add a corresponding call to h.tm.SaveCard using
context.WithoutCancel(r.Context()) to persist an updated recipe card with the
new AudioTrackIndex and TranscodeAudio values, similar to how it is done in the
switch statement for PlayDirect and PlayRemux cases shown in the diff.
In `@internal/playback/transcode_manager.go`:
- Around line 278-287: The LoadOrReconstructSession method does not validate
that the TranscodeManager receiver m is non-nil before calling
m.ReconstructSession, which will cause a panic with a nil receiver. Add a nil
check at the start of the LoadOrReconstructSession method to detect when m is
nil and return nil, SessionMissing status in that case, honoring the documented
optional TranscodeManager behavior. Apply the same nil check to any other
locations mentioned at lines 307-309 where m is dereferenced without validation.
- Around line 558-563: After the http.DefaultClient.Do(req) call succeeds and
before closing resp.Body, add a check for the HTTP response status code to
verify that the remote DELETE request was actually successful. If the status
code indicates a failure (such as 401, 404, or 500), log a warning similar to
the existing error log so that failed remote transcode deletions are properly
tracked instead of being silently ignored. This check should happen between the
error handling for the request itself and the resp.Body.Close() call.
- Around line 412-419: After retrieving the card from the store using
m.store().Get() in the doReconstructTranscode function, add a guard check to
verify that the card is actually a transcode card by inspecting its PlayMethod
field. If the card's PlayMethod indicates it is a direct or remux card (not
transcode), return early before calling card.TranscodeOpts() to prevent direct
or remux sessions from entering the HLS transcode reconstruction path. This
ensures only transcode-type cards proceed to build TranscodeOpts.
In `@migrations/sql/20260618053223_add_jellycompat_playback_sessions.sql`:
- Around line 22-29: The migration adds indexes on expires_at and compat_token
fields, but lacks an index for the user_id field which is identified as a lookup
and audit path. Add a new CREATE INDEX statement for the
jellycompat_playback_sessions table on the user_id column (or optionally create
a composite index on (user_id, expires_at) if queries are typically live-row
filtered). Follow the same naming convention and BTREE indexing pattern as the
existing idx_jellycompat_playback_sessions_expires_at and
idx_jellycompat_playback_sessions_compat_token indexes to ensure consistent
performance across all declared access paths.
---
Nitpick comments:
In `@docs/superpowers/specs/unified-playback-reconstruct.md`:
- Line 62: The fenced code blocks at lines 62, 88, 100, 129, and 169 are missing
language identifiers, which violates markdownlint MD040 compliance. Update each
of these fenced code block opening markers by adding the `text` language
identifier (change from ``` to ```text) since they contain ASCII diagrams. The
code block at line 366 already has the `yaml` identifier so no changes are
needed there. This ensures all code blocks declare their language type as
required by markdownlint rules.
In `@internal/jellycompat/router.go`:
- Around line 101-109: The slog.Warn and slog.Info calls in the transcode
cleanup section of the playbackHandler.CleanupOrphanedTranscodes() block are
missing the transcode directory information in their log output. Add the
transcode directory field to both logging statements for consistency with the
native handler approach. Include "dir" and deps.Config.Playback.TranscodeDir as
additional parameters in both the slog.Warn call (which logs the error case) and
the slog.Info call (which logs the successful cleanup case) to provide better
debugging context about which directory was being processed.
In `@internal/playback/recipecard.go`:
- Around line 54-56: The comment indicates that HWAccel and HWDevice should be
re-resolved from live config during reconstruction rather than pinned to the
recipe card, but the code currently serializes these values from the card.
Remove the HWAccel and HWDevice fields from serialization in the recipe card to
ensure they are always fetched from live config on reconstruct. This applies to
the serialization logic (around lines 73-74) where these fields are being
written to the card and the deserialization logic (around lines 129-130) where
they are being read back. By eliminating these fields from the card, operators'
hardware configuration changes will apply correctly to reconstructed sessions
without stale cached values persisting after restart.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4a7483d0-726c-4e64-b562-77e0d0425141
📒 Files selected for processing (29)
docs/superpowers/specs/unified-playback-reconstruct.mdinternal/api/handlers/admin_playback_control.gointernal/api/handlers/playback.gointernal/api/handlers/playback_realtime.gointernal/api/handlers/playback_test.gointernal/api/handlers/session_ws.gointernal/api/handlers/stream.gointernal/api/router.gointernal/jellycompat/audio_selection_test.gointernal/jellycompat/auth.gointernal/jellycompat/handlers_playback.gointernal/jellycompat/playback_sessions.gointernal/jellycompat/playback_sessions_postgres.gointernal/jellycompat/playback_sessions_postgres_test.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/jellycompat/streams.gointernal/jellycompat/streams_test.gointernal/playback/recipecard.gointernal/playback/recipecard_postgres.gointernal/playback/recipecard_test.gointernal/playback/reconstruct_test.gointernal/playback/session.gointernal/playback/transcode.gointernal/playback/transcode_close_test.gointernal/playback/transcode_manager.gointernal/playback/transcode_manager_test.gomigrations/sql/20260617233705_add_transcode_recipes.sqlmigrations/sql/20260618053223_add_jellycompat_playback_sessions.sql
…deManager Make direct, remux, and native HLS transcode sessions survive a server restart through one shared flow instead of per-method paths. A missing in-memory session becomes a reconstruct trigger, not a 404: the server rebuilds the session from a tiny durable recipe card plus the position the client re-supplies on its next request. - internal/playback/transcode_manager.go: shared TranscodeManager owning the transcodes map, recipe-card lifecycle, reconstruct single-flight + concurrency cap, LoadOrReconstructSession front door, ReconstructSession / ReconstructTranscode, and orphan cleanup. ~90% is logic moved out of the native handler (no behavior change), not new surface. - internal/playback/recipecard.go + recipecard_postgres.go: RecipeCard with a PlayMethod discriminator (direct/remux/transcode; empty decodes as transcode for back-compat) behind a swappable, nil-safe RecipeStore interface backed by transcode_recipes. - internal/playback/session.go: RegisterReconstructed inserts a rebuilt Session under its existing id (no UUID mint, no limit double-count, race-yielding). - internal/playback/transcode.go: CloseProcess keeps the output dir so a reconstruct winner keeps serving; Close removes it. - internal/api/handlers: drain the transcode lifecycle into the manager; wire reconstruct into the stream/segment serve paths; re-bind ownership to the live caller (refuse userID==0/mismatch); card-aware orphan cleanup. - migrations: add transcode_recipes (expires_at TTL, filter-on-read, indexed). Ownership stays two-factor: an authenticated caller AND a session.UserID that matches; the card stores no secrets and identity is re-resolved per request. Tests: recipe-card round-trip/legacy-decode/disabled-noop, RegisterReconstructed insert/race/concurrency, close-vs-close-process dir semantics, the LoadOrReconstructSession status matrix, and the reconstruct concurrency cap. AI-use: implemented with AI assistance (design, implementation, adversarial review).
…anager Bring Jellyfin (jellycompat) HLS playback onto the same restart-resilient flow as the native path. Previously jellycompat owned a separate PlaybackHandler with a private transcodes map and a duplicated transcode lifecycle that never grew the reconstruct half, so an in-flight Jellyfin transcode died on restart and the next segment request 404'd. - Embed the shared playback.TranscodeManager and delete the duplicate lifecycle, so jellycompat gets reconstruct, the concurrency cap, the node-affinity rule, and the card lifecycle for free. - internal/jellycompat/playback_sessions_postgres.go: DurableCompatPlaybackStore, a write-through cache over jellycompat_playback_sessions behind the new CompatPlaybackStore interface (nil pool degrades to cache-only). This persists the load-bearing PlaySessionId -> UpstreamSessionID mapping (plus media sources, route item id, seek) so it survives a restart instead of vanishing with the map. - Write a recipe card on compat transcode start keyed by the upstream session id, using the native StreamAppUserID so the ownership re-bind matches; reconstruct the upstream session and the transcode seeked to the requested seg_NNNNN. - migrations: add jellycompat_playback_sessions (expires_at TTL + compat_token index, full PlaybackSession in data JSONB). Auth is mapped to the native user id before reconstruct so the same two-factor ownership check and userID==0/mismatch refusal apply unchanged. Tests: DB-gated (SILO_TEST_DATABASE_URL) durable-store round-trip proving a session written by one instance reloads in a fresh one (the restart case), plus a nil-pool cache-only path; existing handler tests updated to the manager. AI-use: implemented with AI assistance (design, implementation, adversarial review).
Replace the three overlapping playback docs (the native Postgres restart-resilience spec, the jellycompat plan, and the unification spec) with a single self-contained design at docs/superpowers/specs/unified-playback-reconstruct.md. The doc leads with the unified design — the one-idea reconstruct model, a strong visual flow of a restart mid-playback, the shared TranscodeManager + recipe card, the two swappable durable stores, security, the concurrency cap and node-affinity constraint, preconditions, and verification. The design history and rationale (reconstruct-not-rehydrate, phased delivery, Redis-vs-Postgres, token-as- descriptor, failure analysis) move to an appendix. It references no other md file. AI-use: written with AI assistance.
Four fixes from PR review of the unified reconstruction work: - Rewrite the recipe card on audio-track change. HandleChangeAudioTrack only updated the in-memory session/transcode, so after a restart reconstruct resumed with the stale AudioTrackIndex/TranscodeAudio (and stale play method) from the start-time card. Re-save the card (direct/remux/transcode) with the switched state, mirroring the start-card pattern. - Guard nil TranscodeManager in LoadOrReconstructSession and ReconstructSession. StreamHandler.TM is documented optional (tests/minimal setups); a missing session previously panicked in recipeEnabled instead of returning SessionMissing. ReconstructTranscode already guarded nil; make the two siblings consistent. - Reject direct/remux cards in doReconstructTranscode before spawning ffmpeg, so a non-transcode card id can never enter the HLS reconstruction path. - Log a non-success status from the remote transcode-node DELETE in CloseTranscodeSession; a 401/404/500 was previously silent. AI-use: implemented with AI assistance.
523569e to
c122646
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/api/handlers/playback.go (2)
1944-1972:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMirror start-playback remux planning in audio changes.
The start path treats
PlayRemuxas needing a transcode node and returns/stream/transcode/{token}/master.m3u8. This audio-change path only setsneedsTranscodeforPlayTranscodeand emits/stream/remux/{token}, so remux switches can be planned without a transcode node and return a URL shape inconsistent with the initial playback path.Proposed fix
if h.NodePlanner != nil && h.JWTSecret != "" { - needsTranscode := updatedSession.PlayMethod == playback.PlayTranscode + needsTranscode := updatedSession.PlayMethod == playback.PlayTranscode || updatedSession.PlayMethod == playback.PlayRemux estKbps := updatedSession.TargetBitrateKbps @@ switch updatedSession.PlayMethod { - case playback.PlayRemux: - resp.StreamURL = proxyNode.URL + "/stream/remux/" + token - case playback.PlayTranscode: + case playback.PlayRemux, playback.PlayTranscode: resp.StreamURL = proxyNode.URL + "/stream/transcode/" + token + "/master.m3u8" } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/playback.go` around lines 1944 - 1972, The needsTranscode variable in the audio-change path only considers PlayTranscode as requiring a transcode node, but should also treat PlayRemux the same way as the start-playback path does. Modify the line where needsTranscode is assigned (currently `needsTranscode := updatedSession.PlayMethod == playback.PlayTranscode`) to include both playback.PlayTranscode and playback.PlayRemux using a logical OR condition, ensuring that remux sessions are also planned with a transcode node and return URL paths consistent with the initial playback path.
1097-1134:⚠️ Potential issue | 🔴 CriticalUse
userInitiatedto revoke token-carried resumes.
userInitiatedis passed tofinalizeSessionStopbut never consumed; with token-carried reconstruction, a still-valid stream token can recreate the deleted session unless the stop revokes the lease. The admin control path correctly callsdenyStreamLeasebeforestopPlaybackSessionByID, but the user stop API (HandleStopPlayback) does not. Keep abort/expiry resumable, but make user stops terminal.Minimal fix
func (h *PlaybackHandler) finalizeSessionStop(ctx context.Context, session *playback.Session, syncNow bool, syncReason string, userInitiated bool) { if h == nil || session == nil || session.ID == "" { return } if ctx == nil { ctx = context.Background() } stopResult := h.persistStopAndHistory(ctx, session) if h.WatchScrobbler != nil && stopResult.MediaItemID != "" { event := h.scrobbleEventForSession(ctx, session, stopResult.MediaItemID, stopResult.DurationSeconds, stopResult.FinalPositionSeconds) event.HistoryID = stopResult.HistoryID event.Completed = stopResult.Completed if stopResult.Completed { if err := h.WatchScrobbler.ScrobbleStop(ctx, event); err != nil { slog.Warn("failed to queue watch provider stop scrobble", "session", session.ID, "error", err) } } else if !stopResult.SkippedBelowMinResume { if err := h.WatchScrobbler.ScrobblePause(ctx, event); err != nil { slog.Warn("failed to queue watch provider pause scrobble", "session", session.ID, "error", err) } } } if entry, buildErr := h.buildAdminHistoryEntry(ctx, session); buildErr != nil { slog.Error("failed to build admin history", "session", session.ID, "error", buildErr) } else if entry != nil && h.AdminStore != nil { if err := h.AdminStore.RecordHistory(ctx, *entry); err != nil { slog.Error("failed to record admin history", "session", session.ID, "error", err) } } if h.AdminStore != nil { if err := h.AdminStore.DeleteSession(ctx, session.ID); err != nil { slog.Error("failed to delete synced session", "session", session.ID, "error", err) } } + if userInitiated { + h.denyStreamLease(ctx, session.ID) + } h.tm.CloseTranscodeSession(session.ID, session.TranscodeNodeURL) if syncNow { h.syncSessionsNow(ctx, syncReason) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/playback.go` around lines 1097 - 1134, The `userInitiated` parameter in the `finalizeSessionStop` method is not being used, which means user-initiated playback stops do not revoke the stream token lease, allowing the deleted session to be recreated via the still-valid token. When `userInitiated` is true, add logic to revoke or deny the stream lease before or during the session cleanup (similar to how the admin control path handles this via `denyStreamLease`), ensuring that user-initiated stops are terminal and prevent token-carried session reconstruction while keeping abort and expiry scenarios resumable.
🧹 Nitpick comments (1)
internal/jellycompat/playback_sessions.go (1)
55-57:Putmethod intentionally uses fail-open semantics with explicit error logging.The
Putmethod writes to the in-memory cache first, then attempts to persist to the database viaupsert(). If the database write fails, the session exists in the cache but not in the database. This is by design—errors are logged (not silent), and the pattern prioritizes availability by allowing the in-memory write to always succeed. However, developers should understand this means restarting the service could lose sessions that were only in memory. If this trade-off is intentional, no action is needed; if durability is a strict requirement, consider makingPutreturn an error and propagating it to callers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/jellycompat/playback_sessions.go` around lines 55 - 57, Review whether the fail-open semantics of the Put method in the CompatPlaybackStore interface is intentional for your use case. If durability of playback sessions is a strict requirement and data loss on service restart is unacceptable, modify the Put method signature to return an error instead of void, then update the upsert() call to capture any database persistence errors and return them to callers so they can be properly handled and propagated up the call stack.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/architecture/restart-resilient-playback.md`:
- Line 84: The fenced code blocks at lines 84, 430, and 458 are missing language
identifiers, which triggers MD040 markdownlint warnings. Add the language
identifier `text` to each of these unlabeled code blocks by changing the opening
triple backticks from ``` to ```text while keeping the content and closing
triple backticks unchanged. This applies to all three occurrences mentioned in
the comment.
In `@internal/api/handlers/playback.go`:
- Around line 1929-1939: The StreamURL assigned in the changeAudioResponse is
missing the signed recipe parameter for local transcode playback. When newMethod
is PlayTranscode, h.playbackStreamURL returns an unsigned URL without the ?st=
parameter, causing the updated recipe with the new audio selection to be lost on
restart. Add logic after the StreamURL assignment to check if newMethod is
PlayTranscode, and if so, append a signed recipe token to the StreamURL to
ensure the updated full recipe is included for reconstruction after the audio
switch.
In `@internal/playback/recipecard.go`:
- Around line 53-57: The `TranscodeOpts()` method currently sources `HWAccel`
and `HWDevice` fields only from the card itself, but since the card is rebuilt
from claims (which exclude these fields per `ToClaims()`), these values end up
empty during token-based reconstruction. Modify `TranscodeOpts()` to re-resolve
`HWAccel` and `HWDevice` from live config at reconstruction time, similar to how
`FFmpegPath` is intentionally re-resolved, ensuring that operator config changes
for hardware acceleration are applied to reconstructed sessions as documented in
the comment.
In `@internal/playback/transcode_cleanup.go`:
- Around line 46-50: The minAge protection is bypassed when entry.Info() fails
because the error case is not explicitly handled. Currently, if statErr is not
nil, the condition fails and the code falls through to delete the entry, which
violates the intent of minAge. Fix this by adding an else clause after the check
`if minAge > 0` that explicitly continues (skips deletion) when entry.Info()
returns an error, ensuring entries whose age cannot be verified are
conservatively retained rather than deleted.
In `@internal/playback/transcode_manager.go`:
- Around line 535-551: The issue is a race condition where snapshots of
m.transcodes and m.reconstructInFlight are taken at different times, allowing a
reconstruct to register in m.transcodes after the first snapshot but before the
second snapshot is taken, then clear m.reconstructInFlight before that snapshot,
resulting in the sessionID being absent from the active map and incorrectly
marked for cleanup. To fix this, acquire both m.transcodeMu and m.inFlightMu
locks together at the beginning of the function before taking either snapshot,
copy both active transcodes and reconstructInFlight maps while holding both
locks, then release both locks before calling CleanupOrphanedTranscodeDirs. This
ensures the snapshots are taken atomically and represent a consistent state of
both maps.
---
Outside diff comments:
In `@internal/api/handlers/playback.go`:
- Around line 1944-1972: The needsTranscode variable in the audio-change path
only considers PlayTranscode as requiring a transcode node, but should also
treat PlayRemux the same way as the start-playback path does. Modify the line
where needsTranscode is assigned (currently `needsTranscode :=
updatedSession.PlayMethod == playback.PlayTranscode`) to include both
playback.PlayTranscode and playback.PlayRemux using a logical OR condition,
ensuring that remux sessions are also planned with a transcode node and return
URL paths consistent with the initial playback path.
- Around line 1097-1134: The `userInitiated` parameter in the
`finalizeSessionStop` method is not being used, which means user-initiated
playback stops do not revoke the stream token lease, allowing the deleted
session to be recreated via the still-valid token. When `userInitiated` is true,
add logic to revoke or deny the stream lease before or during the session
cleanup (similar to how the admin control path handles this via
`denyStreamLease`), ensuring that user-initiated stops are terminal and prevent
token-carried session reconstruction while keeping abort and expiry scenarios
resumable.
---
Nitpick comments:
In `@internal/jellycompat/playback_sessions.go`:
- Around line 55-57: Review whether the fail-open semantics of the Put method in
the CompatPlaybackStore interface is intentional for your use case. If
durability of playback sessions is a strict requirement and data loss on service
restart is unacceptable, modify the Put method signature to return an error
instead of void, then update the upsert() call to capture any database
persistence errors and return them to callers so they can be properly handled
and propagated up the call stack.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 75a98279-53bb-4bc5-b7ee-572f20c08fca
📥 Commits
Reviewing files that changed from the base of the PR and between 523569e7e77f41e74129270ca58a9407c4f41d1f and c12264642ba91b4e035c6e61ecce1b92103ccd1e.
📒 Files selected for processing (40)
cmd/silo/main.godocs/architecture/restart-resilient-playback.mdinternal/api/handlers/admin_playback_control.gointernal/api/handlers/playback.gointernal/api/handlers/playback_realtime.gointernal/api/handlers/playback_test.gointernal/api/handlers/session_ws.gointernal/api/handlers/stream.gointernal/api/router.gointernal/jellycompat/audio_selection_test.gointernal/jellycompat/auth.gointernal/jellycompat/cleanup.gointernal/jellycompat/cleanup_test.gointernal/jellycompat/handlers_playback.gointernal/jellycompat/playback_sessions.gointernal/jellycompat/playback_sessions_postgres.gointernal/jellycompat/playback_sessions_postgres_test.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/jellycompat/streams.gointernal/jellycompat/streams_test.gointernal/noderecipe/store.gointernal/noderecipe/store_test.gointernal/nodesessions/tracker.gointernal/playback/recipecard.gointernal/playback/recipecard_test.gointernal/playback/reconstruct_test.gointernal/playback/session.gointernal/playback/transcode.gointernal/playback/transcode_cleanup.gointernal/playback/transcode_close_test.gointernal/playback/transcode_manager.gointernal/playback/transcode_manager_test.gointernal/proxy/server.gointernal/streamauth/lease.gointernal/streamauth/lease_test.gointernal/streamtoken/token.gointernal/transcodenode/server.gointernal/transcodenode/server_test.gomigrations/sql/20260618053223_add_jellycompat_playback_sessions.sql
✅ Files skipped from review due to trivial changes (1)
- internal/streamtoken/token.go
🚧 Files skipped from review as they are similar to previous changes (18)
- internal/api/handlers/session_ws.go
- internal/playback/transcode_close_test.go
- internal/jellycompat/auth.go
- migrations/sql/20260618053223_add_jellycompat_playback_sessions.sql
- internal/api/handlers/playback_test.go
- internal/jellycompat/cleanup_test.go
- internal/api/handlers/playback_realtime.go
- internal/jellycompat/audio_selection_test.go
- internal/api/handlers/stream.go
- internal/jellycompat/cleanup.go
- internal/playback/session.go
- internal/jellycompat/server.go
- internal/jellycompat/streams_test.go
- internal/playback/reconstruct_test.go
- internal/jellycompat/playback_sessions_postgres_test.go
- internal/jellycompat/playback_sessions_postgres.go
- internal/jellycompat/streams.go
- internal/playback/transcode.go
Design evolution since the original three commitsThe reconstruct model held, but the durable descriptor and the revocation story changed. Three follow-up steps, in order: 1. TR — the recipe rides the token, not Postgres. The Postgres 2. Session-deny lease — admin control without trusting the client. Carrying the recipe on the client means a still-valid signed token can outlive an admin's intent to kill a stream. So admin Stop/Terminate writes a per-session deny marker to Redis (TTL = the 24h token lifetime), and the offload node checks it before serving — returning 3. Redis recipe store for the jellycompat node path. TR works for native because a native client round-trips the native token; a Jellyfin client cannot. On a dedicated Net: single-box deployments reconstruct with zero external dependency (token only); multi-node deployments lean on the Redis they already require for offload — one store for deny-leases, one for the jellycompat node recipe. Full design, options comparison, and diagrams in |
|
Thanks for doing this. Let me know if this review makes sense. |
26929d4 to
9e03913
Compare
|
Yep, makes sense — thanks for the thorough pass. Pushed fixes for all three v1 asks:
Left the post-v1 stuff (full revocation wiring, the Heads up: I squashed the branch down to 3 commits and force-pushed, so the inline anchors will have moved. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/jellycompat/handlers_playback.go`:
- Around line 419-435: The code marks TranscodeStarted as true in the playback
session update even when recipe remains nil because the upstream session could
not be loaded. To fix this, after the recipe creation block that attempts to
call h.sessionMgr.GetSession for upstreamSessionID, add a check to verify that
recipe is not nil. If recipe is nil, immediately call h.tm.CloseTranscodeSession
to roll back the started transcode and return an error before proceeding to the
h.playbackStore.Update call. This ensures the session is only marked as
TranscodeStarted when a valid recipe has been successfully constructed from the
upstream session.
- Around line 439-446: The h.RecipeNodeStore.Put call uses
context.WithoutCancel(ctx) which removes the request timeout entirely, allowing
the Redis operation to block indefinitely and hang the manifest request. Instead
of detaching from the context entirely, create a new context with a short
dedicated timeout (such as 1-2 seconds) for this best-effort operation. This
allows the operation to fail gracefully without blocking the request while still
maintaining the resilience benefits when successful.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0c2cec76-45cd-4b13-9137-800476c1d5fc
📥 Commits
Reviewing files that changed from the base of the PR and between 26929d4732c23a5908690724f5a7ecdffa104460 and 9e039136264fa1ca031c9ffddb2e25763f0beeb5.
📒 Files selected for processing (30)
cmd/silo/main.godocs/architecture/restart-resilient-playback.mdinternal/api/handlers/admin_playback_control.gointernal/api/handlers/playback.gointernal/api/handlers/stream.gointernal/api/router.gointernal/jellycompat/audio_selection_test.gointernal/jellycompat/handlers_playback.gointernal/jellycompat/playback_4k_test.gointernal/jellycompat/playback_sessions.gointernal/jellycompat/remote_transcode_reconstruct_test.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/jellycompat/streams.gointernal/noderecipe/store.gointernal/noderecipe/store_test.gointernal/nodesessions/tracker.gointernal/playback/recipecard.gointernal/playback/recipecard_test.gointernal/playback/transcode_cleanup.gointernal/playback/transcode_manager.gointernal/playback/transcode_manager_test.gointernal/proxy/server.gointernal/streamauth/lease.gointernal/streamauth/lease_test.gointernal/streamtoken/token.gointernal/transcodenode/server.gointernal/transcodenode/server_test.goweb/src/player/stream-url.test.tsweb/src/player/stream-url.ts
✅ Files skipped from review due to trivial changes (2)
- internal/playback/recipecard_test.go
- internal/streamtoken/token.go
🚧 Files skipped from review as they are similar to previous changes (20)
- internal/playback/transcode_cleanup.go
- internal/noderecipe/store_test.go
- internal/streamauth/lease_test.go
- internal/nodesessions/tracker.go
- internal/playback/transcode_manager_test.go
- internal/api/handlers/admin_playback_control.go
- internal/jellycompat/playback_sessions.go
- internal/noderecipe/store.go
- internal/transcodenode/server_test.go
- internal/jellycompat/server.go
- internal/api/router.go
- cmd/silo/main.go
- internal/streamauth/lease.go
- internal/proxy/server.go
- internal/api/handlers/stream.go
- internal/transcodenode/server.go
- internal/playback/recipecard.go
- internal/jellycompat/streams.go
- internal/playback/transcode_manager.go
- internal/api/handlers/playback.go
Build on the shared TranscodeManager (introduced earlier in this branch) so a playback session survives an API-server or transcode-node restart without the client re-negotiating, and retire the Postgres transcode_recipes store in favor of a recipe carried inside the signed stream token. - RecipeCard encodes the byte-affecting encode parameters and rides inside the stream token; LoadOrReconstructSession rebuilds the in-memory Session (and, for integrated transcodes, the ffmpeg process) on a cold miss, single-flighted per session and paced by a spawn semaphore. Removes recipecard_postgres.go and the 20260617233705_add_transcode_recipes migration. - transcodenode reconstructs a lost ffmpeg node-side from the forwarded token. - TR-lease: proxy/streamauth enforce a revocation deny-marker on every served segment, with a 500ms Redis timeout, a bounded per-session "allowed" cache (3s TTL, expiry-first graceful eviction), and a degraded-fail-open counter. Review hardening folded in: - Manifest/segment handlers do the in-memory session lookup first and only verify the stream token on a reconstruct miss (token HMAC was per-segment). - Copy-mode reconstruct never applies the encoded-only seg*dur seek, at spawn time or via the recovery path: RestartSeekTarget reports "unresolved" for a copy session whose manifest cannot yet map the segment, so the client retries instead of seeking to a fabricated source time. - Crash teardown is a compare-and-delete (CloseTranscodeSessionIf returns whether it matched); the crash closure tears down the playback session only when it matched, so a session reconstructed under the same id is not killed. - Reconstruct enforces the same per-user stream/transcode caps as a fresh start (RegisterReconstructedWithLimits), closing a token-replay slot bypass. AI-use disclosure: implemented with AI assistance (Claude Code), including a two-round multi-agent adversarial review whose findings drove the hardening.
…store Make Jellyfin-compat playback sessions survive a server or transcode-node restart by reusing the shared TranscodeManager reconstruct path and a durable recipe store, on top of the durable compat session store added earlier in this branch. - Node-side transcode reconstruct goes through the shared recipe store; the recipe is persisted to the control-plane store (Redis) when a dedicated transcode node is used so the node can rebuild ffmpeg after its own restart. - Adopt the shared manager's API (3-arg OnFFmpegCrash carrying the dead session, guarded CloseTranscodeSessionIf, RegisterReconstructedWithLimits). Review hardening folded in: - Recipe lifecycle: noderecipe.Store gains Delete, called on deliberate teardown (stop, method-switch discard, node stop/force-reload) so a stopped session cannot be resurrected by a buffered request after a node restart; crash paths intentionally keep the recipe so a resume can reconstruct. - Crash closure tears down the upstream session only when the guarded transcode close matched, so a reconstructed successor is never left orphaned. - Copy-mode segment recovery surfaces a retryable not-found instead of a wrong-position restart, matching the native and node paths. - Durable Update is now a SELECT ... FOR UPDATE transaction, removing the lost-update clobber that could silently drop a transcode recipe. - Empty-token route resolution no longer falls back to an unbounded full-table scan; DB expiry filters bind the injected clock; the redundant re-Get is gone. AI-use disclosure: implemented with AI assistance (Claude Code), including a two-round multi-agent adversarial review whose findings drove the hardening.
Replace the superpowers spec with a single architecture record describing the token-carried recipe card, the shared TranscodeManager reconstruct path for direct/remux/transcode, the jellycompat durable session + node recipe store, and the revocation-lease model with its fail-open tradeoff. AI-use disclosure: written with AI assistance (Claude Code).
9e03913 to
73d03a8
Compare
The noderecipe / transcode-node / jellycompat comments justified the Redis recipe store with "a Jellyfin client cannot round-trip a token". The real reason: the node-hop token is server-minted and could carry the recipe, but the recipe is mutated in place under a stable session id (a /Sessions/Playing/Progress audio switch restarts ffmpeg without re-minting the client's token) and a third-party Jellyfin client cannot be driven to refresh a stale token, so the node must reconstruct from a server-authoritative, node-reachable store. Aligns the comments with docs/architecture/restart-resilient-playback.md §10. Comment-only; no behavior change.
|
Further comments: |
The deny-lease stream-revocation mechanism (the internal/streamauth package, its silo:streamauth:<sid> Redis markers, the proxy Allowed() enforcement, and the admin Stop/Terminate deny write) only ever enforced on the offload-proxy topology and was a silent no-op on the integrated single box and the dedicated transcode node. Rather than ship a partial revocation feature that looks complete but isn't, remove it wholesale and defer a uniform cross-topology revocation design to a dedicated follow-up. Removed: internal/streamauth (package + tests); the LeaseDenier field, StreamLeaseDenier interface, and denyStreamLease helper in playback.go; the admin deny write; the router/main wiring; and the proxy verifyToken Allowed() gate. The unified-reconstruct core (recipe-token, LoadOrReconstructSession) is orthogonal and untouched. Known limitation (now on every topology): admin Terminate and user Stop tear down the live in-memory session and ffmpeg producer, but a still-valid stream token can reconstruct the session until its 24h TTL expires. No node-side byte-withholding ships in this PR. docs/architecture/restart-resilient-playback.md is updated to mark the revocation/deny-lease sections as deferred and to drop the overstated "instant revocation on admin kill" claim.
The authless HLS transcode delivery routes (master.m3u8 / segment) treat the session UUID as the bearer credential, so a real request carries requestUserID == 0. The live serve path already allows this, but ReconstructSession hard-rejected a zero caller, so a request that worked before a restart became SessionMissing -> 404 after the in-memory session was gone, breaking the restart resilience these routes advertise. Match the live-path contract in LoadOrReconstructSession: allow a zero caller (UUID-as-bearer) and refuse only a non-zero caller that mismatches the card owner. The reconstructed session is bound to card.UserID either way. Adds TestReconstructSession_Ownership covering both cases.
A Jellyfin client switching audio on an integrated/local compat transcode restarted live ffmpeg with the new track but did not re-persist PlaybackSession.Recipe. The remote branch already re-persists via startRemoteTranscode -> persistTranscodeRecipe. After a central restart, reconstruct rebuilt ffmpeg from the stale Recipe.AudioTrackIndex, so the integrated session resumed on the original audio track. Persist the updated recipe (best-effort) after a successful Restart in the local branch, mirroring the remote branch, so the durable Recipe.AudioTrackIndex tracks live ffmpeg. Adds a regression test.
proxyToTranscodeNode appended the client's raw query string to the internal transcode-node URL and logged that URL on transport failure. When a remote transcode runs without a separate proxy node, that query carries ?st=<signed JWT> — a 24h bearer reconstruction descriptor exposing the media path and recipe claims — placing the token into internal requests and error logs. Strip the "st" param before building targetURL, preserving any other query params. The token is neither forwarded to the node nor present in the logged URL. Header-forwarding of the token (so the node can reconstruct) is a separate follow-up (#6).
…ruct During the reconstruct wave right after a restart (Postgres under peak load), a transient limit-provider DB error was collapsed into a hard 404, permanently stopping playback for a user within their limits. limitsForUser wrapped any provider error, RegisterReconstructedWithLimits propagated it, and ReconstructSession mapped every error to SessionMissing -> 404 - indistinguishable from a genuine over-cap rejection. Distinguish the two: tag provider errors with a new ErrLimitProviderUnavailable sentinel and, during reconstruct, fail OPEN on a provider error (admit via RegisterReconstructed + log a degraded warning) rather than refuse - mirroring the reliability-first fail-open-on-dependency-error philosophy. A genuine ErrTooManyStreams / ErrTooManyTranscodes over-cap still refuses. Adds tests for both the fail-open and still-refused paths.
The dedicated transcode node's reconstruct path reads the stream token only from the X-Silo-Stream-Token header, but proxyToTranscodeNode forwarded only the node-API bearer token (and #5 now strips st from the URL). So when the central API proxied to the node and the node self-restarted, it could not reconstruct from the recipe-complete native token -> 404. Capture st before stripping it from the URL, verify it at the API boundary (streamtoken.Verify + SessionID match, mirroring the node's own check), and forward it as X-Silo-Stream-Token. Best-effort: a missing/invalid token never blocks the live proxy, and the token is still kept out of the forwarded URL and logs.
A native audio-track switch on an offloaded/remote transcode was a no-op at the node yet returned 200 with a fresh URL: HandleChangeAudioTrack restarted ffmpeg only when the API owned a LOCAL TranscodeSession, so for an offloaded transcode the node kept serving the OLD audio (the node consults the token only on a session miss). The replacement URL was also minted from identity- only claims, so a later node restart 404'd. For the offloaded transcode case (detected via session.TranscodeNodeURL), POST a fresh /transcode/start to the node with the new AudioTrackIndex (handleStart tears down and restarts ffmpeg) and mint the replacement proxy URL from a full RecipeCard so reconstruct survives a node restart. The encode recipe is derived from the durable session target fields plus the file, mirroring HandleStartTranscode. A concrete SegmentDuration (playback.DefaultSegmentDuration) is embedded rather than 0: the node's token completeness gate treats SegmentDuration<=0 as incomplete and falls back to a recipe store the native path never populates, which would 404 on a node restart - the exact resilience this path provides. A failed node POST now surfaces 502 rather than a false 200. Remux and non-offloaded (local) transcode paths keep their prior identity-claim URLs unchanged. Known limitation: Session does not persist the original SegmentDuration or SubtitleTrackIndex/SubtitleBurnIn, so a remote audio switch resets subtitle selection to none and assumes the default segment length; a client that started with a non-default segment length will resegment on switch. Making that state durable on the session is a follow-up.
|
Optional Enhancement:
FB-4 ( All five callers invoke it unlocked: So a restart racing another restart (e.g. audio-switch vs segment-recovery) or a fresh-start/reconstruct can land two ffmpeg processes writing the same segment directory — mixed timelines, Suggest serializing the restart transition under the same LGTM otherwise. |
… lock TranscodeSession.Restart() releases s.mu across cancel -> wait-for-done -> re-exec and spawns ffmpeg into opts.OutputDir without holding the per-session lifecycle lock. LockSessionLifecycle's contract (fresh start, restart, reconstruct) requires restart to hold it too, but all five callers invoked Restart unlocked: native audio-switch and segment-recovery, compat audio-switch and segment-recovery, and the transcode-node segment-recovery. A restart racing another restart (audio-switch vs segment-recovery) or a fresh-start/reconstruct could land two ffmpeg processes writing the same segment directory -- mixed timelines, init.mp4/segment mismatch, and an orphaned-but-still-writing ffmpeg -- the exact concurrent-writer corruption the lifecycle lock exists to prevent. Add RestartSessionLocked (TranscodeManager) and restartSessionLocked (node Server) that hold LockSessionLifecycle only across the cancel->respawn transition, re-check that the handle is still the live mapped session under the lock, and return ErrSessionSuperseded rather than re-spawning a stale handle. Route all five call sites through them. The lock is released before callers wait on segments so recovery latency is unchanged. Tests: gating (restart blocks until the lifecycle lock frees, then spawns), concurrent-restart serialization, and superseded re-check on both the manager (covers native + compat) and node lock owners.
|
Thanks. Implemented the fix. Confirmed on all counts. Fixed in Approach
Tests (as requested, all three surfaces): gating (a restart blocks until the lifecycle lock frees, then spawns a real stub-ffmpeg), concurrent-restart serialization, and superseded re-check — on both the manager helper (covers native + compat) and the node lock owner. Green under Adversarial self-review notes
One deliberate trade-off: a restart now holds the lifecycle lock across
|
|
LGTM ✅ |
…-reconstruct # Conflicts: # cmd/silo/main.go # internal/api/handlers/playback.go # internal/jellycompat/handlers_playback.go # internal/jellycompat/router.go # internal/jellycompat/streams.go # internal/jellycompat/streams_test.go
[PR was a Success] ✅ Restart-resilience verified in production — 6/6 live sessions self-healedOutcome: SUCCESS. This change works as intended under a real restart. Details below. Recreated a running server onto a build carrying this change while real in-flight playback sessions were active (no synthetic setup), and watched them self-heal across the full container replacement. Verified purely from container logs + DB — no client-side instrumentation needed. Result
Timing
Log evidence (identifiers redacted)Edge observed (not a failure of this change)
Reported with AI assistance. |
…pat) (Silo-Server#174) * feat(playback): unified restart-resilient playback via shared TranscodeManager Make direct, remux, and native HLS transcode sessions survive a server restart through one shared flow instead of per-method paths. A missing in-memory session becomes a reconstruct trigger, not a 404: the server rebuilds the session from a tiny durable recipe card plus the position the client re-supplies on its next request. - internal/playback/transcode_manager.go: shared TranscodeManager owning the transcodes map, recipe-card lifecycle, reconstruct single-flight + concurrency cap, LoadOrReconstructSession front door, ReconstructSession / ReconstructTranscode, and orphan cleanup. ~90% is logic moved out of the native handler (no behavior change), not new surface. - internal/playback/recipecard.go + recipecard_postgres.go: RecipeCard with a PlayMethod discriminator (direct/remux/transcode; empty decodes as transcode for back-compat) behind a swappable, nil-safe RecipeStore interface backed by transcode_recipes. - internal/playback/session.go: RegisterReconstructed inserts a rebuilt Session under its existing id (no UUID mint, no limit double-count, race-yielding). - internal/playback/transcode.go: CloseProcess keeps the output dir so a reconstruct winner keeps serving; Close removes it. - internal/api/handlers: drain the transcode lifecycle into the manager; wire reconstruct into the stream/segment serve paths; re-bind ownership to the live caller (refuse userID==0/mismatch); card-aware orphan cleanup. - migrations: add transcode_recipes (expires_at TTL, filter-on-read, indexed). Ownership stays two-factor: an authenticated caller AND a session.UserID that matches; the card stores no secrets and identity is re-resolved per request. Tests: recipe-card round-trip/legacy-decode/disabled-noop, RegisterReconstructed insert/race/concurrency, close-vs-close-process dir semantics, the LoadOrReconstructSession status matrix, and the reconstruct concurrency cap. AI-use: implemented with AI assistance (design, implementation, adversarial review). * feat(jellycompat): reconstruct transcodes across restart via shared manager Bring Jellyfin (jellycompat) HLS playback onto the same restart-resilient flow as the native path. Previously jellycompat owned a separate PlaybackHandler with a private transcodes map and a duplicated transcode lifecycle that never grew the reconstruct half, so an in-flight Jellyfin transcode died on restart and the next segment request 404'd. - Embed the shared playback.TranscodeManager and delete the duplicate lifecycle, so jellycompat gets reconstruct, the concurrency cap, the node-affinity rule, and the card lifecycle for free. - internal/jellycompat/playback_sessions_postgres.go: DurableCompatPlaybackStore, a write-through cache over jellycompat_playback_sessions behind the new CompatPlaybackStore interface (nil pool degrades to cache-only). This persists the load-bearing PlaySessionId -> UpstreamSessionID mapping (plus media sources, route item id, seek) so it survives a restart instead of vanishing with the map. - Write a recipe card on compat transcode start keyed by the upstream session id, using the native StreamAppUserID so the ownership re-bind matches; reconstruct the upstream session and the transcode seeked to the requested seg_NNNNN. - migrations: add jellycompat_playback_sessions (expires_at TTL + compat_token index, full PlaybackSession in data JSONB). Auth is mapped to the native user id before reconstruct so the same two-factor ownership check and userID==0/mismatch refusal apply unchanged. Tests: DB-gated (SILO_TEST_DATABASE_URL) durable-store round-trip proving a session written by one instance reloads in a fresh one (the restart case), plus a nil-pool cache-only path; existing handler tests updated to the manager. AI-use: implemented with AI assistance (design, implementation, adversarial review). * docs(playback): consolidate unified playback reconstruction design Replace the three overlapping playback docs (the native Postgres restart-resilience spec, the jellycompat plan, and the unification spec) with a single self-contained design at docs/superpowers/specs/unified-playback-reconstruct.md. The doc leads with the unified design — the one-idea reconstruct model, a strong visual flow of a restart mid-playback, the shared TranscodeManager + recipe card, the two swappable durable stores, security, the concurrency cap and node-affinity constraint, preconditions, and verification. The design history and rationale (reconstruct-not-rehydrate, phased delivery, Redis-vs-Postgres, token-as- descriptor, failure analysis) move to an appendix. It references no other md file. AI-use: written with AI assistance. * fix(playback): address review on restart-resilient playback Four fixes from PR review of the unified reconstruction work: - Rewrite the recipe card on audio-track change. HandleChangeAudioTrack only updated the in-memory session/transcode, so after a restart reconstruct resumed with the stale AudioTrackIndex/TranscodeAudio (and stale play method) from the start-time card. Re-save the card (direct/remux/transcode) with the switched state, mirroring the start-card pattern. - Guard nil TranscodeManager in LoadOrReconstructSession and ReconstructSession. StreamHandler.TM is documented optional (tests/minimal setups); a missing session previously panicked in recipeEnabled instead of returning SessionMissing. ReconstructTranscode already guarded nil; make the two siblings consistent. - Reject direct/remux cards in doReconstructTranscode before spawning ffmpeg, so a non-transcode card id can never enter the HLS reconstruction path. - Log a non-success status from the remote transcode-node DELETE in CloseTranscodeSession; a 401/404/500 was previously silent. AI-use: implemented with AI assistance. * fix(playback): harden restart-resilient compat sessions * feat(playback): token-carried reconstruction across restarts Build on the shared TranscodeManager (introduced earlier in this branch) so a playback session survives an API-server or transcode-node restart without the client re-negotiating, and retire the Postgres transcode_recipes store in favor of a recipe carried inside the signed stream token. - RecipeCard encodes the byte-affecting encode parameters and rides inside the stream token; LoadOrReconstructSession rebuilds the in-memory Session (and, for integrated transcodes, the ffmpeg process) on a cold miss, single-flighted per session and paced by a spawn semaphore. Removes recipecard_postgres.go and the 20260617233705_add_transcode_recipes migration. - transcodenode reconstructs a lost ffmpeg node-side from the forwarded token. - TR-lease: proxy/streamauth enforce a revocation deny-marker on every served segment, with a 500ms Redis timeout, a bounded per-session "allowed" cache (3s TTL, expiry-first graceful eviction), and a degraded-fail-open counter. Review hardening folded in: - Manifest/segment handlers do the in-memory session lookup first and only verify the stream token on a reconstruct miss (token HMAC was per-segment). - Copy-mode reconstruct never applies the encoded-only seg*dur seek, at spawn time or via the recovery path: RestartSeekTarget reports "unresolved" for a copy session whose manifest cannot yet map the segment, so the client retries instead of seeking to a fabricated source time. - Crash teardown is a compare-and-delete (CloseTranscodeSessionIf returns whether it matched); the crash closure tears down the playback session only when it matched, so a session reconstructed under the same id is not killed. - Reconstruct enforces the same per-user stream/transcode caps as a fresh start (RegisterReconstructedWithLimits), closing a token-replay slot bypass. AI-use disclosure: implemented with AI assistance (Claude Code), including a two-round multi-agent adversarial review whose findings drove the hardening. * feat(jellycompat): node-side transcode reconstruct via shared recipe store Make Jellyfin-compat playback sessions survive a server or transcode-node restart by reusing the shared TranscodeManager reconstruct path and a durable recipe store, on top of the durable compat session store added earlier in this branch. - Node-side transcode reconstruct goes through the shared recipe store; the recipe is persisted to the control-plane store (Redis) when a dedicated transcode node is used so the node can rebuild ffmpeg after its own restart. - Adopt the shared manager's API (3-arg OnFFmpegCrash carrying the dead session, guarded CloseTranscodeSessionIf, RegisterReconstructedWithLimits). Review hardening folded in: - Recipe lifecycle: noderecipe.Store gains Delete, called on deliberate teardown (stop, method-switch discard, node stop/force-reload) so a stopped session cannot be resurrected by a buffered request after a node restart; crash paths intentionally keep the recipe so a resume can reconstruct. - Crash closure tears down the upstream session only when the guarded transcode close matched, so a reconstructed successor is never left orphaned. - Copy-mode segment recovery surfaces a retryable not-found instead of a wrong-position restart, matching the native and node paths. - Durable Update is now a SELECT ... FOR UPDATE transaction, removing the lost-update clobber that could silently drop a transcode recipe. - Empty-token route resolution no longer falls back to an unbounded full-table scan; DB expiry filters bind the injected clock; the redundant re-Get is gone. AI-use disclosure: implemented with AI assistance (Claude Code), including a two-round multi-agent adversarial review whose findings drove the hardening. * docs(playback): consolidate restart-resilient playback design Replace the superpowers spec with a single architecture record describing the token-carried recipe card, the shared TranscodeManager reconstruct path for direct/remux/transcode, the jellycompat durable session + node recipe store, and the revocation-lease model with its fail-open tradeoff. AI-use disclosure: written with AI assistance (Claude Code). * docs(playback): correct jellycompat node-recipe rationale in comments The noderecipe / transcode-node / jellycompat comments justified the Redis recipe store with "a Jellyfin client cannot round-trip a token". The real reason: the node-hop token is server-minted and could carry the recipe, but the recipe is mutated in place under a stable session id (a /Sessions/Playing/Progress audio switch restarts ffmpeg without re-minting the client's token) and a third-party Jellyfin client cannot be driven to refresh a stale token, so the node must reconstruct from a server-authoritative, node-reachable store. Aligns the comments with docs/architecture/restart-resilient-playback.md §10. Comment-only; no behavior change. * refactor(playback): remove deny-lease revocation, defer to future PR The deny-lease stream-revocation mechanism (the internal/streamauth package, its silo:streamauth:<sid> Redis markers, the proxy Allowed() enforcement, and the admin Stop/Terminate deny write) only ever enforced on the offload-proxy topology and was a silent no-op on the integrated single box and the dedicated transcode node. Rather than ship a partial revocation feature that looks complete but isn't, remove it wholesale and defer a uniform cross-topology revocation design to a dedicated follow-up. Removed: internal/streamauth (package + tests); the LeaseDenier field, StreamLeaseDenier interface, and denyStreamLease helper in playback.go; the admin deny write; the router/main wiring; and the proxy verifyToken Allowed() gate. The unified-reconstruct core (recipe-token, LoadOrReconstructSession) is orthogonal and untouched. Known limitation (now on every topology): admin Terminate and user Stop tear down the live in-memory session and ffmpeg producer, but a still-valid stream token can reconstruct the session until its 24h TTL expires. No node-side byte-withholding ships in this PR. docs/architecture/restart-resilient-playback.md is updated to mark the revocation/deny-lease sections as deferred and to drop the overstated "instant revocation on admin kill" claim. * fix(playback): allow zero-caller bearer on transcode reconstruct The authless HLS transcode delivery routes (master.m3u8 / segment) treat the session UUID as the bearer credential, so a real request carries requestUserID == 0. The live serve path already allows this, but ReconstructSession hard-rejected a zero caller, so a request that worked before a restart became SessionMissing -> 404 after the in-memory session was gone, breaking the restart resilience these routes advertise. Match the live-path contract in LoadOrReconstructSession: allow a zero caller (UUID-as-bearer) and refuse only a non-zero caller that mismatches the card owner. The reconstructed session is bound to card.UserID either way. Adds TestReconstructSession_Ownership covering both cases. * fix(jellycompat): re-persist recipe on local audio switch A Jellyfin client switching audio on an integrated/local compat transcode restarted live ffmpeg with the new track but did not re-persist PlaybackSession.Recipe. The remote branch already re-persists via startRemoteTranscode -> persistTranscodeRecipe. After a central restart, reconstruct rebuilt ffmpeg from the stale Recipe.AudioTrackIndex, so the integrated session resumed on the original audio track. Persist the updated recipe (best-effort) after a successful Restart in the local branch, mirroring the remote branch, so the durable Recipe.AudioTrackIndex tracks live ffmpeg. Adds a regression test. * fix(playback): strip stream token from proxied transcode-node URL proxyToTranscodeNode appended the client's raw query string to the internal transcode-node URL and logged that URL on transport failure. When a remote transcode runs without a separate proxy node, that query carries ?st=<signed JWT> — a 24h bearer reconstruction descriptor exposing the media path and recipe claims — placing the token into internal requests and error logs. Strip the "st" param before building targetURL, preserving any other query params. The token is neither forwarded to the node nor present in the logged URL. Header-forwarding of the token (so the node can reconstruct) is a separate follow-up (Silo-Server#6). * fix(playback): fail open on transient limit-provider error in reconstruct During the reconstruct wave right after a restart (Postgres under peak load), a transient limit-provider DB error was collapsed into a hard 404, permanently stopping playback for a user within their limits. limitsForUser wrapped any provider error, RegisterReconstructedWithLimits propagated it, and ReconstructSession mapped every error to SessionMissing -> 404 - indistinguishable from a genuine over-cap rejection. Distinguish the two: tag provider errors with a new ErrLimitProviderUnavailable sentinel and, during reconstruct, fail OPEN on a provider error (admit via RegisterReconstructed + log a degraded warning) rather than refuse - mirroring the reliability-first fail-open-on-dependency-error philosophy. A genuine ErrTooManyStreams / ErrTooManyTranscodes over-cap still refuses. Adds tests for both the fail-open and still-refused paths. * fix(playback): forward stream token to transcode node as header The dedicated transcode node's reconstruct path reads the stream token only from the X-Silo-Stream-Token header, but proxyToTranscodeNode forwarded only the node-API bearer token (and Silo-Server#5 now strips st from the URL). So when the central API proxied to the node and the node self-restarted, it could not reconstruct from the recipe-complete native token -> 404. Capture st before stripping it from the URL, verify it at the API boundary (streamtoken.Verify + SessionID match, mirroring the node's own check), and forward it as X-Silo-Stream-Token. Best-effort: a missing/invalid token never blocks the live proxy, and the token is still kept out of the forwarded URL and logs. * fix(playback): restart node ffmpeg on native remote audio switch A native audio-track switch on an offloaded/remote transcode was a no-op at the node yet returned 200 with a fresh URL: HandleChangeAudioTrack restarted ffmpeg only when the API owned a LOCAL TranscodeSession, so for an offloaded transcode the node kept serving the OLD audio (the node consults the token only on a session miss). The replacement URL was also minted from identity- only claims, so a later node restart 404'd. For the offloaded transcode case (detected via session.TranscodeNodeURL), POST a fresh /transcode/start to the node with the new AudioTrackIndex (handleStart tears down and restarts ffmpeg) and mint the replacement proxy URL from a full RecipeCard so reconstruct survives a node restart. The encode recipe is derived from the durable session target fields plus the file, mirroring HandleStartTranscode. A concrete SegmentDuration (playback.DefaultSegmentDuration) is embedded rather than 0: the node's token completeness gate treats SegmentDuration<=0 as incomplete and falls back to a recipe store the native path never populates, which would 404 on a node restart - the exact resilience this path provides. A failed node POST now surfaces 502 rather than a false 200. Remux and non-offloaded (local) transcode paths keep their prior identity-claim URLs unchanged. Known limitation: Session does not persist the original SegmentDuration or SubtitleTrackIndex/SubtitleBurnIn, so a remote audio switch resets subtitle selection to none and assumes the default segment length; a client that started with a non-default segment length will resegment on switch. Making that state durable on the session is a follow-up. * docs(playback): scrub stale deny-lease/revalidator comments The deny-lease revocation mechanism and its "central revalidator" were removed earlier in this branch, but four comments still described them as live (transcode_manager.go, noderecipe/store.go, streamtoken/token.go, proxy/server.go). Reword them to match the shipped behavior: ownership claims are re-resolved at reconstruct, the noderecipe store shares Redis only with the node-session tracker, and a sub-TTL hard cut depends on a node-side revocation mechanism that is deferred to a future PR. * fix(jellycompat): surface durable playback-session write failures DurableCompatPlaybackStore.Update applied the in-memory mutation and then swallowed every Postgres commit-failure path, returning nil. Callers that promise restart resilience (persistTranscodeRecipe's recipe write, the upstream-session binds in streams.go) were told the session was durably persisted when only the cache held it, so a transient DB hiccup could leave the next restart reloading a stale row (wrong audio track) or 404ing. updateDB now returns the genuine DB round-trip error (begin/query/unmarshal/ marshal/exec/commit); Update propagates it while still applying the in-memory mutation so live state stays correct. A nil pool and a genuinely absent/expired row remain best-effort (return nil) — only real infrastructure failures propagate, so existing rollback paths fire exactly when durability is lost. Part of Silo-Server#174 * fix(playback): re-inject stream token into proxied transcode manifests API-proxied remote transcode manifests dropped the reconstruct token from their segment URLs, so playback died after a node or API restart. When a remote transcode has no separate proxy node, the client loads its manifest via the API-local path; proxyToTranscodeNode strips the signed token ("st") from the forwarded URL (keeping it off node URLs and logs, forwarded only as the X-Silo-Stream-Token header), and the node builds relative segment URIs from that token-less query. The segment URLs the client received carried no token, and the proxy only re-attached the header when an incoming segment request already had "st" — which it never did — so a restart made those segments non-reconstructable and they 404'd. proxyToTranscodeNode now rewrites the manifest body at the boundary: every segment and #EXT-X-MAP init URI gets the client-facing, API-verified token re-appended (new playback.AppendManifestQueryParam helper), so the client's later segment fetches carry "st" again and reconstruct after a restart. The token still never reaches the node URL or its logs. Only 200 .m3u8 responses are rewritten (Content-Length corrected); segments stream through untouched. Part of Silo-Server#174 * fix(playback): preserve subtitle/cadence recipe across offloaded audio switch Switching audio on a remote (offloaded) transcode with burned-in subtitles silently dropped them, and reset a non-default segment cadence. The offloaded audio-switch restart rebuilt the node start request from Session state, but Session/SessionStreamState retained no subtitle or segment-duration state (only the live local ts.Opts() and the RecipeCard did), so the branch hard-coded SubtitleTrackIndex:-1, SubtitleBurnIn:false and SegmentDuration:Default — signing that altered recipe into the replacement stream token. An audio switch then changed bytes beyond audio selection, and any later reconstruct kept the wrong no-subtitle/wrong-cadence recipe. Persist the byte-affecting recipe on the session: SubtitleTrackIndex, SubtitleBurnIn and SegmentDuration are added to Session/SessionStreamState, populated at start (finalizeTranscodeStart) and on post-restart reconstruct (ReconstructSession from the card), carried forward on every audio-switch state update, and read back when rebuilding the offloaded node request and its recipe card. The restart now reproduces the exact live stream. Also resolves the M-4b non-default segment_duration reset. Part of Silo-Server#174 * fix(playback): serialize transcode spawn paths with a per-session lock Reconstruct was single-flighted only against other reconstructs, so a restart-driven segment reconstruct racing a quality/seek/audio fresh start could spawn two ffmpeg processes writing the same output directory at once — segment corruption, partial-write closes, orphaned processes, and skewed active-job accounting. The atomic register-after-spawn (GetOrRegister / the reconstruct compare-on-register) prevented a map leak but not the concurrent disk writers, because the losing path had already spawned. The dedicated transcode node had the same split between handleStart and spawnReconstruct. Add a refcounted per-session lifecycle lock to both TranscodeManager and the node Server, held across "check existing -> spawn -> register": - reconstruct (doReconstructTranscode / spawnReconstruct) re-checks under the lock and yields to any live session instead of spawning a duplicate; - the native and jellycompat fresh-start paths take the lock around their spawn+register (the native path also closes any session a reconstruct rebuilt in the meantime so its fresh ffmpeg is the sole writer); - the node handleStart holds it across teardown+spawn+register. The refcount drops the map entry once no path holds/waits, keeping it bounded. GetOrRegisterTranscodeSession is removed — the lock supersedes it and keeping a register-after-spawn primitive would invite reintroducing the race. Part of Silo-Server#174 * fix(playback): serialize restart re-spawn under the session lifecycle lock TranscodeSession.Restart() releases s.mu across cancel -> wait-for-done -> re-exec and spawns ffmpeg into opts.OutputDir without holding the per-session lifecycle lock. LockSessionLifecycle's contract (fresh start, restart, reconstruct) requires restart to hold it too, but all five callers invoked Restart unlocked: native audio-switch and segment-recovery, compat audio-switch and segment-recovery, and the transcode-node segment-recovery. A restart racing another restart (audio-switch vs segment-recovery) or a fresh-start/reconstruct could land two ffmpeg processes writing the same segment directory -- mixed timelines, init.mp4/segment mismatch, and an orphaned-but-still-writing ffmpeg -- the exact concurrent-writer corruption the lifecycle lock exists to prevent. Add RestartSessionLocked (TranscodeManager) and restartSessionLocked (node Server) that hold LockSessionLifecycle only across the cancel->respawn transition, re-check that the handle is still the live mapped session under the lock, and return ErrSessionSuperseded rather than re-spawning a stale handle. Route all five call sites through them. The lock is released before callers wait on segments so recovery latency is unchanged. Tests: gating (restart blocks until the lifecycle lock frees, then spawns), concurrent-restart serialization, and superseded re-check on both the manager (covers native + compat) and node lock owners. --------- Co-authored-by: Quick <[email protected]>
Commits that make every video playback session — native and Jellyfin — survive a server restart, a horizontal-scale front-end that never held the session, and a dedicated node reboot, through one shared reconstruct flow. The reconstruction recipe rides the client's signed stream token (no shared per-session store on a single box).
Update — revocation deferred, plus post-review fixes
A re-review pass tightened the reconstruct paths and removed the revocation mechanism from this PR. One concern per commit:
Why revocation was pulled. The deny-marker only ever did anything on the multi-node offload setup, and was a silent no-op on the common single-box server and on dedicated transcode nodes. Rather than ship a kill switch that looks complete but isn't — and grow an already-large PR — the whole mechanism was removed and handed to a dedicated follow-up that will do revocation the same way on every topology. Today, admin Terminate and user Stop still tear down the live session and its encoder, but a client holding a still-valid stream token could rebuild that one session until the token expires (≤24h). It's a narrow edge case, scoped to a single already-authorized stream, and is the reason it's being deferred rather than rushed.
Full design — the problem, the two design axes, the full options comparison, why each alternative was set aside, the chosen design, diagrams, preconditions, and the per-role restart-resiliency matrix:
docs/architecture/restart-resilient-playback.md.Problem
Playback died on every server restart. When an operator restarted Silo (a deploy, a
docker compose down/up, or a crash) while someone was watching, the viewer's player kept playing from its buffer for a minute or two — and then stopped dead. The server came back with no memory of who was watching or what they were watching, so the next chunk request was answered with "not found." On the operator's side this looked like a wave of playback failures clustered right after every restart; in the logs it was a burst of 404s on segment and stream requests for sessions that had been healthy seconds earlier.It also broke the moment you ran more than one server. The same "not found" happened whenever a request landed on a front-end that had never held the session — a second instance behind a load balancer, or a dedicated transcode node that had rebooted. Playback was only ever reliable on a single, never-restarted box.
Only direct play survived, and only by accident. Silo serves video four ways — direct play, remux, native HLS transcode, and the Jellyfin-compatibility path that Jellyfin apps (Jellyfin Web, Streamyfin, Infuse, and others) use. Direct play kept working across restarts only because it serves raw byte ranges and holds no server-side session to lose. Remux, native HLS transcode, and the entire Jellyfin path all died. The Jellyfin path made it worse: it carried a second, independent copy of the playback machinery, so the problem had to be solved twice.
Operators also had no reliable way to cut off a stream. Once a stream was being served from an offload node, an admin "Stop" relied on the client cooperating. A non-cooperative client holding a still-valid stream URL could keep pulling bytes, because the node verified the URL's signature and served — there was no way to revoke an in-flight node-served stream.
Solution
The core idea (design doc §2): a client always re-requests the next chunk after an outage, and that request already states where the client is — an HTTP
Range, a?seek=, or aseg_NNNNNsegment number. So the server never needs to remember a live session; it rebuilds it on the next request from a small durable descriptor (identity, ownership, and the byte-affecting encode "recipe") plus the position the client supplies. A missing in-memory session becomes a reconstruct trigger, not a 404. Nothing live is serialized — no ffmpeg process, context, or channel. The client's buffer is the reconstruction budget.The work split into a reconstruct core and then an evolution of where the descriptor lives and how revocation is bounded. The core was kept throughout; the storage and revocation model changed.
The shared reconstruct core (
feat(playback): unified restart-resilient playback via shared TranscodeManager,feat(jellycompat): reconstruct transcodes across restart via shared manager)playback.TranscodeManager(internal/playback/transcode_manager.go): the transcodes map, theLoadOrReconstructSessionfront door,ReconstructSession/ReconstructTranscode, a per-session single-flight plus areconstructSemconcurrency cap that paces the post-restart thundering herd,RegisterReconstructed(re-inserts a rebuilt session under its existing id — no fresh UUID, no double-counting the concurrency limit), and theCloseProcess/Closesplit. Most of it is logic moved out ofinternal/api/handlers/playback.go, so the native handler shed surface rather than grew.RecipeCard(internal/playback/recipecard.go) with aPlayMethoddiscriminator (direct/remux/transcode) is the descriptor: one card and one reconstruct path, differing only in the per-method runtime rebuilt on demand. Tier-1 (direct/remux) is a stateless re-serve; Tier-2 (transcode) rebuilds ffmpeg seeked to the requested segment (fast path: a surviving segment on a persistentTranscodeDiris served with no re-encode).internal/jellycompatembeds the sameTranscodeManagerand deletes its private transcodes map and duplicated lifecycle, retiring the second copy of the machinery.session.UserIDto the live authenticated caller and refuses onuserID == 0or a session-id mismatch — it never trusts a stored id alone (internal/api/handlers/stream.go,playback.go).Token-carried reconstruction — the recipe rides the token, Postgres recipe table retired (
feat(playback): token-carried reconstruction; retire transcode_recipes)transcode_recipesPostgres row. That coupled reconstruction to a shared DB (a write on every start and per audio/quality change) and gave no single-box zero-dependency property. It was replaced by a client-carried signed stream token as the durable descriptor, andPostgresRecipeStore, theRecipeStoreinterface, and the unmergedtranscode_recipesmigration were deleted.streamtoken.Claims(internal/streamtoken/token.go) now carries the full byte-affecting recipe plusuid/pid/mfidownership lookup keys.playback.RecipeCardprojects to/from claims (ToClaims/RecipeCardFromClaims); theReconstruct*front door takes the decoded recipe instead of reading Postgres.HWAccel/HWDeviceare deliberately not carried — they re-resolve from live config, so an operator config change applies to reconstructed sessions too.?st=; the manifest rewriter already appendsRawQueryonto segment URIs, so segments inherit it with no route change (internal/api/handlers/playback.go,stream.go). The integrated server is hit directly (no query-stripping proxy in front), so a query param is safe there; the proxy/node path keeps the token in the URL path.Durable compat store for the Jellyfin path (
feat(jellycompat): reconstruct transcodes across restart via shared manager,fix(playback): harden restart-resilient compat sessions)?sttoken, so the compat layer keeps its own durable per-session state.DurableCompatPlaybackStore(internal/jellycompat/playback_sessions_postgres.go) is a write-through cache over the newjellycompat_playback_sessionstable (migration..._add_jellycompat_playback_sessions.sql), behind aCompatPlaybackStoreinterface (a nil pool degrades to cache-only).PlaySessionId → UpstreamSessionIDmapping, the media sources, the route item id, the seek, and — folded into the sameUpdatethat flipsTranscodeStarted— the encodeRecipe. This makes all compat methods resilient: compat direct/remux are stateless re-serves whose only failure was the now-durable session lookup; compat HLS reconstructs the transcode from the stored recipe.Admin revocation — server-side session-deny marker (
feat(playback): TR-lease — node session-deny for stream revocation)silo:streamauth:<sid> = denyto Redis (TTL ≥ the 24h token lifetime) viaPlaybackHandler.LeaseDenier(internal/api/handlers/admin_playback_control.go), and the offload node consults it before serving any bytes —403, no bytes, on a hit (internal/proxy/server.goverifyToken).internal/streamauthis a deny-only Redis store:Deny(sid)plus a fail-openAllowed(sid). No poller, no allow-leases, no access re-resolver — an earlier iteration that re-resolved every active stream on a ~2-min timer was cut as constant DB load for a rare case./playback/start, and cooperative clients stop over the realtime WebSocket — so the marker covers only the explicit, session-scoped kill of a non-cooperative node-served stream. Enforcement is byte-withholding, not client cooperation. Fail-open on absence or a Redis error (reliability over revocation latency).nodesessions.SessionInfo(internal/nodesessions/tracker.go) now carriesauth_user_id/profile_id/media_file_idfrom the verified token, enriching the live admin "active streams" view with who/what.Node-side reconstruct after a transcode-node reboot (
feat(playback): node-side reconstruct — token-carried recovery…,feat(jellycompat): node-side transcode reconstruct via shared recipe store)X-Silo-Stream-Token; on a manifest/segment miss the node re-verifies it, decodes the recipe, and self-reconstructs ffmpeg seeked to the requested segment — single-flighted and concurrency-capped exactly like the integrated reconstruct, and refused for a missing/forged token, session-id mismatch, or a non-transcode card (internal/transcodenode/server.go).internal/noderecipe, keyedsilo:noderecipe:<upstreamSessionID>, TTL = max token TTL), and the node reads it on the reconstruct miss — over the same Redis the deny-lease and session tracker already use, so the node needs no central URL. Reads fail closed (absent/forged/wrong-session → 404, no spawn); writes no-op without Redis (single-box safe). Integrated transcodes reconstruct on central from the token and need no handoff.Review hardening (
fix(playback): address review…, ×3) and docsfix(playback): address review on restart-resilient playback,fix(playback): harden restart-resilient compat sessions, andfix(playback): address PR review — signed reconstruct URL, atomic cleanup snapshot, conservative age-gate: a signed reconstruct URL on audio-track switch (so a post-restart reconstruct resumes with the switched track, not the stale token), an atomic live-map + in-flight-set snapshot under both locks inCleanupOrphanedTranscodes(so a session migrating between them is never reaped while live), and a conservative age-gate that retains a dir whose age can't be stat'd (internal/playback/transcode_cleanup.go).docs(playback): consolidate restart-resilient playback design into one recordfolds four working notes into the single self-containeddocs/architecture/restart-resilient-playback.md, tracing the evolution to TR-lease so a future engineer sees how the decision was reached. (It supersedes the earlierdocs(playback): consolidate unified playback reconstruction designcommit, which is why two doc-consolidation commits appear in the history.)Risk / follow-ups
--mode=transcodenodes (node affinity routes every front-end to the same node).TranscodeDirrecommended. With an ephemeral dir, reconstruct still works but re-transcodes from the requested segment instead of serving surviving segments — slower, must beat the buffer runway on worst-case hardware. Config/deployment step, not code.JWTSecretsigns native auth, the stream token, and the node bearer; a node-secret leak could forge native logins. Accepted on the trusted-node precondition; deferred hardening is to split the stream-token secret and move to asymmetric signing before any untrusted/edge node (doc §9 E, §10).noderecipekey surviving (≤24h TTL).web/src/player/components/VideoPlayer.tsx— retry policies on manifest/playlist/fragment loads plus a fatal-NETWORK_ERRORhls.startLoad()loop). Remaining client work is insilo-android/silo-appleand third-party Jellyfin clients, which must retry segment/manifest GETs on 5xx/connection error and reconnect the WebSocket for this to be visible to users. The token rides the URL, so no extra client logic is needed to carry it.Verification
go build ./...andgo vetclean oninternal/playback,internal/jellycompat,internal/noderecipe,internal/transcodenode,internal/proxy,internal/api.go build ./...,go vet, and theinternal/playback,internal/jellycompat,internal/proxy, andinternal/api/handlerstest suites all pass (the handler suite, including the new offloaded-audio-switch test, was run in a libvips/CGO-capable environment). New tests added for the zero-caller reconstruct, the fail-open-on-provider-error path, the local jellycompat recipe re-persist, and the recipe-complete remote-audio-switch token.recipecard_test.go),RegisterReconstructedinsert/race/concurrency and theLoadOrReconstructSessionstatus matrix (reconstruct_test.go,transcode_manager_test.go), close-vs-close-process directory semantics (transcode_close_test.go), cleanup atomic-snapshot and conservative age-gate (cleanup_test.go), thenoderecipenil-store no-op + namespacing + TTL and the node fetch-path guards — store miss / incomplete recipe / wrong-session recipe all 404 without spawning (noderecipe/store_test.go,transcodenode/server_test.go), and aSILO_TEST_DATABASE_URL-gated compat-store round-trip proving a session written by one instance reloads in a fresh one (playback_sessions_postgres_test.go).go test ./...skips the CGOinternal/api/handlerspackage.docker compose down/up(<60s) mid-playback for native direct, remux, transcode, and a Jellyfin HLS client; confirm reconstruct instead of 404. Repeat with an ephemeral vs persistentTranscodeDir, and a multi-node topology with a proxy-node and a transcode-node restart (including an audio switch on an offloaded transcode, then a node reboot — expect the stream to resume on the switched track, not a 404).AI-use disclosure
Designed and implemented with AI assistance (design exploration, the options comparison, implementation, commit reorganization, and several adversarial multi-agent review passes — the most recent of which caught and fixed a token that could not actually reconstruct after a node reboot). Code references were verified against the tree at authoring time.
Summary by CodeRabbit