Skip to content

refactor(playback): share HLS segment wait and recovery core across surfaces - #4890

Merged
Quick104 merged 3 commits into
mainfrom
refactor/playback-hls-segment-recovery
Nov 22, 2026
Merged

Quick104 merged 3 commits into
mainfrom
refactor/playback-hls-segment-recovery

Conversation

@Quick104

@Quick104 Quick104 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Other clients: N/A (no client-visible change)

Native playback, Jellyfin compatibility, and the remote transcode node each carried their own copy of the HLS segment open, wait, locked restart, and init-segment wait loop. Because the three copies lived in separate packages, fixes such as the copy-video unresolved seek guard had to be ported by hand and had already drifted in structure and log fields, including a //nolint:nestif suppression in internal/transcodenode/server.go. This change moves the shared recovery core into internal/playback.OpenSegmentWithRecovery so all three HTTP surfaces execute one implementation while keeping their own HTTP handling intact.

Approach

internal/playback/segment_recovery.go adds OpenSegmentWithRecovery and SegmentRecoveryOptions to run the missing-segment sequence: initial OpenSegment, non-numbered init-segment wait while running, SegmentRecoveryDecision, optional wait, locked seek-restart callback, copy-video unresolved target guard returning ErrSegmentNotFound, post-restart wait, and optional copy-video lookahead.

Each of the three callers keeps everything specific to its HTTP contract:

  • internal/api/handlers/playback.go (HandleGetTranscodeSegment) passes h.tm.RestartSegmentLocked and CopyLookaheadTimeout: 1200 * time.Millisecond so only the native surface waits for segNum+1 on copy-video restarts.
  • internal/jellycompat/streams.go (HandleHLSSegment) passes h.tm.RestartSegmentLocked, SegmentNumberName: name (preserving Jellyfin's segmentId-based segment parsing for multi-dot containers), and its fingerprinted play_session log attribute, leaving its response headers and hlsSegmentErrorResponse mapping unchanged.
  • internal/transcodenode/server.go (handleSegment) passes s.restartSegmentLocked, drops the //nolint:nestif suppression, and keeps its node-specific log messages and GenerationHeader proxy handling.

All three callers keep their own r.Context().Err() to ErrSegmentNotFound mapping, HTTP error writers, Cache-Control/Pragma headers, http.ServeContent with RollingDeadlineWriter, and ReportSegmentDownloadedForGeneration accounting. Extracting the HTTP wrapper itself was left out so surface-specific headers, proxy headers, and error envelopes stay local to each handler.

Unit tests in internal/playback/segment_recovery_test.go cover immediate hits, wait-then-hit, wait timeout followed by locked restart and copy-video lookahead, unresolved copy-video seek targets returning ErrSegmentNotFound, multi-dot SegmentNumberName overrides, init-segment waiting (running and stopped), restart error propagation, and per-surface slog attributes and messages. They do not run real FFmpeg; restart locking and FFmpeg lifecycles remain covered by the existing playback and transcode-node tests.

Validation

  • Build & formatting (make embed-stub, go build ./..., gofmt -l ., go mod tidy -diff): pass.
  • Static analysis (go vet ./..., make lint-changed BASE_REF=origin/main): pass, 0 issues.
  • Repository & contract checks (make verify-size-ratchet BASE_REF=origin/main, make verify-local-paths, make verify-bidi, make verify-case-collisions, make verify-route-inventory, make verify-playback-fixtures): pass.
  • Stress & race tests (go test -count=200 -run '^TestOpenSegmentWithRecovery' ./internal/playback/, go test -race ./internal/playback/... ./internal/jellycompat/... ./internal/transcodenode/..., and umask 0022 && go test -race ./internal/api/handlers/...): pass.

Evidence

No user-visible behavior changes. Verified on commit c553c21efcf6fae2343bd354117d9fb20c9b1711 (based on origin/main at e2e4ab8b5):

Before/after line counts across the migrated callers and shared helper:

  • internal/api/handlers/playback.go: +8 / -123 (-115 lines)
  • internal/jellycompat/streams.go: +10 / -113 (-103 lines)
  • internal/transcodenode/server.go: +7 / -96 (-89 lines; removed //nolint:nestif)
  • internal/playback/segment_recovery.go: +179 lines (net -128 production lines)
  • internal/playback/segment_recovery_test.go: +476 lines

Trimmed verification output:

$ go test -count=200 -run '^TestOpenSegmentWithRecovery' ./internal/playback/
ok  	github.com/Silo-Server/silo-server/internal/playback	2.425s

$ make lint-changed BASE_REF=origin/main
lint-changed: 4 package(s) changed since origin/main
0 issues.

$ make verify-size-ratchet BASE_REF=origin/main
(exit 0)

Risks

Low. The recovery state machine, timeout durations, restart-lock callbacks, error mapping, and HTTP response headers stay the same on each surface. One minor log addition: jellycompat and transcodenode now also emit the restart_on_timeout boolean field that api already logged on segment-recovery info events.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

Council: gpt, claude, 1 round, reviewed c1e36dc

AI Disclosure

  • Harness: T3 Code (Antigravity)
  • Tool(s): T3 Code
  • Model(s): gemini-4-neon (implementation); gpt-6.2-sol and claude-opus-5-5 (pre-implementation council review); gpt-6.2-sol (post-PR diff review)
  • Involvement: AI-assisted
  • Adversarial review: Pre-implementation design review by gpt-6.2-sol and claude-opus-5-5 (council, 1 round); post-PR diff review by gpt-6.2-sol flagged a racy lookahead flag in segment_recovery_test.go and multi-dot Jellyfin segmentContainer parsing parity, both fixed in c553c21ef

Note

Extract shared HLS segment wait-and-recovery core into playback.OpenSegmentWithRecovery

  • Adds playback.OpenSegmentWithRecovery in segment_recovery.go, which consolidates the inline segment-open, wait, and restart-recovery flow used by three segment handlers: the API HandleGetTranscodeSegment, the Jellyfin-compatible HandleHLSSegment, and the transcode-node handleSegment.
  • The helper takes a SegmentRecoveryOptions config for session/component log attributes, an optional play-session fingerprint, an alternate segment-number name, a restart callback, and a copy-video lookahead timeout. It handles non-numbered init segments and unresolved copy-video restart targets.
  • Log helpers preserve the existing transcode-node-specific restart messages while other surfaces use the general message; the play-session log attribute is only attached when a fingerprint is provided.
  • Adds tests in segment_recovery_test.go covering immediate hit, wait, restart, timeout, init-segment behavior, error propagation, log attributes, and name overrides.
  • Risk: no intended behavior change, but all three handlers' recovery paths now run through the new helper — check playback.go, streams.go, and server.go for correct wiring of the 1,200 ms lookahead timeout and restart callbacks.

Macroscope summarized eddad68.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 46 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dfbc1951-857d-4ecd-86e2-79b89a18a196
Commits

Reviewing files that changed from the base of the PR and between c553c21 and eddad68.

Files selected for processing: 2

  • internal/playback/segment_recovery.go
  • internal/playback/segment_recovery_test.go
Walkthrough

The playback package adds shared segment-opening and recovery logic. The API, Jellyfin-compatible, and transcodenode handlers now use it. Tests cover recovery waits, restarts, copy-video lookahead, and component-specific logging.

Changes: Shared HLS Segment Recovery

Layer / File(s) Summary
Shared recovery logic and validation
internal/playback/segment_recovery.go, internal/playback/segment_recovery_test.go
OpenSegmentWithRecovery opens segments and handles missing-segment waits, restart callbacks, and copy-video lookahead. Tests cover recovery outcomes, options, and component-specific logging.
Handler adoption
internal/api/handlers/playback.go, internal/jellycompat/streams.go, internal/transcodenode/server.go
The three handlers delegate segment opening and recovery to OpenSegmentWithRecovery, with caller-specific session context and restart callbacks.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Suggested reviewers: blurbery, rhainland, rangodj

Merge Risk: Low · previous review c553c

Segment serving for native playback, Jellyfin compatibility, and transcode nodes now shares one recovery path, with no established user-visible behavior change. A small test-hygiene follow-up remains: the restart test should wait for its background producer so that a future regression reports a clear failure instead of crashing the test run. The change is safe to merge with that follow-up noted.

Security architecture risk: Minimal · up to c553c

The shared recovery flow preserves the inspected session controls, locked restart callbacks, cancellation handling and segment cleanup. No introduced or worsened risk materially affecting security, failure containment or ownership was identified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A defect in the shared recovery policy could now affect all three serving surfaces. However, the inspected change retains per-session callback binding and introduces no cross-session restart selector; sharing the implementation does not itself widen the authority of an individual request.

Trust Boundaries and Controls

  • observed — The native handler retains session-load status enforcement, owning-profile checks and native egress checks before recovery. Jellycompat retains authenticated-context enforcement, own-play-session lookup, route validation and user-bound runtime loading before invoking the helper. These checks remain outside the extracted core.

Resilience and Maintainability Implications

  • inferred — Centralization reduces independent recovery-policy copies while preserving the inspected failure-containment boundaries: unresolved copy-video targets return not-found without entering post-restart waiting, and non-not-found wait errors return before another restart is attempted.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: moving the HLS segment open, wait, and recovery sequence into a shared playback helper used by native playback, Jellyfin compatibility, and the transcode node. It is s…
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 The description states the problem (three duplicated HLS segment open, wait, locked restart, and init-segment wait loops across the native playback, Jellyfin compatibility, and transcode-node surfaces…
Full details: Title check

Explanation

The title names the main change: moving the HLS segment open, wait, and recovery sequence into a shared playback helper used by native playback, Jellyfin compatibility, and the transcode node. It is specific and accurate to the changeset.

Full details: Description check

Explanation

The description states the problem (three duplicated HLS segment open, wait, locked restart, and init-segment wait loops across the native playback, Jellyfin compatibility, and transcode-node surfaces). It names the shared helper, the per-caller options, the validation performed, and the risks. It matches the changeset, which moves that logic into playback.OpenSegmentWithRecovery.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T15:22:55.294798Z eddad68 New commits
🔒 Security Review ✅ Completed 2026-11-21T15:25:18.020978Z eddad68 New commits
ℹ️ 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-kody

silo-kody Bot commented Nov 21, 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 ❌

@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. priority: P2 Limited scope, workaround exists, or polish labels Nov 21, 2026
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/XL 500–999 added + deleted lines (all files); change volume, not priority. labels Nov 21, 2026
@silo-kody

silo-kody Bot commented Nov 21, 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 ❌

@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: 1

Minor comments: 1

internal/playback/segment_recovery.go: 1

135-135: Minor · Functional Correctness · Low value

Derive the lookahead name from the full suffix of the requested segment name.

filepath.Ext returns only the final extension. For a name such as seg_00002.m4s.extra, the lookahead builds seg_00003.extra, not the next fragment seg_00003.m4s.extra. The helper then polls for the full CopyLookaheadTimeout and returns the target lease without the lookahead result.

No current caller sets both SegmentNumberName and CopyLookaheadTimeout, so this does not affect existing behavior. It applies to the shared option contract, which accepts both options together. Fix the successor name so it keeps the full suffix after the segment-number stem when SegmentNumberName matches the requested name. Keep the current single-extension result for ordinary .ts and .m4s names.

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4f650555-02ed-4762-b810-31cf57ae6d46
Commits

Reviewing files that changed from the base of the PR and between ce96773 and c553c21.

Files selected for processing: 5

  • internal/api/handlers/playback.go
  • internal/jellycompat/streams.go
  • internal/playback/segment_recovery.go
  • internal/playback/segment_recovery_test.go
  • internal/transcodenode/server.go

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

@silo-kody

silo-kody Bot commented Nov 21, 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 ❌

@Quick104
Quick104 merged commit 0bc3ce2 into main Nov 22, 2026
19 checks passed
@Quick104
Quick104 deleted the refactor/playback-hls-segment-recovery branch November 22, 2026 00:53
Quick104 added a commit to Rhainland/silo-server that referenced this pull request Nov 22, 2026
Main's Silo-Server#4890 moved the three segment handlers' wait and restart logic into
playback.OpenSegmentWithRecovery. The end-of-stream check now sits in that
core, after the wait and before any restart: it returns ErrPastEndOfStream
(which wraps ErrSegmentNotFound), and the API, jellycompat and transcode
node handlers answer it with ServePastEndOfStream's empty 200.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant