Skip to content

perf(playback): stop at the newest segment when reading transcode progress - #2954

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/segment-progress-tail-walk
Oct 23, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/segment-progress-tail-walk

Conversation

@blurbery

@blurbery blurbery commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none passed yet. This reaches the seek paths of #1149 C2 and #1148 C3, both not run.

Every time Silo checks how far FFmpeg has got with a transcode, it reads the whole HLS playlist and stats every segment file the playlist lists. FFmpeg is started with -hls_list_size 50000, so a long session can list tens of thousands of segments, and a copy session (or a keyframe-planned one, which restarts from segment 0) fills the playlist quickly. That check (TranscodeSession.SegmentProgress) runs:

  • every 5 seconds per transcode from the throttler, which is on by default, on the API server and on transcode nodes;
  • synchronously on every segment request that misses on disk, through SegmentRecoveryDecision. That is every startup and every seek, on the native API, transcode nodes and jellycompat.

So the number of stat calls behind a seek, and behind each throttler tick, grows with playback position. It gets worse when the transcode directory is on a network filesystem, where each stat is a round trip.

This change stops at the newest segment instead of statting all of them.

Approach

SegmentProgress needs two things from the segment files: the highest listed segment that exists with data (ProducedHead), and when it was written (LastProducedAt). It now walks the playlist from the tail and stops at the first listed segment that exists with a size above zero.

That gives the same answer as the full walk because of how FFmpeg writes the playlist. I checked this in libavformat/hlsenc.c from FFmpeg 8.0 (Silo ships jellyfin-ffmpeg 8.1), both for a segment cut in hls_write_packet and for the last segment in hls_write_trailer:

  • Each segment is written to a .tmp file in one go and renamed into place (-hls_flags temp_file). Only then is it appended to the list and the playlist rewritten, itself through a temp file and a rename.
  • Segment numbers go up by one from -start_number. Without append_list, a playlist lists only the segments of the process that wrote it.

So within one playlist, entries go up in both number and write time, and every listed segment was complete before it was listed. The last listed segment still on disk is the highest and the newest. A pruned prefix, a gap, listed segments that are missing and zero-byte files are all skipped on the way back, as before. ProducedHead keeps its floor of StartSegmentNumber - 1, so a playlist an earlier generation left behind a later restart point still reports the floor, and LastProducedAt still comes from the segment found.

The two walks can differ in one case. An encoded restart with an unchanged recipe keeps the earlier generation's playlist on disk. That playlist could list a segment the new process has already rewritten, before the new process replaces the playlist. FFmpeg replaces it straight after renaming its first segment, in the same call, so the window is the gap between two renames. If FFmpeg died inside that window, the session would report transcode_not_running before the staleness check that reads LastProducedAt, so no decision changes. Before the new process's first segment, both walks return the old generation's head and time. When nothing listed is on disk, the walk still visits every entry, which costs the same as before.

The whole playlist is still read and parsed; the stats were most of the cost (see Benchmarks). Reading only the tail, as the segment pruner does, would also cut the parse, but #2515 checks the full parsed timeline in this function, so I left that out.

ProducedCount is removed. Nothing read it outside two test assertions, and filling it would need the full walk. #1770 assigns it in its new plannedSegmentProgress, so whichever of the two merges second has to drop that assignment.

Validation

  • Focused go test runs on internal/playback for SegmentProgress, the recovery decisions and the throttler: pass. CI runs the full gate.
  • The new table test in transcode_manifest_test.go covers a pruned prefix; a missing tail, a zero-byte tail, a gap and a newer unlisted file in one playlist; a playlist left behind a later restart point; and nothing listed on disk. It checks ProducedHead, LastProducedAt and HasManifest. It also passes against the parent commit's transcode.go, so the old and new walks agree on every row. Removing the StartSegmentNumber - 1 floor makes it fail. Existing tests already cover a missing playlist and the .m4s naming.
  • Full validation gate: not run locally; CI runs it on this revision. It was still running when the PR was opened; see the checks below.

Benchmarks

Measured with BenchmarkSegmentProgress, added in this PR. It calls only SegmentProgress, so the same benchmark ran against the parent's transcode.go (db95c13) and this branch's (eea621c). The branch binary was built before a code comment in transcode.go was reworded; the compiled code is the same. Each case writes a playlist and one 1-byte file per listed segment into a temp directory, then times SegmentProgress with every segment present, which is the steady state during playback.

  • Workload: 3,600 entries (a two-hour title at 2 s segments) and 50,000 entries (the -hls_list_size cap).
  • Environment: macOS on Apple M5 Pro, local APFS SSD, Go 1.27.1, GOMAXPROCS=6.
  • Command: go test -c once per commit, then the two binaries alternated 10 times with -test.run '^$' -test.bench '^BenchmarkSegmentProgress$' -test.benchmem -test.count 1, compared with benchstat.
                        │    before     │                after                 │
                        │    sec/op     │    sec/op     vs base                │
SegmentProgress/3600-6    5853.0µ ± 18%   262.1µ ± 22%  -95.52% (p=0.000 n=10)
SegmentProgress/50000-6   97.684m ±  3%   3.303m ±  5%  -96.62% (p=0.000 n=10)

                        │    before     │                after                 │
                        │     B/op      │     B/op      vs base                │
SegmentProgress/3600-6    2165.1Ki ± 0%   507.4Ki ± 0%  -76.57% (p=0.000 n=10)
SegmentProgress/50000-6   30.067Mi ± 0%   7.555Mi ± 0%  -74.87% (p=0.000 n=10)

                        │   before     │                after                │
                        │  allocs/op   │  allocs/op   vs base                │
SegmentProgress/3600-6    28.573k ± 0%   7.231k ± 0%  -74.69% (p=0.000 n=10)
SegmentProgress/50000-6    399.8k ± 0%   100.0k ± 0%  -74.98% (p=0.000 n=10)

What is left after the change is reading and parsing the playlist. Limitations: this is one local SSD. I did not measure a network filesystem, where each stat is a round trip, a real FFmpeg run or a production server.

Evidence

Evidence: none, no user-visible change. No screen, response or setting changes; the server spends less time before answering a missing-segment request on a long session.

Risks

Low. The result matches the full walk for every playlist FFmpeg writes, apart from the two-rename window above. The function still reads the disk without holding s.mu, as before.

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 says there is none.

AI Disclosure

  • Harness: Claude Code (desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5; claude-sonnet-5-5 for one read-only code search
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: a separate agent, given only the diff, reviewed it for parity with the full walk, locking, restart generations, API versus node paths and conflicts with open PRs. It confirmed parity apart from the two-rename window. It also flagged feat(playback): restart keyframe-planned copy streams mid-stream #1770's ProducedCount assignment, which is noted above, and a test that kept a copy of the old walk; that test was rewritten with explicit expected values.

…gress

SegmentProgress statted every segment the playlist lists to find the
produced head and its write time. FFmpeg lists up to 50,000 segments,
and the throttler (every five seconds) and every missing-segment request
read this, so the number of stat calls grew with playback position.

FFmpeg numbers segments in order, renames each finished segment into
place before rewriting the playlist to list it, and lists only its own
segments, so the last listed segment still on disk is both the highest
and the newest. Walk back from the tail and stop there. The playlist is
still read and parsed in full.

ProducedCount had no readers and needed the full walk, so it is removed.
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@silo-kody

silo-kody Bot commented Oct 23, 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 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 39 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: b9534c8d-0823-49b6-ac3e-d76407a45424
📥 Commits

Reviewing files that changed from the base of the PR and between 8c90021 and eea621c.

📒 Files selected for processing: 2
  • internal/playback/transcode.go
  • internal/playback/transcode_manifest_test.go
  • 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.

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

Seeking to a missing HLS segment can now respond sooner because SegmentProgress performs fewer file stats (internal/playback/transcode.go); the benchmark does not show this playback effect, so please add a short before-and-after recording of the same seek on the same media, naming the surface and builds or commits.

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

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@blurbery

Copy link
Copy Markdown
Contributor Author

I haven't added a recording for this one. The change removes stat calls from a server-side check: at 50,000 listed segments a call drops from 97.7 ms to 3.3 ms on a local SSD, and at 3,600 from 5.9 ms to 0.26 ms (see Benchmarks). A seek recording on local storage wouldn't show a difference that small, and nothing on screen changes, so the Evidence section stays "none, no user-visible change".

@Quick104

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: eea621cb9d9265a689bcdcae785434fa5572a2a5

I found no defects, so this review has no inline findings and I pushed no commits.

What I checked

  • Parity with the full walk. Without append_list, FFmpeg's playlist lists one generation's segments in rising order, and temp_file renames each segment into place before the playlist lists it. So the last listed segment on disk has both the highest number and the newest write time. The max(...) keeps the StartSegmentNumber - 1 floor for a playlist an earlier generation left below a later restart point. The only difference is the two-rename window the description discloses, during a same-recipe restart. In that window the staleness check gets the old generation's tail time instead of the new segment's. FFmpeg closes the window right away, so I found no decision it changes.
  • Callers. The throttler and copy_keyframe_plan.go read only ProducedHead, which is unchanged. The recovery staleness check reads LastProducedAt only when the head is at or past the start. The native API, jellycompat and the transcode node use LastProducedAt only for a log field. ProducedCount has no remaining readers in the repo: Go, web, docs and test data.
  • Segment pruner. It removes only segments behind the download floor, so it never removes the newest listed one.
  • Tests. go test ./internal/playback/ passes on this head. TestSegmentProgressFindsNewestListedSegment also passes on the base. That is expected for a parity test, so it guards the new walk against drift and doesn't prove a fix.
  • Benchmark, rerun on Linux with a local disk, 2 runs each, base db95c13bd against this head: 3,600 entries 2.7 ms → 0.24 ms, and 50,000 entries 52 ms → 3.5 ms. Allocations drop about 75%. This agrees with the numbers in the description.
  • fix(playback): stop segment waits when the request ends #2955 (segment waits). It edits different hunks of transcode.go and transcode_manifest_test.go. The two branches merge cleanly together, and go vet and the internal/playback tests pass on the combined tree. They can merge in either order. feat(playback): restart keyframe-planned copy streams mid-stream #1770 still has to drop its ProducedCount assignment if it merges after this PR, as the description says.

Remaining for maintainers

Validated features

No passed case on the v1.0 board reaches this code. #1148 C3 and #1149 C2 are not run yet. The PR body's Validation tasks: line is accurate.

User manual and clients

The manual is unaffected: no setting, default or visible behavior changes. No API change, so neither Apple nor Android needs follow-up.

Fit: 9/10 · Readiness: 9/10 — ready

  • Fit: it removes per-segment file stats from a check that runs every 5 seconds per transcode and on every seek. This keeps a long session cheap on small hosts and on network storage, without new settings or surface area.
  • Readiness: the change is small, the parity argument holds against the FFmpeg flags Silo passes, CI is green, and I reproduced the speedup locally. The one disclosed timing window changes no decision.

Review by Claude Code (claude-opus-5-5) acting for a maintainer.

@Quick104
Quick104 merged commit 1f5af76 into Silo-Server:main Oct 23, 2026
16 checks passed
rangoDJ added a commit to rangoDJ/silo-server that referenced this pull request Oct 25, 2026
Main's Silo-Server#3033 moves recording a planned segment request into
notePlannedSegmentRequest, which its subtitle renditions also call. Keep
this branch's narrower near-head case and its planned progress, manifest
and audio recipe helpers, and record the request through main's helper.

Main's Silo-Server#2954 drops SegmentProgress.ProducedCount, which nothing read;
planned progress no longer sets it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@blurbery
blurbery deleted the perf/segment-progress-tail-walk branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants