Skip to content

fix(playback): rebuild header-authenticated sessions after an API restart - #2501

Merged
Quick104 merged 3 commits into
mainfrom
fix/2495-header-auth-restart
Oct 15, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/2495-header-auth-restart

Conversation

@Quick104

@Quick104 Quick104 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2495
Related issue: #333
Validation tasks: changes #1177 C3
Pairs with Silo-Server/silo-apple#802

After every server update, Apple apps playing a server transcode stop a minute or two later with "End of playback", well before the end of the film. Web and Android ride through the same restart. With this change the Apple apps keep playing through an API restart too.

The Apple apps opt into header-authenticated media (header_authenticated_media_v1), so their media URLs carry no st stream token. The token is what a restarted API rebuilds a lost in-memory playback session from. For these sessions the restarted API had nothing to rebuild from: the manifest and every segment answered 404, which the v2 media routes turn into the generic not_found problem. AVPlayer skips 404 segments until it reaches the end of the playlist it already loaded, and the app then shows "End of playback" (Silo-Server/silo-apple#801). The protocol doc listed this as the accepted cost of the mode and named server-side session state as the fix.

Approach

For header-authenticated attempts served from the API origin, the API now keeps the recipe the token would have carried in a new Redis key space, next to the existing proxy grants and node recipes (noderecipe.NewSessionRecipeStore). It is written once the transport commits, with the routing taken from the live session, and updated when a transcode moves off a dead node. When a manifest, segment, /stream or sidecar request finds no in-memory session, the API rebuilds the session from that record. From there the path is the token one: deny marker, route checks, copy-safety gate, admission caps, then the relay to the node (which rebuilds from its own stored recipe) or the local FFmpeg rebuild at the requested segment.

The record only helps reconstruction; the durable v3 attempt row decides whether it may be used. It must name the same plan, so a record a later replan failed to overwrite is refused. It must also match the account and selected profile, and be neither expired nor stopped. All of this is checked before anything is registered or started. The rebuilt session still refuses unauthenticated requests. If Redis or the attempt row can't be read, the request answers a retryable 500 instead of telling the client its session is gone. The rebuilt session keeps the progress policy and requested file the live session had. Without Redis nothing changes: the session answers 404 after a restart and the client starts a new attempt.

Proxy-served attempts (authorized_media_origins_v1) get no record. Their proxy grant already survives a restart, and a session the API rebuilt for them would be reaped on API-side activity alone. Progress, replan and the control socket are untouched, and a replan of a lost session still answers 404.

No API contract change. The app side of the same failure is Silo-Server/silo-apple#801, fixed in Silo-Server/silo-apple#802: the app treats a premature end of a server stream as a lost connection and replans at its position, so it also recovers against servers without this change.

Validation

  • Reproduced on a dev deployment with an API, a transcode node and Redis, recreated together with docker compose up -d --force-recreate the way a production deploy does (8 s outage). Before, with a header-authenticated 480p transcode running on the transcode node: after the restart the master playlist and every segment returned 404 not_found, progress stayed 200, and a replan returned 404. After: the same requests returned 200, an unauthenticated segment request returned 401, and a replan returned a plan. Video PTS stayed continuous across the restart (+180180 per segment). A far segment rebuilt after the restart started within 45 ms of its position in the playlist the client already held.

  • The iOS app on a simulator, against that deployment, restarted 12 minutes before the end of a film at 480p:

    • the current app (silo-apple main) played through to the credits with no 404s and no reconnect;
    • with the silo-apple#802 fix it did the same, and its reconnect path never fired.

    The server log shows each session rebuilt on its first request after the restart. Against unfixed server main, the silo-apple#802 app hit the segment 404s, replanned, and resumed at the same position on a new session 3.7 s later (checked in that PR).

  • New handler tests cover:

    • recovery after a restart;
    • the refusals: unauthenticated, another account, another profile, stopped attempt, superseded plan, unreachable Redis, unreadable attempt store;
    • a client-owned progress policy surviving the rebuild;
    • a rebuilt session refusing unauthenticated requests;
    • recovery onto another node when the original one is gone;
    • /stream direct play;
    • which stops drop the record (a user's stop, and any teardown of a remote transcode) and which keep it (an FFmpeg exit on a transcode the API runs).

    Removing each guard fails its test.

  • make test-go, go vet ./..., make lint-changed, make verify-local-paths and the route, playback-fixture, OpenAPI, contract and offline-route checks pass. No web changes.

  • Validation impact: "Distributed transcode nodes — Server" (Distributed transcode nodes — Server #1177) C3 removes a worker during playback, which runs the failover path this change touches. For a header-authenticated session, a move to another executor now also points the recovery record at the new executor: one Redis read and one bounded write, taken after the move has succeeded and before the relayed request is answered. That's milliseconds against C3's 10-second bar. Token-bearing sessions move exactly as before. The task records C3 as not run; it should be run (or re-run) on a build with this change. I couldn't read the validation board itself (token scope).

Evidence

Surface and build: the iOS app on a simulator (silo-apple main, and the silo-apple#802 build) against a dev deployment of this branch, plus the server's media responses, logs and segment timestamps before and after the restart.

Evidence: https://evidence.siloserver.org/r/silo-server/issue-2495/

Risks

  • Every header-authenticated start and replan does one more bounded Redis write. The read happens only when a session is missing.
  • Deployments with several API replicas should keep session affinity for these attempts: a replica holding an idle copy of the session stops its transcode on the node when that copy expires. The protocol doc says so.
  • A crash between a replan's durable commit and the record write leaves the old record, which recovery refuses. That session answers 404 once and the client starts a new attempt.
  • Like a live session and a token rebuild, a rebuilt session isn't re-checked against the user's current library access; Silo checks access when playback starts. Re-checking on every rebuild would be a separate policy change covering tokens too.

Follow-ups

  • playback: restart resilience misses control-plane endpoints — progress 404 kills recoverable streams within 10s #333: control-plane calls after a restart (replan, audio change, control socket) could rebuild from the same record.
  • Found in review and present on main, left for separate issues: a transcode moved to another node loses its keyframe-playlist mode; token reconstruction drops a client-owned progress policy; a stale idle copy on one replica stops a transcode another replica is serving.
  • The three recipe stores share an API Redis client that doesn't honor context deadlines; moving them to the deadline-aware client is a separate change.
  • jellycompat is unaffected; it rebuilds from its own session row. Android and web carry tokens and need no change.
  • User manual: unaffected. It doesn't describe restart behavior or replica affinity for these sessions.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code subagents for code review; OpenAI Codex through T3 Code for the plan review and the adversarial review
  • Model(s): claude-opus-5-5 (implementation, review finders and verification), claude-sonnet-5-5 (review finder), gpt-6.1-sol (plan review, adversarial review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: before implementation, gpt-6.1-sol (xhigh) reviewed the plan. It led to binding the record to the durable attempt (plan, stop, profile, progress policy), sidecar recovery, and keeping the record current across node moves; the items out of scope are listed above. A multi-agent code review then fixed transient-error handling, attempt expiry, proxy-served scope, and system-teardown retention. Background review by gpt-6.1-sol of 1f2f52e: 2 findings (Redis read failures answered as 404; progress policy lost when a file lookup fails), both fixed in 90895c8, the same two the Codex connector raised. Bot reviews also led to 0bcd8c8 (drop the record when a remote transcode is torn down); the access re-check question is open in review.

🤖 Generated with Claude Code

…tart

An attempt that negotiated header_authenticated_media_v1 publishes no stream
token, so after a restart the API had nothing to rebuild its in-memory
playback session from: the manifest and every segment answered 404, which
AVPlayer skips to the end of its playlist (Apple apps then show "End of
playback").

Keep the recipe the token would have carried in a new Redis key space
(noderecipe.NewSessionRecipeStore) for API-origin transports, written once
the transport commits and followed when a transcode moves off a dead node.
A manifest, segment, /stream or sidecar request that finds no live session
rebuilds it from that record, only for the authenticated owner and only
while the durable attempt still names the recorded plan, matches the
selected profile, and has neither expired nor been stopped. The rebuilt
session keeps requiring media authorization. An unreadable attempt row
answers a retryable 500 instead of a 404.

Closes #2495

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T01:19:51.870695Z 0bcd8c8 New commits
🔒 Security Review ✅ Completed 2026-10-15T01:19:48.027704Z 0bcd8c8 New commits

Security findings

Advisory findings (1)

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: playback Can't play, stalls, or wrong media priority: P1 Core-path bug; painful workaround — next after P0 labels Oct 15, 2026
@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 16d3dcef-9371-4f91-9cd4-23c4f10dfe33
📥 Commits

Reviewing files that changed from the base of the PR and between 1f2f52e and 0bcd8c8.

📒 Files selected for processing: 9
  • docs/architecture/restart-resilient-playback.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_session_recipe.go
  • internal/api/handlers/playback_session_recipe_test.go
  • internal/api/handlers/playback_v3_origins_test.go
  • internal/api/handlers/stream.go
  • internal/noderecipe/store.go
  • internal/noderecipe/store_test.go
  • internal/playback/recipecard.go
🚧 Files skipped from review as they are similar to previous changes: 2
  • internal/playback/recipecard.go
  • docs/architecture/restart-resilient-playback.md

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

📝 Walkthrough

The API now stores recovery recipes for committed header-authenticated playback transports. On a session miss, playback handlers validate the caller and durable attempt before rebuilding an eligible session. Stops and aborts remove recipes under the specified lifecycle conditions.

Changes: Header-authenticated session recovery

Layer / File(s) Summary
Recovery-card contract and Redis wiring
internal/playback/recipecard.go, internal/noderecipe/store.go, internal/api/router.go, internal/api/handlers/playback.go, internal/api/handlers/stream.go, internal/api/handlers/playback_v3.go, internal/api/handlers/playback_v3_origins_test.go
Recipe cards now include the plan and session settings needed for recovery. Redis provides a separate session-recipe key space and lookup errors. The router shares the Redis-backed store with playback and stream handlers.
Record, follow, and retire session recipes
internal/api/handlers/playback_v3.go, internal/api/handlers/playback_session_recipe.go, internal/api/handlers/playback_transcode_rehome.go, internal/api/handlers/playback.go, internal/api/handlers/stream.go, internal/api/handlers/playback_v3_node_recipe_test.go, internal/api/handlers/playback_session_recipe_test.go
Transport preparation and commits record recipes for header-authenticated transports. Replans and transcode moves update routing data. User stops and aborts delete recipes; specified system teardowns retain them.
Validate and reconstruct sessions
internal/api/handlers/playback_session_recipe.go, internal/api/handlers/playback.go, internal/api/handlers/stream.go, internal/playback/session.go, internal/playback/transcode_manager.go, internal/api/handlers/playback_session_recipe_test.go, docs/architecture/playback-protocol-v3.md, docs/architecture/restart-resilient-playback.md
On an in-memory session miss, handlers load a recipe and validate its caller, plan, profile, authorization, expiry, and stopped state against the durable attempt. Reconstructed sessions restore media authorization and client settings. Tests cover restart recovery and refusal cases; the architecture documents describe recovery and replica behavior.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant MediaClient
  participant PlaybackHandler
  participant SessionManager
  participant SessionRecipeStore
  participant AttemptStore
  MediaClient->>PlaybackHandler: Request media for a session
  PlaybackHandler->>SessionManager: Look up session
  SessionManager-->>PlaybackHandler: Return session miss
  PlaybackHandler->>SessionRecipeStore: Load recovery card
  PlaybackHandler->>AttemptStore: Validate caller and durable attempt
  PlaybackHandler->>SessionManager: Rebuild session from validated card
  PlaybackHandler-->>MediaClient: Serve media with client authentication required
Loading

Suggested reviewers: coffeeknyte

Merge Risk: ⚪ Minimal · up to 0bcd8

No confirmed issue blocks merging after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 73.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 15 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Issue #2495 requires header-authenticated server-transcoded playback to survive an API restart or return an actionable recovery response. The PR stores API-origin session recipes in Redis and rebuilds…
Out of Scope Changes check Passed The changes remain within issue #2495. The store, recipe fields, lifecycle handling, route recovery, node-move updates, documentation, and tests support restart recovery for header-authenticated media…
Title check Passed The title clearly and concisely identifies the main change: rebuilding header-authenticated playback sessions after an API restart.
Description check Passed The description is directly related to the changeset. It explains the restart problem, Redis-backed session recovery approach, validation results, risks, and scope limits.
Full details: Docstring Coverage

Explanation

Docstring coverage is 73.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 15 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f2f52e6a9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.1-sol, reviewed 1f2f52e)

I verified two dependency-failure paths in recovery. Both overlap with findings the automated review posted during this pass. The inline comments give the source traces and repairs; I did not reproduce these failures on a running deployment.

Focused recovery, tokenless transport, node-recipe and sidecar Go tests passed in internal/api/handlers, internal/noderecipe and internal/playback. The validation-board query was blocked by the missing read:project scope; #1177 C3 is recorded as Not run in its issue.

AI disclosure: Review performed with OpenAI Codex in T3 Code, model gpt-6.1-sol.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ Codex Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 1f2f52e6a9

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment on lines +194 to +198
if record == nil || record.StoppedAt != nil || record.CurrentPlanID != card.PlanID ||
record.UserID != userID || record.ProfileID != card.ProfileID ||
(!record.ExpiresAt.IsZero() && time.Now().After(record.ExpiresAt)) ||
!playback.HasFeatureV3(record.NormalizedRequest.ClientFeatures, playback.FeatureHeaderAuthenticatedMediaV3) {
return nil, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ Codex Security Review · Automatically triggered

P2 Badge Security: Reauthorize recovered sessions against current access

When Redis recovery is enabled and a header_authenticated_media_v1 request lands after an API restart or replica miss, a user whose library/profile access was revoked can replay the session URL they received earlier. This gate checks only the stored attempt/card identity, plan, stop state, and expiry; it never applies the request's current viewer scope or ItemAccess, and the profile comparison is skipped when no selector is present. Reconstruction then serves the recorded media for up to 24 hours. RequireAuth and user-ID matching block anonymous/cross-account use, but not stale same-account authorization. Reauthorize the media against current policy, or invalidate the recipe by policy revision, before returning the card.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Silo authorizes the file once, at start (loadAuthorizedFile in the v3 start path). After that, neither a live session's media requests nor token reconstruction (?st, web and Android) re-check library or profile access during the attempt's 24-hour lifetime. Recovery keeps that same posture: it requires the authenticated owner, the selected profile when one is sent (the same rule requireOwningProfile applies to live sessions), the current plan, and an attempt that is neither stopped nor expired. It does not widen access beyond what a live session or a token already allows. Re-checking access on every rebuild would be a broader policy change that should cover token reconstruction too, so I have left it out of this PR and listed it under Risks. Leaving this thread open for a maintainer to decide.

Comment thread internal/api/handlers/playback.go Resolved
… policy

A Redis read failure during recovery was answered like a missing session
(404). The session-recipe reader now uses noderecipe's new Store.Lookup,
which reports the read error, and the loaders answer a retryable 500 as
they already do for an unreadable attempt row. Get keeps failing closed
for the node and proxy readers.

The rebuilt session's progress policy and requested file are now the live
session's, recorded with the card and carried across node moves, instead of
recomputed from a file lookup that could fail and leave a multipart part
writing resume state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

…n down

A system teardown keeps the recovery card so the next request can rebuild a
transcode the API runs itself. For a remote transcode the same teardown stops
the node job and drops the node's recipe, so the card could only rebuild a
session that relays the node's 404; drop it there too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@macroscopeapp

macroscopeapp Bot commented Oct 15, 2026

Copy link
Copy Markdown

The PR changes visible playback behavior: header-authenticated playback now survives an API restart instead of ending when media requests return 404. The before/after results and evidence link are under ## Validation, but there is no ## Evidence section. Move the existing Evidence: link under a ## Evidence heading; the linked page should show the before/after media responses and playback continuity across the restart so reviewers can verify the change.

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

Posted via Macroscope — Visible change evidence

@macroscopeapp

macroscopeapp Bot commented Oct 15, 2026

Copy link
Copy Markdown

The recorded silo-server#1177 C3 case needs re-validation after merge. Its run on local merge bfd02acf6 measured failover against the agreed 10-second bar, but this diff adds a synchronous Redis recipe read and write to the header-authenticated rehome path before the recovered request returns. The earlier measurement does not cover that work. The PR should explain why this validated recovery behavior changes, and C3 needs re-validation after merge.

Please replace Validation tasks: none with:

Validation tasks: changes #1177 C3

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104
Quick104 merged commit c65eb60 into main Oct 15, 2026
25 checks passed
@Quick104
Quick104 deleted the fix/2495-header-auth-restart branch October 15, 2026 22:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: playback Can't play, stalls, or wrong media priority: P1 Core-path bug; painful workaround — next after P0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Header-authenticated transcode sessions get 404 for every segment after a server restart

1 participant