You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
refactor(playback): share HLS segment wait and recovery core across surfaces - #4890
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:
$ 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.
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.
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).
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.
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: 4
Check name
Status
Explanation
Title check
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
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
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.
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
priority: P2Limited scope, workaround exists, or polishsize/XXL1000–2999 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
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:nestifsuppression ininternal/transcodenode/server.go. This change moves the shared recovery core intointernal/playback.OpenSegmentWithRecoveryso all three HTTP surfaces execute one implementation while keeping their own HTTP handling intact.Approach
internal/playback/segment_recovery.goaddsOpenSegmentWithRecoveryandSegmentRecoveryOptionsto run the missing-segment sequence: initialOpenSegment, non-numbered init-segment wait while running,SegmentRecoveryDecision, optional wait, locked seek-restart callback, copy-video unresolved target guard returningErrSegmentNotFound, 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) passesh.tm.RestartSegmentLockedandCopyLookaheadTimeout: 1200 * time.Millisecondso only the native surface waits forsegNum+1on copy-video restarts.internal/jellycompat/streams.go(HandleHLSSegment) passesh.tm.RestartSegmentLocked,SegmentNumberName: name(preserving Jellyfin'ssegmentId-based segment parsing for multi-dot containers), and its fingerprintedplay_sessionlog attribute, leaving its response headers andhlsSegmentErrorResponsemapping unchanged.internal/transcodenode/server.go(handleSegment) passess.restartSegmentLocked, drops the//nolint:nestifsuppression, and keeps its node-specific log messages andGenerationHeaderproxy handling.All three callers keep their own
r.Context().Err()toErrSegmentNotFoundmapping, HTTP error writers,Cache-Control/Pragmaheaders,http.ServeContentwithRollingDeadlineWriter, andReportSegmentDownloadedForGenerationaccounting. 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.gocover immediate hits, wait-then-hit, wait timeout followed by locked restart and copy-video lookahead, unresolved copy-video seek targets returningErrSegmentNotFound, multi-dotSegmentNumberNameoverrides, init-segment waiting (running and stopped), restart error propagation, and per-surfaceslogattributes and messages. They do not run real FFmpeg; restart locking and FFmpeg lifecycles remain covered by the existing playback and transcode-node tests.Validation
make embed-stub,go build ./...,gofmt -l .,go mod tidy -diff): pass.go vet ./...,make lint-changed BASE_REF=origin/main): pass, 0 issues.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.go test -count=200 -run '^TestOpenSegmentWithRecovery' ./internal/playback/,go test -race ./internal/playback/... ./internal/jellycompat/... ./internal/transcodenode/..., andumask 0022 && go test -race ./internal/api/handlers/...): pass.Evidence
No user-visible behavior changes. Verified on commit
c553c21efcf6fae2343bd354117d9fb20c9b1711(based onorigin/mainate2e4ab8b5):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 linesTrimmed verification output:
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:
jellycompatandtranscodenodenow also emit therestart_on_timeoutboolean field thatapialready logged on segment-recovery info events.Checklist
Council: gpt, claude, 1 round, reviewed c1e36dc
AI Disclosure
segment_recovery_test.goand multi-dot JellyfinsegmentContainerparsing parity, both fixed inc553c21efNote
Extract shared HLS segment wait-and-recovery core into
playback.OpenSegmentWithRecoveryplayback.OpenSegmentWithRecoveryin segment_recovery.go, which consolidates the inline segment-open, wait, and restart-recovery flow used by three segment handlers: the APIHandleGetTranscodeSegment, the Jellyfin-compatibleHandleHLSSegment, and the transcode-nodehandleSegment.SegmentRecoveryOptionsconfig 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.Macroscope summarized eddad68.