Skip to content

feat(playback): unified restart-resilient playback (native + jellycompat) - #174

Merged
Quick104 merged 23 commits into
mainfrom
feat/unified-playback-reconstruct
Jul 2, 2026
Merged

Quick104 merged 23 commits into
mainfrom
feat/unified-playback-reconstruct

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

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 since review — please read first. Admin revocation has been pulled from this PR and deferred to a focused follow-up. Every section below that describes a "session-deny marker", a deny-lease, or a hard 403 cut (notably Admin revocation — server-side session-deny marker, and the revocation lines in Risk and Verification) describes a mechanism that no longer ships in this PR. See the Update section immediately below for what changed and why.

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:

  • Reconstruct no longer drops a within-limits viewer after a restart. If the limits database had a brief hiccup during the post-restart reconnect wave, the server used to treat it as "over your limit" and 404 the stream for good. It now admits and meters instead of failing closed.
  • Auth-optional HLS transcode routes survive a restart again. These routes use the session UUID itself as the credential (no separate login per chunk). Reconstruct was rejecting that "no user" case and 404ing after a restart; it now accepts it like the live path does, still bound to the token's real owner.
  • A Jellyfin audio-track switch on a single-box server now sticks across a restart. The local switch restarted the live encoder but forgot to save the new track, so a restart resumed on the original audio. It now saves the updated recipe, matching the multi-node path.
  • Switching audio on an offloaded (remote-node) transcode actually changes the audio. Previously the handler returned success without telling the worker node to switch, so the old track kept playing — and a later node reboot turned that stream into a 404. It now restarts the node's encoder on the new track and hands back a URL that can rebuild itself after a reboot.
  • The signed stream token no longer leaks into internal URLs or error logs. It's stripped from the URL the server forwards to a worker node (and from the failure log line), and passed as a header instead — which doubles as the missing piece that lets a node rebuild a stream after it reboots.

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 a seg_NNNNN segment 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)

  • Extracted the transcode lifecycle into one shared playback.TranscodeManager (internal/playback/transcode_manager.go): the transcodes map, the LoadOrReconstructSession front door, ReconstructSession / ReconstructTranscode, a per-session single-flight plus a reconstructSem concurrency 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 the CloseProcess/Close split. Most of it is logic moved out of internal/api/handlers/playback.go, so the native handler shed surface rather than grew.
  • A RecipeCard (internal/playback/recipecard.go) with a PlayMethod discriminator (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 persistent TranscodeDir is served with no re-encode).
  • internal/jellycompat embeds the same TranscodeManager and deletes its private transcodes map and duplicated lifecycle, retiring the second copy of the machinery.
  • Ownership stays two-factor: reconstruct re-binds session.UserID to the live authenticated caller and refuses on userID == 0 or 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)

  • The first iteration of the core stored the recipe in a transcode_recipes Postgres 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, and PostgresRecipeStore, the RecipeStore interface, and the unmerged transcode_recipes migration were deleted.
  • streamtoken.Claims (internal/streamtoken/token.go) now carries the full byte-affecting recipe plus uid/pid/mfid ownership lookup keys. playback.RecipeCard projects to/from claims (ToClaims / RecipeCardFromClaims); the Reconstruct* front door takes the decoded recipe instead of reading Postgres. HWAccel/HWDevice are deliberately not carried — they re-resolve from live config, so an operator config change applies to reconstructed sessions too.
  • Native serve URLs carry the token as ?st=; the manifest rewriter already appends RawQuery onto 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.
  • Why: rebuilding from the client-re-presented token avoids serializing live runtime objects, removes the per-start DB write, and gives the single-box deployment zero external dependency for reconstruction.

Durable compat store for the Jellyfin path (feat(jellycompat): reconstruct transcodes across restart via shared manager, fix(playback): harden restart-resilient compat sessions)

  • A Jellyfin client cannot round-trip a native ?st token, 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 new jellycompat_playback_sessions table (migration ..._add_jellycompat_playback_sessions.sql), behind a CompatPlaybackStore interface (a nil pool degrades to cache-only).
  • It persists the load-bearing PlaySessionId → UpstreamSessionID mapping, the media sources, the route item id, the seek, and — folded into the same Update that flips TranscodeStarted — the encode Recipe. 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)

  • Carrying the recipe on the client means a still-valid 24h token can outlive an admin's intent to kill a stream. So admin Stop/Terminate writes a per-session deny marker silo:streamauth:<sid> = deny to Redis (TTL ≥ the 24h token lifetime) via PlaybackHandler.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.go verifyToken).
  • internal/streamauth is a deny-only Redis store: Deny(sid) plus a fail-open Allowed(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.
  • Scope is deliberate (doc §7): new playback is already gated at /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 carries auth_user_id/profile_id/media_file_id from 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)

  • Native: the proxy forwards the verified stream token to the transcode node as 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).
  • Jellycompat: the node-hop token is identity-only (the recipe can't round-trip a Jellyfin client), so central writes the recipe to a shared Redis recipe store at remote-transcode start (internal/noderecipe, keyed silo: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 docs

  • fix(playback): address review on restart-resilient playback, fix(playback): harden restart-resilient compat sessions, and fix(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 in CleanupOrphanedTranscodes (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 record folds four working notes into the single self-contained docs/architecture/restart-resilient-playback.md, tracing the evolution to TR-lease so a future engineer sees how the decision was reached. (It supersedes the earlier docs(playback): consolidate unified playback reconstruction design commit, which is why two doc-consolidation commits appear in the history.)

Risk / follow-ups

  • Not unconditional. Resilience requires the client to retry the failed request and reconnect the WebSocket; without retry the server-side reconstruct is invisible. An outage longer than the 24h token TTL won't resume. Documented as preconditions (doc §11).
  • Passive revocation is bounded by the token, not hard-cut. A passive ban or partial access change (lost a library, lowered rating) does NOT hard-revoke an already-running, non-cooperative node-served stream — it is enforced at next play and otherwise bounded by the ≤24h token. Only the explicit admin kill is instant on the node path (doc §7, §10).
  • Integrated-transcode split-brain. An integrated transcode (no remote node) spread across multiple front-ends without sticky affinity can split-brain into divergent ffmpeg runs; the descriptor carries no owning-node id yet (deferred). Safe on a single front-end, with LB session affinity, or with dedicated --mode=transcode nodes (node affinity routes every front-end to the same node).
  • Persistent TranscodeDir recommended. 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.
  • Signing-key blast radius. One JWTSecret signs 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).
  • No durable per-session history. Token-carried reconstruction deliberately drops the durable per-session recipe record (the trade for zero-dependency single-box). Live "who is watching now" is covered by the Redis node tracker; historical/audit lives in the separate watch-progress system.
  • Multi-node precondition. Central and the nodes must share one Redis (already required for the session tracker). Node-side jellycompat reconstruct additionally depends on the noderecipe key surviving (≤24h TTL).
  • Client coordination. The web player already recovers for HLS (web/src/player/components/VideoPlayer.tsx — retry policies on manifest/playlist/fragment loads plus a fatal-NETWORK_ERROR hls.startLoad() loop). Remaining client work is in silo-android / silo-apple and 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 ./... and go vet clean on internal/playback, internal/jellycompat, internal/noderecipe, internal/transcodenode, internal/proxy, internal/api.
  • Post-review fixes verified: go build ./..., go vet, and the internal/playback, internal/jellycompat, internal/proxy, and internal/api/handlers test 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.
  • Unit + race coverage: recipe-card round-trip / claims projection / legacy decode (recipecard_test.go), RegisterReconstructed insert/race/concurrency and the LoadOrReconstructSession status 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), the noderecipe nil-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 a SILO_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).
  • Run Go tests in a libvips/CGO-capable container per the repo pre-push checklist — a bare-host go test ./... skips the CGO internal/api/handlers package.
  • Manual plan: 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 persistent TranscodeDir, 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

  • New Features
    • Playback sessions now recover after server restarts using signed reconstruction tokens, improving continuity for direct play, remux, and transcodes.
    • Added durable Jellyfin-compat playback session storage with optional Postgres backing for restart resilience.
    • Added restart-resilient recipe handoff to support reconstruction by downstream nodes.
  • Bug Fixes
    • Admin Stop/Terminate now more proactively revokes access so already-issued streams are cut off on subsequent requests.
  • Documentation
    • Added an architecture guide for restart-resilient playback.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Implements "TR-lease" restart-resilient playback by introducing a RecipeCard model persisted in JWT stream tokens and Jellycompat durable storage, a shared TranscodeManager that reconstructs sessions/transcodes on demand via RecipeCard, a Redis deny-marker store for admin session revocation, and a noderecipe Redis handoff store for transcode nodes. Reconstruction paths are wired across native handlers, Jellycompat handlers, the proxy, and the dedicated transcode node server.

Changes

TR-lease Restart-Resilient Playback

Layer / File(s) Summary
RecipeCard, token serialization, and transcode close semantics
internal/playback/recipecard.go, internal/playback/recipecard_test.go, internal/playback/transcode.go, internal/playback/transcode_close_test.go, internal/playback/transcode_cleanup.go, internal/streamtoken/token.go
RecipeCard struct and constructor helpers (NewRecipeCard, NewDirectRecipeCard, NewRemuxRecipeCard) for transcode/direct/remux play methods; ToClaims/RecipeCardFromClaims for token round-tripping with back-compat; MaxTokenTTL constant (24h); TranscodeSession.CloseProcess() preserves output dir alongside existing Close() deletion; CleanupOrphanedTranscodeDirs accepts minAge to spare recently-modified directories.
SessionManager.RegisterReconstructed
internal/playback/session.go, internal/playback/reconstruct_test.go
RegisterReconstructed re-inserts a session under its existing ID after in-memory loss, yields to existing entries on collision, normalizes timestamps; covered by insert, collision, and concurrent tests.
TranscodeManager orchestration
internal/playback/transcode_manager.go, internal/playback/transcode_manager_test.go
TranscodeManager with thread-safe transcode registry, per-session singleflight reconstruct, CPU-bounded semaphore, LoadOrReconstructSession returning SessionLoadStatus, ReconstructSession, ReconstructTranscode, MonitorLocalTranscodeExit, CloseTranscodeSession (including remote HTTP DELETE with bearer token), and CleanupOrphanedTranscodes.
Redis lease and recipe stores
internal/streamauth/lease.go, internal/streamauth/lease_test.go, internal/noderecipe/store.go, internal/noderecipe/store_test.go, internal/nodesessions/tracker.go
streamauth.Store deny-marker persistence with Deny and Allowed (fail-open) semantics and DefaultDenyTTL; noderecipe.Store for transcode-node recipe handoff; SessionInfo gains AuthUserID/ProfileID/MediaFileID ownership fields.
CompatPlaybackStore interface and DurableCompatPlaybackStore+Postgres
internal/jellycompat/playback_sessions.go, internal/jellycompat/playback_sessions_postgres.go, internal/jellycompat/playback_sessions_postgres_test.go, migrations/sql/20260618053223_add_jellycompat_playback_sessions.sql
Recipe field added to PlaybackSession; CompatPlaybackStore interface standardizing session persistence operations; DurableCompatPlaybackStore with write-through/read-through Postgres cache and DeleteExpired; jellycompat_playback_sessions table with indexes on expires_at and compat_token.
Native stop flow: userInitiated and stream lease denial
internal/api/handlers/playback_realtime.go, internal/api/handlers/admin_playback_control.go, internal/api/handlers/session_ws.go, internal/api/router.go
userInitiated bool propagated through stopPlaybackSession/stopPlaybackSessionByID and call sites; denyStreamLease called before Stop/Terminate dispatch; StreamLeaseDenier interface introduced for lease revocation integration; router wires LeaseDenier from Redis when available.
Native PlaybackHandler and StreamHandler reconstruction
internal/api/handlers/playback.go, internal/api/handlers/stream.go, internal/api/handlers/playback_test.go
Handler-local transcode maps replaced by shared TranscodeManager; signed RecipeCard embedded in stream URLs via stream-token helpers (signSessionToken, streamCardFromQuery, appendStreamToken); manifest/segment/transcode handlers use LoadOrReconstructSession and ReconstructTranscode; StreamHandler gains TM field; tests updated to access transcode sessions via tm.GetTranscodeSession.
Jellycompat handler reconstruction and recipe persistence
internal/jellycompat/handlers_playback.go, internal/jellycompat/streams.go, internal/jellycompat/auth.go, internal/jellycompat/audio_selection_test.go, internal/jellycompat/streams_test.go, internal/jellycompat/remote_transcode_reconstruct_test.go, internal/jellycompat/playback_4k_test.go
Jellycompat transcode maps replaced by shared TranscodeManager; HandleHLSSegment loads/reconstructs upstream session and transcode; ensureUpstreamPlayback reconstructs stale upstream native sessions; ensureTranscodeSession uses atomic GetOrRegisterTranscodeSession with race-safe registration, persists Recipe and TranscodeStarted to compat store with rollback, starts exit monitoring, best-effort writes recipe to RecipeNodeStore for remote transcodes; comprehensive restart/rollback test coverage.
Jellycompat router, server, and cleanup integration
internal/jellycompat/router.go, internal/jellycompat/server.go, internal/jellycompat/cleanup.go, internal/jellycompat/cleanup_test.go
PlaybackStore defaults to DurableCompatPlaybackStore when DB present; startup orphan cleanup added; Dependencies.PlaybackStore typed as CompatPlaybackStore; periodic cleanup extended to include playbackSessionExpirer interface for durable session deletion alongside auth deletions.
Proxy lease enforcement and transcode-node reconstruction
internal/proxy/server.go, internal/transcodenode/server.go, internal/transcodenode/server_test.go
Proxy adds leases store; verifyToken checks Allowed and rejects 403 on deny; X-Silo-Stream-Token forwarded to nodes; transcode node adds reconstructFromToken validation and ffmpeg rebuild, spawnReconstruct with semaphore-bounded concurrent spawn, SetRecipeStore for optional jellycompat recipe fetch, manifest/segment handlers reconstruct on missing sessions.
Application entry point wiring
cmd/silo/main.go
leaseStore wired into proxy.NewServer for lease enforcement; transcode server SetRecipeStore called with noderecipe.NewStore; Jellycompat compatDeps extended with RecipeNodeStore for node restart recovery.
TR-lease architecture documentation
docs/architecture/restart-resilient-playback.md
Comprehensive design document: problem statement, TR-lease specification, design option comparison, token-carried reconstruction rules, deny-marker enforcement, implementation summary, preconditions, topology/sequence diagrams, and resiliency behavior matrix.
Web client stream-URL query parameter handling
web/src/player/stream-url.ts, web/src/player/stream-url.test.ts
Updates buildPlayerStreamUrl to preserve existing query parameters (including ?st=) and conditionally add token/seek parameters using proper & vs ? separators; comprehensive Vitest coverage of concatenation and preservation rules.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • Silo-Server/silo-server#126: Modifies the same buildProxyManifestURL helper in internal/api/handlers/playback.go that this PR rewrites to accept a RecipeCard and proxy node.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: unified restart-resilient playback across native and Jellyfin-compat paths through the TR-lease design.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/unified-playback-reconstruct

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (3)
docs/superpowers/specs/unified-playback-reconstruct.md (1)

62-62: 💤 Low value

Add 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: text for ASCII diagrams, yaml for YAML examples, etc.

🔧 Proposed fixes for fenced code blocks

Line 62 (ASCII diagram):

-    ```
+    ```text
                         ┌──────────────────────────────────────────┐

Line 88 (ASCII diagram):

-    ```
+    ```text
    Watching here              Bucket filled to here

Line 100 (ASCII diagram):

-    ```
+    ```text
  SERVER:  UP ───────────────✕ DOWN (≤60s) ✕──────────────── UP again

Line 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 yaml identifier, 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 lift

Resolve the HWAccel/HWDevice contract 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 value

Consider adding transcode directory to cleanup log messages for consistency.

The native handler logs "dir", deps.Config.Playback.TranscodeDir in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 381136a and 46bdaa3.

📒 Files selected for processing (29)
  • docs/superpowers/specs/unified-playback-reconstruct.md
  • internal/api/handlers/admin_playback_control.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_realtime.go
  • internal/api/handlers/playback_test.go
  • internal/api/handlers/session_ws.go
  • internal/api/handlers/stream.go
  • internal/api/router.go
  • internal/jellycompat/audio_selection_test.go
  • internal/jellycompat/auth.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/playback_sessions.go
  • internal/jellycompat/playback_sessions_postgres.go
  • internal/jellycompat/playback_sessions_postgres_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/jellycompat/streams_test.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_postgres.go
  • internal/playback/recipecard_test.go
  • internal/playback/reconstruct_test.go
  • internal/playback/session.go
  • internal/playback/transcode.go
  • internal/playback/transcode_close_test.go
  • internal/playback/transcode_manager.go
  • internal/playback/transcode_manager_test.go
  • migrations/sql/20260617233705_add_transcode_recipes.sql
  • migrations/sql/20260618053223_add_jellycompat_playback_sessions.sql

Comment thread internal/api/handlers/playback.go Resolved
Comment thread internal/playback/transcode_manager.go Resolved
Comment thread internal/playback/transcode_manager.go Resolved
Comment thread internal/playback/transcode_manager.go Resolved
CoffeeKnyte and others added 5 commits June 19, 2026 12:56
…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.
@CoffeeKnyte
CoffeeKnyte force-pushed the feat/unified-playback-reconstruct branch from 523569e to c122646 Compare June 19, 2026 13:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Mirror start-playback remux planning in audio changes.

The start path treats PlayRemux as needing a transcode node and returns /stream/transcode/{token}/master.m3u8. This audio-change path only sets needsTranscode for PlayTranscode and 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 | 🔴 Critical

Use userInitiated to revoke token-carried resumes.

userInitiated is passed to finalizeSessionStop but 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 calls denyStreamLease before stopPlaybackSessionByID, 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: Put method intentionally uses fail-open semantics with explicit error logging.

The Put method writes to the in-memory cache first, then attempts to persist to the database via upsert(). 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 making Put return 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.go
  • docs/architecture/restart-resilient-playback.md
  • internal/api/handlers/admin_playback_control.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_realtime.go
  • internal/api/handlers/playback_test.go
  • internal/api/handlers/session_ws.go
  • internal/api/handlers/stream.go
  • internal/api/router.go
  • internal/jellycompat/audio_selection_test.go
  • internal/jellycompat/auth.go
  • internal/jellycompat/cleanup.go
  • internal/jellycompat/cleanup_test.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/playback_sessions.go
  • internal/jellycompat/playback_sessions_postgres.go
  • internal/jellycompat/playback_sessions_postgres_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/jellycompat/streams_test.go
  • internal/noderecipe/store.go
  • internal/noderecipe/store_test.go
  • internal/nodesessions/tracker.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/reconstruct_test.go
  • internal/playback/session.go
  • internal/playback/transcode.go
  • internal/playback/transcode_cleanup.go
  • internal/playback/transcode_close_test.go
  • internal/playback/transcode_manager.go
  • internal/playback/transcode_manager_test.go
  • internal/proxy/server.go
  • internal/streamauth/lease.go
  • internal/streamauth/lease_test.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/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

Comment thread internal/api/handlers/playback.go Resolved
Comment thread internal/playback/recipecard.go Resolved
Comment thread internal/playback/transcode_cleanup.go Resolved
Comment thread internal/playback/transcode_manager.go Resolved
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Design evolution since the original three commits

The 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 transcode_recipes card store (and its RecipeStore interface and migration) is retired. The byte-affecting encode recipe, plus the uid/pid/mfid ownership keys, now travel inside the client-carried signed stream token (streamtoken.Claims). A front-end that lost its in-memory session rebuilds ffmpeg from the token the client re-presents on the next request — no shared per-session store and zero external dependency for reconstruction on a single box. Native serve URLs carry it as ?st=; the manifest rewriter already propagates RawQuery onto segment URIs, so segments inherit it with no route change.

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 403 with no bytes on a hit. It's a deny-only, fail-open store (internal/streamauth): an absent marker or a Redis error serves; only an explicit deny withholds. This covers the one revocation case the offloaded topology couldn't otherwise handle — the hard cut of a non-cooperative, node-served stream with no local producer to kill. New playback is already gated at /playback/start and cooperative clients stop over the WebSocket.

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 --mode=transcode node, a node restart left a Jellyfin HLS stream with an identity-only node-hop token and nothing to rebuild from. So at remote transcode start, central hands the recipe to the node over the shared Redis the deny-lease and session tracker already use (internal/noderecipe, keyed silo:noderecipe:<upstreamSessionID>), and the node fetches it inside its per-session single-flight to reconstruct ffmpeg seeked to the requested segment. Reads fail closed (absent/forged/wrong-session → 404, no spawn); writes no-op without Redis so a single box is unaffected. Integrated transcodes still reconstruct on central from the token and need no handoff.

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 docs/architecture/restart-resilient-playback.md.

@darthShadow

Copy link
Copy Markdown
Contributor

pr174-review-comments.md

Thanks for doing this. Let me know if this review makes sense.

@CoffeeKnyte
CoffeeKnyte force-pushed the feat/unified-playback-reconstruct branch from 26929d4 to 9e03913 Compare June 21, 2026 06:19
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Yep, makes sense — thanks for the thorough pass. Pushed fixes for all three v1 asks:

  • Inline 1 (remote transcode recipe): startRemoteTranscode now builds the RecipeCard and writes both stores (compat Update + RecipeNodeStore.Put), with node-side rollback (CloseTranscodeSession) if the Update fails. Covers the initial start and the audio-switch restart. Added the two round-trip tests (node restart + central restart).
  • Inline 2 (stream-url double ?): join now picks the separator off the base, so ?st= + ?token= stop collapsing into st=X?token=Y. Both params kept, frontend test added.
  • Inline 3 (compat TTL): default raised to playback.MaxTokenTTL (24h, absolute) at both the router default and the store fallback.

Left the post-v1 stuff (full revocation wiring, the 403 client contract, the durable-store upsert metric) as tracked — agree those arent blockers.

Heads up: I squashed the branch down to 3 commits and force-pushed, so the inline anchors will have moved.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.go
  • docs/architecture/restart-resilient-playback.md
  • internal/api/handlers/admin_playback_control.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/stream.go
  • internal/api/router.go
  • internal/jellycompat/audio_selection_test.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/playback_4k_test.go
  • internal/jellycompat/playback_sessions.go
  • internal/jellycompat/remote_transcode_reconstruct_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/noderecipe/store.go
  • internal/noderecipe/store_test.go
  • internal/nodesessions/tracker.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/transcode_cleanup.go
  • internal/playback/transcode_manager.go
  • internal/playback/transcode_manager_test.go
  • internal/proxy/server.go
  • internal/streamauth/lease.go
  • internal/streamauth/lease_test.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • web/src/player/stream-url.test.ts
  • web/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).
@CoffeeKnyte
CoffeeKnyte force-pushed the feat/unified-playback-reconstruct branch from 9e03913 to 73d03a8 Compare June 21, 2026 11:18
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.
@darthShadow

Copy link
Copy Markdown
Contributor

Further comments:
pr174-review-comments-v2.md

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.
@darthShadow

Copy link
Copy Markdown
Contributor

Optional Enhancement:

Restart() re-spawns ffmpeg outside the new per-session lifecycle lock (High).

FB-4 (d1238a66) serialized the fresh-start and reconstruct spawn paths, but the lock's own contract comment says it must also cover restart — and that arm is unguarded. TranscodeSession.Restart() (internal/playback/transcode.go:1399) releases s.mu across cancel → wait-for-done → spawn and re-execs ffmpeg into the same opts.OutputDir without taking LockSessionLifecycle.

All five callers invoke it unlocked: internal/api/handlers/playback.go:1951 (native audio-switch) and :2788 (native segment-recovery), internal/jellycompat/streams.go:477 (compat segment-recovery) and :1220 (compat audio-switch), and internal/transcodenode/server.go:717 (node segment-recovery).

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, init.mp4/segment mismatch, orphaned-but-still-writing ffmpeg — the exact concurrent-writer corruption FB-4 was added to prevent (both topologies).

Suggest serializing the restart transition under the same LockSessionLifecycle/lockSessionLifecycle (with the existing-session re-check) as the start/reconstruct paths, or centralizing restart spawning in the manager, plus concurrent-restart tests on the API, jellycompat, and node paths.


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.
@CoffeeKnyte

CoffeeKnyte commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks. Implemented the fix. Confirmed on all counts. Restart() releases s.mu across cancel → wait-for-done → re-exec and spawns ffmpeg into opts.OutputDir without ever taking LockSessionLifecycle, and all five callers invoked it unlocked. So an audio-switch racing a segment-recovery (or a restart racing a fresh-start/reconstruct) really could land two ffmpeg writers on the same segment dir — the exact FB-4 corruption, on both topologies.

Fixed in 108946f0.

Approach

  • New TranscodeManager.RestartSessionLocked (native + compat) and Server.restartSessionLocked (node) hold the per-session lifecycle lock only across the cancel→respawn transition inside Restart, then release before the caller waits on segments — so segment-recovery latency is unchanged.
  • Under the lock they re-check that the handle is still the live mapped session and return a new ErrSessionSuperseded sentinel instead of re-spawning a stale handle (guards the concurrent-teardown/reconstruct-replaced window you implied with "existing-session re-check").
  • All five sites rerouted: native audio-switch (playback.go:1951) and segment-recovery (:2788), compat audio-switch (streams.go:1220) and segment-recovery (:477), node segment-recovery (server.go:717).

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

Adversarial self-review notes

  • No false ErrSessionSuperseded after a reconstruct: doReconstructTranscode / node spawnReconstruct register the rebuilt session into the same map the re-check reads before returning the handle, so identity matches.
  • Lock order is consistent with the existing start/reconstruct paths (lifecycle → map mutex → s.mu); no inversion, and Restart never takes the lifecycle lock.
  • The superseded return is handled non-fatally at every site (log + continue / fall through to 404-retry), so no new client-facing error.

One deliberate trade-off: a restart now holds the lifecycle lock across Restart's <-done wait (bounded by ffmpeg's WaitDelay = 3s), briefly serializing a competing same-session start/reconstruct — same coupling those paths already had.

internal/api/handlers tests still need the libvips container; the shared RestartSessionLocked those handlers call is covered by the manager-level tests here. Thanks for the thorough pass. 🙏

@darthShadow

Copy link
Copy Markdown
Contributor

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
@CoffeeKnyte

CoffeeKnyte commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor Author

[PR was a Success] ✅ Restart-resilience verified in production — 6/6 live sessions self-healed

Outcome: 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

  • 6 of 6 active playback sessions reconstructed automatically — 5 direct-play + 1 remux (video copy + audio transcode to AAC).
  • The transcode session resumed at the segment the client was already on (segment 4691), not from zero — ffmpeg was rebuilt from the recipe and immediately kept serving (995× 200 on segment requests afterward).
  • Zero reconstruct refused, zero ownership rejections, zero admission-cap denials. No ERROR/FATAL/panic on boot.

Timing

  • Container start → HTTP serving: ~10s (migrations applied on boot; API, ABS, and Jellyfin-compat listeners all up).
  • First session reconstructed ~1.3s after the server began accepting connections.
  • All 6 sessions reconstructed within ~7.6s of the server coming back (span of ~6.3s across the group).
  • Total client-visible unavailability from recreate to serving ≈ ~22s (most of it health-gating dependencies, not the app itself).

Log evidence (identifiers redacted)

INFO playback session reconstructed from recipe card   method=transcode
INFO transcode process reconstructed from recipe card  requested_segment=4691 start_segment_number=0
INFO playback session reconstructed from recipe card   method=direct   (×5)

Edge observed (not a failure of this change)

  • Reconstruction is triggered on the stream/segment serve path, as designed. Two idle sessions that only polled control-plane endpoints (/progress, control/ws) without re-requesting media stayed 404 until they would next fetch a segment. Worth considering whether /progress should also front-door a reconstruct so paused/backgrounded clients recover their progress + control channel without waiting on the next media request.
  • Durable jellycompat recipe rows survived the restart intact; native sessions carried their recipe with the request, so no shared server-side state was required for them to resume.

Reported with AI assistance.

Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…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]>
@Rhainland Rhainland mentioned this pull request Oct 11, 2026
8 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants