Skip to content

perf: root-cause fixes for endpoints still slow after #292 (NextUp, series badges, resume tail, subtitle fonts) - #350

Merged
Quick104 merged 7 commits into
mainfrom
perf/slow-endpoint-root-causes
Jul 9, 2026
Merged

Quick104 merged 7 commits into
mainfrom
perf/slow-endpoint-root-causes

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

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

What the user sees Endpoint(s) Before After
Next Up rail on the home screen /Shows/NextUp, native home sections 17–44s ~0.5–1.1s
Unwatched-count badges on TV shows /Items/Latest, /Items browse, search ~17s ~120ms
Continue Watching resume tail for bulk importers Users/{id}/Items/Resume 60–116s stops on page 1
Embedded subtitle fonts on anime /stream/{sid}/subtitles/{track}/fonts 17–60s (p95 ~33s) ~1–2s

Problem

"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/NextUp route 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 a
recent_completed pre-CTE of the most-recent nextUpAnchorMaxRows = 500 completed
rows via an ordered index walk, instead of DISTINCT ON over the whole history. A
Next 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 by
PostgresUserStore) computes total/watched/in-progress/played per series in one
GROUP BY e.series_id query with the same visibility/history semantics as the old
per-episode fanout. enrichSeriesListUserData / enrichDetailUserData
(internal/jellycompat/content_direct.go) use it when available and keep the
chunked 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 SupersededEpisodeProgressIDs now computes that updated_at cutoff and
passes it to CompletedProgressSnapshots, which — reading updated_at DESC — stops
paging 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), then
reads the files back — the media file is opened once, not N times
(internal/playback/subtitle_fonts.go). p95 ~30s → ~1–2s, output unchanged. The
32-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

  • The 5-page superseded-walk cap can, for a genuinely adversarial profile, let a
    superseded episode briefly reappear on Continue Watching until the stale
    in-progress entry ages out; this is logged, not silent.
  • The SQL rollup path is Postgres-only; SQLite-backed user stores fall back to the
    existing chunked path (unchanged behavior, unchanged cost).
  • The DB repair + three indexes (root causes 1 and 4) live only in the deployment's
    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 running
    container
    — the other four are cherry-picked into the deployed silo:local
    build; the fonts fix has only been validated by its unit tests and a manual
    extraction so far.

Verification

  • go build ./... and go vet ./... clean.
  • go test -race on internal/catalog, internal/jellycompat,
    internal/userstore/..., internal/sections, internal/playback.
  • EXPLAIN ANALYZE and endpoint timings above measured on the production database
    against the worst real profile, before/after: next-up 44.7s → 517ms; 50-series
    rollup ~17s → 123ms; subtitle-fonts p95 ~30s → ~1–2s.
  • Four of the five commits are cherry-picked into the live silo:local image
    (built 2026-07-08); post-deploy of the full branch, re-run the slow-request
    aggregation over docker logs silo to 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

    • Improved continue-watching and “Next Up” results so they stay responsive on large libraries.
    • Series pages and lists now show watch status using faster aggregated data, with the same visible results.
  • Bug Fixes

    • Reduced cases where recently updated items could make playback-related screens feel slow.
    • Added safeguards to prevent long-running background scans from going too far.
    • Subtitle font handling is now more reliable and processes attachments more efficiently.

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.
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Slow endpoint root cause fixes

Layer / File(s) Summary
Root cause investigation doc
docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md
Documents four database performance root causes, remediation plans, deliverables, and verification steps.
Bounded superseded-episode progress scan
internal/catalog/continue_watching_progress.go, internal/catalog/continue_watching_progress_test.go
Adds a page cap and notBefore cutoff to CompletedProgressSnapshots, stopping scans once in-progress episode age is reached, with warning logging and new tests.
Bounded Next Up global anchor query
internal/catalog/nextup_repo.go, internal/catalog/nextup_repo_test.go
Adds nextUpAnchorMaxRows and bounds the global anchor CTE while keeping series-scoped anchoring unbounded, with new query tests.
SQL series watch-state rollup with fallback
internal/userstore/progress_helpers.go, internal/userstore/pgstore/progress.go, internal/catalog/user_data_rollup.go, internal/jellycompat/content_direct.go, internal/jellycompat/content_direct_test.go
Adds SeriesWatchCounts/SeriesEpisodeRollupStore, a Postgres SQL aggregate implementation, SeasonUserDataFromCounts, and wiring that prefers the rollup with fallback to chunked per-episode aggregation.

Subtitle font extraction rework

Layer / File(s) Summary
Single-invocation font dump with watchdog
internal/playback/subtitle_fonts.go
Replaces per-attachment streaming extraction with a single ffmpeg -dump_attachment invocation and a concurrent watchdog that kills ffmpeg when dumped size exceeds the cap.
Font dump test coverage
internal/playback/subtitle_fonts_test.go
Adds a fake-ffmpeg shell helper and tests for argv order, single-invocation extraction, missing-dump skipping, and over-limit rejection.

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
Loading
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
Loading

Possibly related PRs

  • Silo-Server/silo-server#41: Both PRs modify buildListNextUpQuery's per-series anchor derivation and bounding logic in internal/catalog/nextup_repo.go.
  • Silo-Server/silo-server#114: Both PRs update CompletedProgressSnapshots paging/cutoff logic used for superseded-progress filtering.
  • Silo-Server/silo-server#292: Both PRs touch series watch-state rollup enrichment logic in internal/jellycompat/content_direct.go and EnrichSeriesUserData.

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the PR’s main performance fixes and names the affected endpoints after #292.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/slow-endpoint-root-causes

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.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 9, 2026

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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.

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_completed pulls 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_completed would regress the whole fix. The point of this change (root cause 2) is that recent_completed is a pure ordered index walk on idx_uwp_profile_completed with no join. Adding JOIN episodes before the LIMIT re-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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ab55cb and f24f70a.

📒 Files selected for processing (12)
  • docs/superpowers/plans/2026-07-06-slow-endpoint-root-causes.md
  • internal/catalog/continue_watching_progress.go
  • internal/catalog/continue_watching_progress_test.go
  • internal/catalog/nextup_repo.go
  • internal/catalog/nextup_repo_test.go
  • internal/catalog/user_data_rollup.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/content_direct_test.go
  • internal/playback/subtitle_fonts.go
  • internal/playback/subtitle_fonts_test.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/progress_helpers.go

Comment thread internal/playback/subtitle_fonts.go Resolved
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.
@Quick104
Quick104 merged commit 9d8acf5 into main Jul 9, 2026
11 checks passed
@Quick104
Quick104 deleted the perf/slow-endpoint-root-causes branch July 9, 2026 13:02
Quick104 pushed a commit that referenced this pull request Jul 10, 2026
…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.
Quick104 added a commit that referenced this pull request Aug 11, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Home screen and Latest rail are slow and don't scale under concurrent load

2 participants