Repository navigation
perf: root-cause fixes for endpoints still slow after #292 (NextUp, series badges, resume tail, subtitle fonts) - #350
Conversation
Five endpoint groups stayed slow after the home/Continue Watching/Latest latency work shipped: Resume (110s p95), NextUp (17s p95), Latest (17s), /Items, and the home sections routes. The caps and caches from PR #292 are live in the deployed binary; they bounded how many rows the loops touch but not what each underlying query costs. Documents the four confirmed root causes (4.3M stale completed-with-position progress rows + missing resume index, unbounded next-up anchor scan, per-episode series rollup fanout, two index-starved history/scanner paths) with live EXPLAIN ANALYZE measurements and the fix plan implemented by the follow-up commits. AI-use disclosure: analysis and doc produced with AI (Claude) assistance.
…ions The completed_episodes CTE in buildListNextUpQuery derived per-series anchors from the profile's ENTIRE completed history — DISTINCT ON over 233k rows joined to episodes for the worst bulk-import profile, then a per-series LATERAL that scans every episode of a fully-watched series before yielding nothing. 648 slow executions in a 19h window, 44.7s worst; this drove /Shows/NextUp (17.1s p95) and the next-up injection on the native home sections aggregate. Global queries now derive anchors from the profile's nextUpAnchorMaxRows (500) most recent completed rows — an ordered index walk on idx_uwp_profile_completed, with the hidden-items exclusion and date cutoff applied inside the bounded scan so hidden/old rows never consume the anchor budget. A next-up rail surfaces ~24 series; the 500 most recent completions cover every series that can realistically rank on it. Series-scoped calls (the show-detail tile) keep the unbounded shape: they must anchor on the series' last completed episode no matter how long ago it was watched, and are naturally bounded by one series. Measured on the live worst-case profile with the exact generated SQL: 44.7s worst / ~2.6s avg before; 10ms after (together with the one-time stale-resume-point data repair applied directly to the deployment DB — see docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md). AI-use disclosure: implemented with AI (Claude) assistance.
The series Played/UnplayedItemCount badge on list rails (per-library Latest, library browse, search results) and series detail pages was computed by materializing EVERY episode of every series on the page (episodeRepo.ListBySeriesIDs) and then batching per-episode progress+history lookups in 500-id chunks. A 50-series page of an episode-heavy library (Sports) expanded to 32,467 episode rows and ~65 sequential queries — measured 17-18s per /Items/Latest request, and PR #292's cached Latest fast path pays it on every response for series libraries. The same fanout made /Items?searchTerm=... slow whenever the result set was mostly series (Meilisearch itself answers in milliseconds). New optional store capability userstore.SeriesEpisodeRollupStore, implemented by PostgresUserStore as one GROUP BY e.series_id aggregate with semantics identical to the chunked path (episode availability via episode_libraries, hidden-items visibility on progress rows, completed-history fold, in-progress = not watched with position > 0 — verified value-for-value against the old semantics on a real 1,586-episode series). enrichSeriesListUserData and enrichDetailUserData use it when present; SQLite-backed stores and rollup query failures keep the existing chunked path as fallback. catalog.SeasonUserDataFromCounts pins the counts-to-DTO mapping to EpisodeRollupUserData. Measured on the live worst-case profile against the real 50-series Sports Latest page: ~17s of chunked round-trips before, 119ms in one query after. Part of docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md. AI-use disclosure: implemented with AI (Claude) assistance.
The Resume / Continue Watching superseded-episode filter loaded a profile's *entire* completed history into memory on every request that contained an in-progress episode: CompletedProgressSnapshots paged user_watch_progress WHERE completed=TRUE with no upper bound. The 2026-07-06 slow-query comparison showed this surviving as a 60-116s Resume tail even after the in-progress index landed live, because the 4.3M zeroed Plex-import rows are still completed=TRUE and were re-walked every load. A completed episode can only supersede an in-progress one it was finished more recently than (the query gates on done_progress.updated_at > ip_progress.updated_at), so only completed rows newer than the oldest in-progress entry can matter. Compute that cutoff in SupersededEpisodeProgressIDs and pass it to CompletedProgressSnapshots, which — since the completed listing is ordered updated_at DESC — stops paging as soon as it crosses the cutoff. Import-heavy profiles whose back-catalogue predates their current in-progress items now stop on the first page instead of paging hundreds of thousands of irrelevant rows. Correctness is unchanged: no relevant superseding row is excluded.
The updated_at cutoff added in the previous commit bounds the completed walk on the relevance axis, but a very old in-progress entry sitting behind a large volume of newer completions could still page deep. Add a 5-page (2,500-row) hard backstop on top of the cutoff: normal profiles still stop on page one via the cutoff, and only the adversarial tail hits the cap. When it engages the tail of the completed set goes unscanned, so a superseded episode could momentarily survive on Continue Watching — we log a warning when that happens (with profile_id + rows scanned) rather than mis-filter silently, and it self-corrects once the stale in-progress entry ages out of the scanned window.
Embedded ASS/SSA font extraction spawned one ffmpeg process per font
attachment, each re-opening the (usually CephFS-backed) media file. Anime
releases carry 15-47 fonts, so the per-spawn file-open cost dominated and
pushed GET /api/v1/stream/{sid}/subtitles/{track}/fonts to a 17-60 s plateau
(p95 ~33 s in the live logs).
Collapse the N spawns into one ffmpeg invocation that dumps every attachment
to a temp dir (-dump_attachment:idx path ... -i file -map 0:t? -c copy), then
read the files back. The file is opened once instead of N times, taking p95
from ~30 s to ~1-2 s with no change to output.
Safety is preserved. The 32-attachment / 32 MiB caps still apply: attachment
size is stat'd before read so an over-limit font never enters memory, and a
watchdog polls the dump dir and kills ffmpeg if its on-disk output crosses the
cap -- restoring the hard bound the old pipe-per-attachment reader enforced by
killing at maxBytes+1, so a container with oversized "font" attachments can't
fill the disk.
Part of the slow-endpoint follow-up; see
slow-query-analysis/subtitle-fonts-extraction-findings.md.
📝 WalkthroughWalkthroughThis PR addresses slow-endpoint root causes: bounding superseded-episode progress scans with a cutoff and page cap, bounding Next Up's global anchor query via a limited recent-completions CTE, adding a SQL-based series watch-state rollup with fallback, and reworking subtitle font extraction to a single ffmpeg dump with a size watchdog. ChangesSlow endpoint root cause fixes
Subtitle font extraction rework
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant ContentDirect as content_direct.go
participant Store as PostgresUserStore
participant Fallback as Chunked per-episode path
ContentDirect->>Store: SeriesEpisodeWatchCounts(profileID, seriesIDs)
alt rollup succeeds
Store-->>ContentDirect: map of SeriesWatchCounts
ContentDirect->>ContentDirect: SeasonUserDataFromCounts per series
else rollup fails
ContentDirect->>Fallback: list episodes and chunk progress
Fallback-->>ContentDirect: EpisodeRollupUserData
end
sequenceDiagram
participant ExtractAttachedSubtitleFonts
participant dumpFontAttachments
participant ffmpeg
participant watchDumpSize
ExtractAttachedSubtitleFonts->>dumpFontAttachments: extract(maxBytes)
dumpFontAttachments->>ffmpeg: run with -dump_attachment per stream
dumpFontAttachments->>watchDumpSize: start watchdog(tempDir, maxBytes)
watchDumpSize->>watchDumpSize: poll dirBytes(tempDir)
watchDumpSize->>ffmpeg: kill process if size exceeds cap
ffmpeg-->>dumpFontAttachments: dump files written
dumpFontAttachments-->>ExtractAttachedSubtitleFonts: SubtitleFontAttachment list
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f24f70ac87
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| ) | ||
| %s | ||
| ORDER BY uwp.updated_at DESC | ||
| LIMIT %d |
There was a problem hiding this comment.
Apply the anchor cap after filtering to episodes
When a profile has 500 newer completed progress rows that are not episodes (for example movies or books), this LIMIT fills recent_completed before the following JOIN episodes can discard them. The old query joined episodes over the whole completed set, so those users still got next-up rows from older episode completions; after this change /Shows/NextUp can return an empty or short rail even though eligible series exist. Move the cap after restricting to episode progress, or otherwise over-fetch episode anchors so non-episode completions do not consume the budget.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping this one — the fix would cost more than the edge case it guards.
- The 500 cap is already a deep over-fetch. A Next Up rail surfaces ~24 series;
recent_completedpulls the 500 most-recent completions. For non-episode completions to starve the rail, a profile would need 500+ movie/book finishes all newer than every one of their in-progress shows' most recent episode completion — and even then Next Up only shows a couple dozen rows. - Filtering to episodes inside
recent_completedwould regress the whole fix. The point of this change (root cause 2) is thatrecent_completedis a pure ordered index walk onidx_uwp_profile_completedwith no join. AddingJOIN episodesbefore theLIMITre-introduces the join over the entire completed set — exactly the 44.7s shape we bounded away. Over-fetching episode anchors specifically requires that join.
If a movie-heavy profile ever does regress in practice we can bump nextUpAnchorMaxRows, which stays an index-only walk.
There was a problem hiding this comment.
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 `@docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md`:
- Around line 191-192: The plan doc currently says subtitle extraction is out of
scope, but the PR scope includes subtitle font extraction; update the bullet in
the plan to match the actual work. In the markdown section describing
`/api/v1/stream/{session_id}/subtitles/{track}`, either remove the “out of
scope” claim or revise it so it aligns with the
`/stream/{sid}/subtitles/{track}/fonts` single-pass ffmpeg optimization
referenced elsewhere in the plan, keeping the scope consistent across the
document.
In `@internal/playback/subtitle_fonts.go`:
- Line 130: The over-limit errors in dumpFontAttachments are using the package
constant instead of the function’s maxBytes argument, so the reported limit is
wrong when callers pass a different cap. Update both error संदेश locations in
dumpFontAttachments to interpolate maxBytes, and keep the messages consistent
for the attachment-size checks so the actual enforced bound is shown.
🪄 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: a122e629-48be-4feb-abff-ee0e034c0cd2
📒 Files selected for processing (12)
docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.mdinternal/catalog/continue_watching_progress.gointernal/catalog/continue_watching_progress_test.gointernal/catalog/nextup_repo.gointernal/catalog/nextup_repo_test.gointernal/catalog/user_data_rollup.gointernal/jellycompat/content_direct.gointernal/jellycompat/content_direct_test.gointernal/playback/subtitle_fonts.gointernal/playback/subtitle_fonts_test.gointernal/userstore/pgstore/progress.gointernal/userstore/progress_helpers.go
Address PR #350 review: - dumpFontAttachments reported the maxSubtitleFontBytes package constant in both over-limit errors instead of the maxBytes argument the caller passed, so the message misstated the enforced bound whenever a different cap was in effect (as the tests use). Interpolate maxBytes in both messages. - The root-cause plan claimed subtitle extraction was 'out of scope' while the branch actually optimizes /subtitles/{track}/fonts. Scope the out-of-scope note to subtitle *track* conversion and record the fonts single-pass work as deliverable 5.
…eries badges, resume tail, subtitle fonts) (#350) * docs(plans): root-cause analysis for endpoints still slow after PR #292 Five endpoint groups stayed slow after the home/Continue Watching/Latest latency work shipped: Resume (110s p95), NextUp (17s p95), Latest (17s), /Items, and the home sections routes. The caps and caches from PR #292 are live in the deployed binary; they bounded how many rows the loops touch but not what each underlying query costs. Documents the four confirmed root causes (4.3M stale completed-with-position progress rows + missing resume index, unbounded next-up anchor scan, per-episode series rollup fanout, two index-starved history/scanner paths) with live EXPLAIN ANALYZE measurements and the fix plan implemented by the follow-up commits. AI-use disclosure: analysis and doc produced with AI (Claude) assistance. * perf(catalog): bound the global next-up anchor scan to recent completions The completed_episodes CTE in buildListNextUpQuery derived per-series anchors from the profile's ENTIRE completed history — DISTINCT ON over 233k rows joined to episodes for the worst bulk-import profile, then a per-series LATERAL that scans every episode of a fully-watched series before yielding nothing. 648 slow executions in a 19h window, 44.7s worst; this drove /Shows/NextUp (17.1s p95) and the next-up injection on the native home sections aggregate. Global queries now derive anchors from the profile's nextUpAnchorMaxRows (500) most recent completed rows — an ordered index walk on idx_uwp_profile_completed, with the hidden-items exclusion and date cutoff applied inside the bounded scan so hidden/old rows never consume the anchor budget. A next-up rail surfaces ~24 series; the 500 most recent completions cover every series that can realistically rank on it. Series-scoped calls (the show-detail tile) keep the unbounded shape: they must anchor on the series' last completed episode no matter how long ago it was watched, and are naturally bounded by one series. Measured on the live worst-case profile with the exact generated SQL: 44.7s worst / ~2.6s avg before; 10ms after (together with the one-time stale-resume-point data repair applied directly to the deployment DB — see docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md). AI-use disclosure: implemented with AI (Claude) assistance. * perf(jellycompat,userstore): aggregate series watch-state rollup in SQL The series Played/UnplayedItemCount badge on list rails (per-library Latest, library browse, search results) and series detail pages was computed by materializing EVERY episode of every series on the page (episodeRepo.ListBySeriesIDs) and then batching per-episode progress+history lookups in 500-id chunks. A 50-series page of an episode-heavy library (Sports) expanded to 32,467 episode rows and ~65 sequential queries — measured 17-18s per /Items/Latest request, and PR #292's cached Latest fast path pays it on every response for series libraries. The same fanout made /Items?searchTerm=... slow whenever the result set was mostly series (Meilisearch itself answers in milliseconds). New optional store capability userstore.SeriesEpisodeRollupStore, implemented by PostgresUserStore as one GROUP BY e.series_id aggregate with semantics identical to the chunked path (episode availability via episode_libraries, hidden-items visibility on progress rows, completed-history fold, in-progress = not watched with position > 0 — verified value-for-value against the old semantics on a real 1,586-episode series). enrichSeriesListUserData and enrichDetailUserData use it when present; SQLite-backed stores and rollup query failures keep the existing chunked path as fallback. catalog.SeasonUserDataFromCounts pins the counts-to-DTO mapping to EpisodeRollupUserData. Measured on the live worst-case profile against the real 50-series Sports Latest page: ~17s of chunked round-trips before, 119ms in one query after. Part of docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md. AI-use disclosure: implemented with AI (Claude) assistance. * perf(catalog): bound superseded-episode completed walk to recent history The Resume / Continue Watching superseded-episode filter loaded a profile's *entire* completed history into memory on every request that contained an in-progress episode: CompletedProgressSnapshots paged user_watch_progress WHERE completed=TRUE with no upper bound. The 2026-07-06 slow-query comparison showed this surviving as a 60-116s Resume tail even after the in-progress index landed live, because the 4.3M zeroed Plex-import rows are still completed=TRUE and were re-walked every load. A completed episode can only supersede an in-progress one it was finished more recently than (the query gates on done_progress.updated_at > ip_progress.updated_at), so only completed rows newer than the oldest in-progress entry can matter. Compute that cutoff in SupersededEpisodeProgressIDs and pass it to CompletedProgressSnapshots, which — since the completed listing is ordered updated_at DESC — stops paging as soon as it crosses the cutoff. Import-heavy profiles whose back-catalogue predates their current in-progress items now stop on the first page instead of paging hundreds of thousands of irrelevant rows. Correctness is unchanged: no relevant superseding row is excluded. * perf(catalog): hard-cap superseded-episode completed walk at 5 pages The updated_at cutoff added in the previous commit bounds the completed walk on the relevance axis, but a very old in-progress entry sitting behind a large volume of newer completions could still page deep. Add a 5-page (2,500-row) hard backstop on top of the cutoff: normal profiles still stop on page one via the cutoff, and only the adversarial tail hits the cap. When it engages the tail of the completed set goes unscanned, so a superseded episode could momentarily survive on Continue Watching — we log a warning when that happens (with profile_id + rows scanned) rather than mis-filter silently, and it self-corrects once the stale in-progress entry ages out of the scanned window. * perf(playback): extract subtitle fonts in a single ffmpeg pass Embedded ASS/SSA font extraction spawned one ffmpeg process per font attachment, each re-opening the (usually CephFS-backed) media file. Anime releases carry 15-47 fonts, so the per-spawn file-open cost dominated and pushed GET /api/v1/stream/{sid}/subtitles/{track}/fonts to a 17-60 s plateau (p95 ~33 s in the live logs). Collapse the N spawns into one ffmpeg invocation that dumps every attachment to a temp dir (-dump_attachment:idx path ... -i file -map 0:t? -c copy), then read the files back. The file is opened once instead of N times, taking p95 from ~30 s to ~1-2 s with no change to output. Safety is preserved. The 32-attachment / 32 MiB caps still apply: attachment size is stat'd before read so an over-limit font never enters memory, and a watchdog polls the dump dir and kills ffmpeg if its on-disk output crosses the cap -- restoring the hard bound the old pipe-per-attachment reader enforced by killing at maxBytes+1, so a container with oversized "font" attachments can't fill the disk. Part of the slow-endpoint follow-up; see slow-query-analysis/subtitle-fonts-extraction-findings.md. * fix(review): report enforced font-byte cap; correct doc subtitle scope Address PR #350 review: - dumpFontAttachments reported the maxSubtitleFontBytes package constant in both over-limit errors instead of the maxBytes argument the caller passed, so the message misstated the enforced bound whenever a different cap was in effect (as the tests use). Interpolate maxBytes in both messages. - The root-cause plan claimed subtitle extraction was 'out of scope' while the branch actually optimizes /subtitles/{track}/fonts. Scope the out-of-scope note to subtitle *track* conversion and record the fonts single-pass work as deliverable 5.
* fix(catalog): bound Next Up anchors by distinct series, not rows The global Next Up query capped its anchor scan at the 500 most recently completed rows (nextUpAnchorMaxRows, #350). Bulk mark-watched writes hundreds of completed rows with the newest timestamps, so one series could flood the whole window and evict every other series from the rail - observed in production wiping a user's Next Up row entirely. Replace the row-capped CTE with a recursive skip-scan over idx_uwp_profile_completed that emits the newest completed row of each not-yet-seen series and stops after nextUpAnchorMaxSeries (96) distinct series. A compound (updated_at, media_item_id) cursor keeps the walk total when bulk writes share one timestamp across series. The series-scoped branch (show-detail tile) keeps its unbounded shape. DB-backed regression tests cover the flood shape (600 same-timestamp rows of one series must not evict others) and same-timestamp anchors across series; the flood test fails against the previous query. Fixes #592 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(catalog): continue Next Up anchor walk until enough eligible series found The 96-series walk budget counted visited series, but eligibility (next episode exists with a present file, no newer partial progress) is only decided downstream, so 96 consecutive ineligible anchors - all caught up, unavailable, or blocked - still emptied the rail and silently capped /Shows/NextUp pagination at whatever survived one walk. Run the walk in batches: each batch keeps the 96-series budget, reports its frontier (compound cursor position, seen-series array, rows walked), and ListNextUp resumes the next batch below that frontier until the requested limit is filled, history is exhausted (frontier short of the budget), or a 10-batch runaway guard trips (logged, never silent). Batches emit anchors in strictly descending (updated_at, media_item_id) order, so appending preserves rail order. Series-scoped queries keep their single-shot shape. DB-backed regressions: 100 fully-watched series must not hide older series with eligible next episodes (fails on the single-batch code), and an all-caught-up profile returns empty without spinning to the batch cap. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(catalog): anchor Next Up on the highest episode, not the highest ID Review follow-up to the anchor walk. Two issues remained after the batching fix. The walk ordered anchors by (updated_at, media_item_id) and then by (season, episode). media_item_id is unique, so no two rows ever tie on that pair and the season/episode clause was unreachable. For a bulk mark-watched series — every row written with one timestamp — the anchor was therefore whichever content_id sorted highest. With production-shape 18-digit IDs where season 2 was scanned before a season-1 backfill, season 1 sorts higher, so the rail surfaced s01e04: an episode following one the user had already watched. Choosing the series and choosing its anchor episode are now separate steps. The walk still advances on the compound cursor, which is the total order it needs; a lateral then picks the highest (season, episode) among that series' rows sharing pick.updated_at, matching what the series-scoped branch already did. Pinning updated_at instead of re-sorting keeps it an index probe, and both rows carry the same updated_at, so cursor order and the reported CompletedAt are unchanged. Also adds the index the compound cursor needs. idx_uwp_profile_completed stops at updated_at, so the media_item_id half of the seek was a filter and every step re-read the rows tied on one timestamp — the exact shape a bulk mark-watched profile has. Measured by dropping and recreating the index around the shipped query on a synthetic 40k-row profile: 341ms -> 224ms, same plan shape otherwise. Verified against Postgres 18.3. The new DB regression seeds the scanned-out-of-order ID shape and fails on the previous ordering (returns s01e04, wants s02e04); the SQL-shape test pins that media_item_id can no longer gate the episode choice. Part of #592 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Closes #293 (same scope item as #292).
Extends #292. That PR bounded how many rows the home-screen loops touch; this
one attacks what each underlying query costs — so the endpoints that stayed slow
after #292 shipped finally drop out of the ≥1s report. Five code commits plus the
root-cause write-up.
Root-cause analysis (measured on the live worst-case profile) is committed on the
branch:
docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md.Performance
/Shows/NextUp, native home sections/Items/Latest,/Itemsbrowse, searchUsers/{id}/Items/Resume/stream/{sid}/subtitles/{track}/fontsProblem
"Next Up" re-read a viewer's entire finished history on every load. For anyone
who bulk-imported a Plex history (a quarter-million watched rows), the home screen's
Next Up rail walked the whole back-catalogue to figure out which shows to anchor on,
then scanned every episode of each already-finished show looking for one that wasn't
there. Worst observed: 44.8s. It dragged the native home screen and the Jellyfin
/Shows/NextUproute down with it.Every list of TV shows rebuilt its "unwatched" badges the slow way. To show the
"N unwatched episodes" badge on a row of shows — per-library "Latest", library
browse, search results — the server loaded every episode of every show on the page
into memory and asked the watch database about them in batches. One 50-show page of
a big Sports library expanded to 32,000+ episodes and ~65 sequential round-trips
(~17s). The as-you-type search box paid the same toll.
Continue Watching could stall for a minute-plus for heavy importers. The filter
that hides episodes you've since finished loaded a profile's entire completed
history on every load that contained an in-progress episode. Even after the live DB
repair, the 4.3M zeroed import rows kept getting re-walked — leaving a 60–116s tail
on the Resume list.
Anime subtitle fonts took half a minute to extract. Playing a release with
embedded ASS/SSA subtitles, the server spawned a separate ffmpeg process for each
font attachment (anime carries 15–47 of them), re-opening the CephFS-backed media
file every time. The fonts endpoint sat at a 17–60s plateau (p95 ~33s).
Solution
Companion to #292's caps/caches — this branch makes each capped unit cheap. The
one-time DB repair and three supporting indexes from the same investigation (root
causes 1 and 4 in the doc) were already applied directly to the live database on
2026-07-06 and are deliberately not shipped as migrations — so there are no
migration files here by design.
perf(catalog): bound the global next-up anchor scan to recent completions
buildListNextUpQuery(internal/catalog/nextup_repo.go) now derives series from arecent_completedpre-CTE of the most-recentnextUpAnchorMaxRows = 500completedrows via an ordered index walk, instead of
DISTINCT ONover the whole history. ANext Up rail surfaces ~24 series; 500 recent completions cover every realistically
surfaceable one. Series-scoped calls (show-detail tile) keep the unbounded shape —
they're already bounded by one series. Live worst-profile: 44.7s → 517ms.
perf(jellycompat,userstore): aggregate series watch-state rollup in SQL
New optional
userstore.SeriesEpisodeRollupStore(implemented byPostgresUserStore) computes total/watched/in-progress/played per series in oneGROUP BY e.series_idquery with the same visibility/history semantics as the oldper-episode fanout.
enrichSeriesListUserData/enrichDetailUserData(
internal/jellycompat/content_direct.go) use it when available and keep thechunked path as a SQLite fallback. Live Sports "Latest": ~17s → 123ms. Also
fixes the slow series-heavy
/Items?searchTerm=…calls.perf(catalog): bound superseded-episode completed walk to recent history
A completed episode can only supersede an in-progress one it finished more recently
than, so
SupersededEpisodeProgressIDsnow computes thatupdated_atcutoff andpasses it to
CompletedProgressSnapshots, which — readingupdated_at DESC— stopspaging once it crosses the cutoff. Import-heavy profiles stop on page one instead of
paging hundreds of thousands of irrelevant rows. Correctness unchanged.
perf(catalog): hard-cap superseded-episode completed walk at 5 pages
Backstop on top of the cutoff: a 5-page (2,500-row) hard cap for the adversarial
case of a very old in-progress entry behind a large volume of newer completions.
When it engages, a superseded episode could momentarily survive on Continue Watching
— we log a warning (profile_id + rows scanned) rather than mis-filter silently,
and it self-corrects once the stale entry ages out of the scanned window.
perf(playback): extract subtitle fonts in a single ffmpeg pass
Collapse the N per-attachment ffmpeg spawns into one invocation that dumps every
attachment to a temp dir (
-dump_attachment:idx … -i file -map 0:t? -c copy), thenreads the files back — the media file is opened once, not N times
(
internal/playback/subtitle_fonts.go). p95 ~30s → ~1–2s, output unchanged. The32-attachment / 32 MiB caps are preserved: sizes are stat'd before read and a
watchdog kills ffmpeg if on-disk output crosses the cap.
Risk / follow-ups
superseded episode briefly reappear on Continue Watching until the stale
in-progress entry ages out; this is logged, not silent.
existing chunked path (unchanged behavior, unchanged cost).
ops notes, not this repo — a fresh deployment would need them re-applied. Tracked
as a follow-up to decide whether to formalize them as migrations.
f24f70ac(subtitle fonts) is the one commit not yet exercised in the runningcontainer — the other four are cherry-picked into the deployed
silo:localbuild; the fonts fix has only been validated by its unit tests and a manual
extraction so far.
Verification
go build ./...andgo vet ./...clean.go test -raceoninternal/catalog,internal/jellycompat,internal/userstore/...,internal/sections,internal/playback.against the worst real profile, before/after: next-up 44.7s → 517ms; 50-series
rollup ~17s → 123ms; subtitle-fonts p95 ~30s → ~1–2s.
silo:localimage(built 2026-07-08); post-deploy of the full branch, re-run the slow-request
aggregation over
docker logs siloto confirm the endpoint groups drop out of the≥1s report.
AI-use disclosure
Investigation, root-cause analysis, and these changes were prepared with AI
assistance (Claude Code) and reviewed before submission.
Summary by CodeRabbit
New Features
Bug Fixes