Skip to content

perf: cut home-screen, Continue Watching, and Latest latency; cache shared home rails - #292

Merged
Quick104 merged 11 commits into
mainfrom
perf/section-fetch-optimization
Jul 5, 2026
Merged

Quick104 merged 11 commits into
mainfrom
perf/section-fetch-optimization

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #293.

Five commits from a log-driven performance investigation of the home screen and
Jellyfin-compat browse paths. The first three cut targeted latency (Continue
Watching, detail rows, Latest browse, home-row concurrency); the last two add a
shared, access-scope-keyed list cache so the home screen and Latest rail stop
rebuilding the same shared lists per user, per request. Findings were verified
with adversarial review; the gaps surfaced (see below) are fixed and covered by
tests.

Problem

The same shared rows are rebuilt for every user, on every request. Rows like
"Recently Added", genre rails, "Trending on this server", "Most Watched", "New to
Library", editorial/featured, and admin-curated lists are identical for everyone
who can see the same libraries — only the watched checkmarks and play position are
personal. Yet each request recomputes the whole list against the database, so
database load grows with concurrent users rather than with distinct content, and
the home screen degrades exactly when the server is busiest.

Continue Watching could hang for tens of seconds. Some clients ask for the
Resume list and an exact total count; to produce that count the server read a
profile's entire watch history — huge for heavy watchers — and the request
stalled (worst observed ~36s). This was worst for heavy watchers whose recent
in-progress rows are mostly dismissed, so the visible list stays sparse and the
scan kept going.

Detail-heavy rows (Latest, browse) did redundant per-item work. Building a
50-item row with full details, the server looked up each item's watch-status one
at a time (~100 tiny database trips per page).

The "Latest" rail was slow for heavy watchers with multiple libraries.
/Items/Latest hides already-watched titles. For someone who's seen most of the
newest items, the server exhausted its fast lane and dropped onto a slow lane
that scans the entire movie catalog (~0.8–1.6s). This rail loads ~10k/day.

Large home screens build their rows too slowly. A 32-row home layout resolved
only 4 rows at a time.

Solution

perf(jellycompat,sections): bound resume scan, batch leaf detail progress, widen section concurrency

  • loadProgressPage now caps its scan at resumeScanMaxRows = 300
    (internal/jellycompat/handlers_items.go). The cap is unconditional — it
    fires even when the visible (post-filter) page never fills, closing the
    sparse-visible-set case where a heavy watcher's mostly-dismissed history would
    otherwise be scanned end to end. Beyond the cap the total is a clamped lower
    bound. Covered by TestLoadProgressPage_BoundsScanForSparseVisibleSet.
  • GetItemDetailsByIDs (internal/jellycompat/content_direct.go) batches
    movie/episode progress via ListProgressWithCompletedHistory instead of a
    per-item GetProgressWithCompletedHistory (~100 sequential queries per 50-item
    page). Series keep the per-item episode-rollup path (they own no progress row).
    Output is unchanged; a batch-lookup failure is now logged (slog.Warn) rather
    than silently dropping played state for the whole page.
  • fetchAllMaxConcurrency raised 4 → 6 (internal/sections/fetcher.go) to cut
    FetchAll wave count for large home layouts, kept modest against the default
    20-connection pool (documented inline so it can't silently drift past the pool).

perf(jellycompat): keep Latest browse on the cross-library fast path under isPlayed

  • The isPlayed overlay can't be pushed into SQL, so browse over-fetches and
    filters locally. The cross-library recently-added fast path
    (BrowseRecentlyAddedAcrossLibraries, ~1ms/library index walk) was gated on
    Offset == 0; a heavy watcher needed a 2nd chunk and fell through to
    BrowsePage's whole-catalog MIN(first_seen_at) + GROUP BY (~755ms/call).
  • Fix (internal/jellycompat/content_direct.go): fetch the whole over-fetch
    budget (maxScannedRows) in one merged fast-path walk, so the loop fills from a
    single call and never advances filters.Offset into BrowsePage. Caveat
    documented inline: the helper clamps to MaxLimit=1000, so this fully avoids
    the fall-through for requestedLimit ≤ 200 (the Latest hot path, limit ~24–50);
    very large limits (201–1000) can still page through but remain correct.

perf(sections): cache shared user-agnostic home rails per access scope

  • Adds a process-global resolved-list cache (internal/sections/resolvedlistcache.go)
    at the FetchOne choke point. User-agnostic section types (recently added,
    recently released, genre, custom filter, critically acclaimed, award winners,
    format showcase, seasonal, mood, trending-on-server, new-to-library, most
    watched, trending-discover, admin-curated lists, and library collections) are
    built once per access scope, cached with a 15m TTL, and refreshed in the
    background 3m before expiry; singleflight collapses cold-miss stampedes.
  • The per-user overlay (watched flags, play position, presigned posters) still
    runs fresh in buildSectionsResponse (internal/api/handlers/sections.go), so
    no profile state is shared. Random and per-user rows (Continue Watching, Next
    Up, recommendations, hidden gems, forgotten favorites, activity feed, user
    collections) bypass the cache.
  • Security-critical key: resolvedListCacheKey captures every access boundary
    (sorted accessible/disabled libraries, max content rating, excluded media
    types, allowed-content-id allow-list, name prefix, section type + config hash +
    item limit) and nothing per-user, so entries are safely shared. Empty
    membership is never cached (avoids freezing a transiently empty rail);
    background refreshes are bounded by a 30s timeout.

perf(jellycompat): serve per-library Latest via the cached recently-added section

  • A per-library /Items/Latest for a movies or series library is the same
    user-agnostic list as the native "recently added" rail (both order by
    mil.first_seen_at DESC). HandleLatest (internal/jellycompat/handlers_items.go)
    now routes those through FetchOne(SectionRecentlyAdded) so they reuse the
    shared cache; the per-user overlay tail is extracted into buildLatestItemDTOs,
    shared by both the native and BrowseItems paths (no duplicated overlay logic).
  • To let the compat Latest and the native rail share one cache entry,
    resolvedListCacheKey no longer includes the arbitrary section ID (audited: no
    cacheable type derives membership from its own ID; the sole s.ID read lives in
    the non-cacheable user-collection branch). Access-scope isolation is unchanged.
  • Restricted to movies/series libraries; ebook/music/manga/mixed libraries,
    deeper pages, isPlayed, backdrop-required, and cross-type requests fall back
    to the unchanged BrowseItems path (which the commit above just made faster) — so
    no non-video items ever reach a Jellyfin client and empty rails stay empty.

Plain-language issue list

Shared home-screen rows were rebuilt for every user

  • Before → After: database work for the shared rows drops from roughly
    (rows × concurrent requests) to (rows × distinct access scopes) per 15-minute
    window — a warm home load runs zero section queries for these rows.
  • Fix: build each shared row (recently added, genre, trending, admin lists, …)
    once per "who can see what" group and reuse it; each person's watched marks and
    poster images are still applied fresh on top, so nobody sees another's state.
  • Notes: newly scanned content can appear up to ~15 min late in those rows;
    personalized rows (Continue Watching, Next Up, For You) are never cached.

"Latest" for movie/TV libraries now reuses that cache

  • Fix: a movies/series library's Latest rail is the same list as its "recently
    added" row, so it now serves from the shared cache instead of rebuilding. Other
    library types keep their exact existing behavior.
  • Notes: shares one cached copy with the native rail for the same libraries.

Continue Watching could hang for tens of seconds

  • Before → After: up to ~36s → under ~0.3s
  • Fix: apps that ask for an exact "total items" count made the server read a
    person's whole history; we cap the read at ~1,000 recent items and return a
    "1000+"-style count. The cap now applies even when most recent items are hidden
    (dismissed), so it can't run away.
  • Notes: the specific 36s log entry came through a related path we're addressing
    separately, but this closes the general risk. No visible change for normal users.

Detail rows did redundant per-item work

  • Before → After: removes ~50–150ms of wasted work per page
  • Fix: ask the database about all 50 items' watch-status at once instead of one
    at a time. TV shows still use the per-show method (they need it).
  • Notes: on-screen result is identical; a lookup failure is now logged instead of
    silently blanking watch-state.

"Latest" rail slow for heavy watchers with multiple libraries

  • Before → After: ~0.8–1.6s → ~0.05–0.15s (≈8–10×)
  • Fix: grab a bigger batch on the fast lane up front so it never drops onto the
    catalog-wide slow lane.
  • Notes: only affected people with 2+ libraries and lots of watch history.
    ~10k/day.

Large home screens built rows too slowly

  • Before → After: a 32-row screen goes from ~8 build "waves" to ~6
  • Fix: build 6 rows in parallel instead of 4.
  • Notes: kept modest on purpose — the database allows only 20 simultaneous
    connections, so going higher could hurt under concurrent load without a wider
    pool. The shared-list cache relieves some of this pressure (cached rows do no
    database work), but validate under real concurrent load before raising further.

Risk / follow-ups

  • Shared-list cache staleness: newly scanned content appears up to ~15 min
    late in cached rails. Optional near-instant invalidation on scan-complete
    (Redis EventScanComplete already exists) is a follow-up, not wired here.
  • Cache key is security-critical: if it failed to capture an access boundary
    it could cross-serve content. Covered by scope-isolation and content-boundary
    tests; when in doubt a field is added to the key.
  • Latest-via-cache is limited to movies/series libraries by design; every
    other library type keeps its exact BrowseItems behavior.
  • Concurrency 4→6 trades pool pressure for latency; validate under real
    concurrent home load before raising further (candidate for a config knob if the
    pool is re-tuned).
  • Resume total beyond the cap is a clamped lower bound (a "1000+"-style total).
  • Deferred to their own PRs: the hourly Continue Watching cold-recompute spike,
    Shows/{id}/Episodes pagination (client-visible, needs Android/Apple
    coordination), NextUp dedup + SQL-side Continue Watching filtering (structural),
    and applying the same shared-list cache to the cross-library (no-parentId)
    /Items/Latest browse path.
  • Dropped: content_id-derived NextUp rewrite (tiny gain, ::int ordering-
    correctness risk).

Verification

  • go build ./..., go vet, gofmt -l clean on all changed files.
  • go test -race ./internal/jellycompat/ ./internal/sections/ ./internal/catalog/
    pass, including TestLoadProgressPage_BoundsScanForSparseVisibleSet and the new
    cache tests (scope isolation, content-boundary key, section-ID-independent key,
    shared-across-surfaces single build, refresh-ahead non-blocking, stampede
    collapse, empty-not-cached, and Latest→recently-added config parity).
  • make verify-local-paths clean.
  • Adversarial review across leaf-progress parity, browse fast-path, resume cap,
    concurrency, and the cache (access-key completeness, shallow-copy safety,
    empty-caching, background-refresh timeout, mixed-library parity). Gaps found
    were fixed and tested.
  • EXPLAIN (ANALYZE, BUFFERS) confirmed the browse slow path (~755ms whole-catalog
    GROUP BY) vs the fast path (~1ms/library); detail-progress batching verified
    output-identical to the per-item path.

AI-use disclosure

Implemented with AI (Claude) assistance.

Summary by CodeRabbit

  • New Features

    • Faster browsing and “Latest” results for eligible libraries, with improved caching and batched image loading.
    • Continue Watching now stops scanning sooner for sparse results, improving load times.
    • Favorites, seasons, and episodes now load artwork more efficiently.
  • Bug Fixes

    • Fixed stale plugin and metadata updates after plugin lifecycle changes.
    • Improved series watch-state display in list views and latest results.
    • Reduced slowdowns and stalls in resume, next-up, and section browsing flows.

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 42b4c3ff-2815-4f52-aed0-a39d71f6db56

📥 Commits

Reviewing files that changed from the base of the PR and between bddf499 and d75a78c.

📒 Files selected for processing (14)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-07-03-section-fetch-performance.md
  • internal/catalog/access_cache_key.go
  • internal/catalog/audiobook_groups_cache.go
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/latest_via_sections_test.go
  • internal/jellycompat/presign_list.go
  • internal/jellycompat/userdata_direct.go
  • internal/sections/fetcher.go
  • internal/sections/resolvedlistcache.go
  • internal/sections/resolvedlistcache_test.go
💤 Files with no reviewable changes (1)
  • docs/superpowers/plans/2026-07-03-section-fetch-performance.md
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/jellycompat/presign_list.go
  • cmd/silo/main.go
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/userdata_direct.go
  • internal/jellycompat/latest_via_sections_test.go
  • internal/jellycompat/content_direct_test.go
  • internal/sections/resolvedlistcache_test.go
  • internal/jellycompat/handlers_items.go

📝 Walkthrough

Walkthrough

This PR adds a process-global resolved-list cache for shared section fetches, jellycompat "Latest" and browse fast paths with bounded Continue Watching resume scans, batched image presigning across list/detail/season/episode paths, a plugin installation in-memory cache with lifecycle invalidation, metadata provider chain enablement checking, and performance planning documents.

Changes

Performance plan documents

Layer / File(s) Summary
Planning docs
docs/superpowers/plans/2026-07-03-section-fetch-performance.md, docs/superpowers/plans/2026-07-03-shared-list-cache.md
New dated plans document jellycompat/section-fetch bottlenecks, implemented vs deferred fixes, and the shared in-process resolved-list cache design, keys, refresh semantics, and verification steps.

Estimated code review effort: 4 (Complex) | ~75 minutes

Jellycompat fast paths and section caching

Layer / File(s) Summary
Latest fast path and resume cap
internal/jellycompat/handlers_items.go, internal/jellycompat/latest_via_sections_test.go, internal/jellycompat/resume_filter_test.go
HandleLatest gains a sections-backed fast path with eligibility gating and a shared DTO-building tail, falling back to BrowseItems; loadProgressPage caps resume-history scanning at resumeScanMaxRows=300 without affecting completed-item scanning.
Browse, details, and presign batching
internal/jellycompat/content_direct.go, internal/jellycompat/content_direct_test.go, internal/jellycompat/presign_list.go, internal/jellycompat/batch_loaders.go, internal/jellycompat/batch_loaders_test.go, internal/jellycompat/userdata_direct.go, internal/jellycompat/content_service.go, internal/jellycompat/batch_progress_test.go, internal/jellycompat/handlers_items_test.go
Browse/search/favorites presigning moves to batched presignCompatListItems; GetItemDetailsByIDs batch-fetches leaf progress and falls back per-item on error; series rollup is exported as EnrichSeriesUserData; seasons/episodes use batched presigning.
Access-scope cache key helper
internal/catalog/access_cache_key.go, internal/catalog/audiobook_groups_cache.go
Adds AccessFilter.WriteAccessScopeCacheKey for deterministic, order-independent cache-key serialization; the audiobook groups cache key now delegates access-scope encoding to it.
Resolved list cache and fetcher
internal/sections/resolvedlistcache.go, internal/sections/resolvedlistcache_test.go, internal/sections/fetcher.go, internal/catalog/query_definition.go
Adds a process-global, singleflight-backed resolved-list cache with refresh-ahead expiry and cacheability rules (personalization/collection scope), wired into Fetcher.FetchOne; raises fetchAllMaxConcurrency and fixes release_date column scanning.

Estimated code review effort: 4 (Complex) | ~90 minutes

Plugin lifecycle and installation cache

Layer / File(s) Summary
Metadata checker wiring
internal/metadata/chain.go, internal/metadata/service.go, internal/metadata/person_refresh.go
Adds InstallationEnabledChecker interface and ResolveChainWithChecker, threading a checker through provider resolution to prefer an in-memory cache over direct DB queries.
Auto-update lifecycle hook
internal/plugins/auto_update.go, internal/plugins/auto_update_replace_test.go
AutoUpdateService accepts an onChange callback fired once per run when plugin_installations mutate.
Installation cache
internal/plugins/service.go, internal/plugins/service_installation_cache_test.go, cmd/silo/main.go
Service caches installation rows with generation-guarded invalidation on lifecycle change, exposes IsInstallationEnabled, and is wired into auto-update and metadata service initialization in main.go.

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

Sequence Diagram(s)

sequenceDiagram
  participant HandleLatest
  participant SectionsFetcher
  participant buildLatestItemDTOs

  HandleLatest->>HandleLatest: infer libraryItemType and check latestFastPathEligible
  HandleLatest->>SectionsFetcher: loadLatestViaSections
  SectionsFetcher-->>HandleLatest: latest items
  HandleLatest->>buildLatestItemDTOs: build DTOs from shared tail
  HandleLatest->>HandleLatest: fallback to BrowseItems on errLatestNotEligible
Loading
sequenceDiagram
  participant Fetcher
  participant resolvedListCache
  participant Loader

  Fetcher->>resolvedListCache: getOrRefresh(cache key)
  alt warm
    resolvedListCache-->>Fetcher: cached items and total
  else refresh window
    resolvedListCache-->>Fetcher: cached items and total
    resolvedListCache->>Loader: async refresh
  else cold or expired
    resolvedListCache->>Loader: blocking rebuild via singleflight
    Loader-->>resolvedListCache: items and total
    resolvedListCache-->>Fetcher: rebuilt items and total
  end
Loading

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main performance and shared-cache changes across home-screen, Continue Watching, and Latest paths.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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/section-fetch-optimization

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.

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

ℹ️ 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".

Comment thread internal/jellycompat/handlers_items.go Outdated
// most recent resumeScanMaxRows already cover every realistically-visible
// Continue Watching entry; beyond the cap we stop and return what we have
// (and, for EnableTotalRecordCount, a clamped lower-bound total).
if offset >= resumeScanMaxRows {

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 Keep the resume scan cap off watched-item pages

When status == "completed" (the IsPlayed=True path in handlePlayedItems), this loop is also responsible for paginating the user's watched-items list. Because the new break runs regardless of status, default requests with EnableTotalRecordCount=true stop after about 1000 raw progress rows; users with more than 1000 watched entries get an underreported TotalRecordCount, and pages with StartIndex beyond the cap can come back empty even though more completed rows exist. Guard this cap to the in-progress/resume path, or otherwise exempt completed progress scans, so watched-items pagination keeps its existing semantics.

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.

Good catch — fixed in 1e18fff. The cap in the general loop is now gated on resumeFiltered (if resumeFiltered && offset >= resumeScanMaxRows), so the completed/watched-items path keeps its exact TotalRecordCount and deep StartIndex pagination. Added TestLoadProgressPage_CompletedScanNotCapped which asserts the exact total is preserved (it fails if the guard is removed).

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/jellycompat/handlers_items.go (1)

2380-2426: 🚀 Performance & Scalability | 🔴 Critical | ⚡ Quick win

Fast-path scan loop still unbounded for sparse visible sets.

resumeScanMaxRows is only enforced in the general loop (Line 2502). This earlier "fast path" loop — entered for the default Continue Watching shape (typeSet empty, libraryID nil, enableTotalRecordCount false, startIndex==0) — has the identical structural bug the cap is meant to fix: when FilterResumeProgress drops almost every row (heavy watcher, sparse visible set), result never reaches query.limit and rawCount stays equal to batchSize until the true end of history, so the loop keeps paging unbounded. This is precisely the case the new test (TestLoadProgressPage_BoundsScanForSparseVisibleSet) exercises for the general loop, but that test forces enableTotalRecordCount: true, which routes around this branch entirely, so the gap isn't caught.

This branch is also the one hit by handleResumeResponse's fallback path whenever h.sectionsFetcher is nil or loadResumeViaSections errors, i.e. a realistic production route for default resume requests.

🐛 Proposed fix to bound the fast-path scan
 			if len(result) >= query.limit {
 				break
 			}
 			result = append(result, item)
 		}
-		if len(result) >= query.limit || rawCount < batchSize {
+		offset += rawCount
+		if len(result) >= query.limit || rawCount < batchSize {
 			break
 		}
-		offset += rawCount
+		if offset >= resumeScanMaxRows {
+			break
+		}
 	}
🤖 Prompt for 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.

In `@internal/jellycompat/handlers_items.go` around lines 2380 - 2426, The
fast-path branch in ItemsHandler.loadProgressPage has the same unbounded scan
problem as the general loop when FilterResumeProgress makes the visible set very
sparse. Apply the same resumeScanMaxRows cap used elsewhere to this fast-path
loop, and stop paging once the cap is reached even if result has not reached
query.limit. Make sure the fix is in loadProgressPage and covers the default
resume path triggered by handleResumeResponse.
🤖 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-03-section-fetch-performance.md`:
- Around line 112-119: The fenced example blocks in this document are missing
language tags, which triggers markdownlint MD040. Update the affected fences in
the performance snippets to use a language identifier such as sql or text, and
make the same change in the related block mentioned in the review so the docs
remain lint-clean.

---

Outside diff comments:
In `@internal/jellycompat/handlers_items.go`:
- Around line 2380-2426: The fast-path branch in ItemsHandler.loadProgressPage
has the same unbounded scan problem as the general loop when
FilterResumeProgress makes the visible set very sparse. Apply the same
resumeScanMaxRows cap used elsewhere to this fast-path loop, and stop paging
once the cap is reached even if result has not reached query.limit. Make sure
the fix is in loadProgressPage and covers the default resume path triggered by
handleResumeResponse.
🪄 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: 26e92c21-fd33-4f6d-ba1d-2287c7309496

📥 Commits

Reviewing files that changed from the base of the PR and between 3d82aa5 and aa06a6a.

📒 Files selected for processing (5)
  • docs/superpowers/plans/2026-07-03-section-fetch-performance.md
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/resume_filter_test.go
  • internal/sections/fetcher.go

…ress, widen section concurrency

Three low-risk fixes from the section-fetch performance investigation
(docs/superpowers/plans/2026-07-03-section-fetch-performance.md):

- jellycompat: bound loadProgressPage at resumeScanMaxRows=300 so a single
  request never pages through more than that many in-progress rows. The cap is
  unconditional: it also covers the sparse-visible-set case (a heavy watcher
  whose recent rows are mostly dismissed/superseded, or a Series/Season-only
  request that matches no leaf in-progress row), where the page never fills and
  the loop would otherwise scan the entire history — previously an O(history)
  scan reaching tens of seconds. In the common case the loop exits far earlier,
  so the cap only bounds the pathological worst case; 300 leaves ample headroom
  to fill a ~20-item Continue Watching page. Beyond the cap the reported total
  is a clamped lower bound. Covered by TestLoadProgressPage_BoundsScanForSparseVisibleSet.
- jellycompat: batch the leaf-item (movie/episode) progress lookup in
  GetItemDetailsByIDs via ListProgressWithCompletedHistory instead of a
  per-item GetProgressWithCompletedHistory (~100 sequential queries for a
  50-item detail page). Series keep the per-item episode-rollup path (they own
  no progress row). Output is unchanged; a batch-lookup failure is now logged
  rather than silently dropping played state for the whole page.
- sections: raise fetchAllMaxConcurrency 4 -> 6 to cut FetchAll wave count for
  large home layouts, staying within the default 20-conn pool.

Part of the home/continue-watching latency work.

AI-use disclosure: implemented with AI (Claude) assistance.
…under isPlayed

/Items/Latest with isPlayed=false is the highest-frequency compat browse
(~10.8k calls/day). The played overlay can't be pushed into SQL, so browse
over-fetches and filters locally. The cross-library recently_added fast path
(BrowseRecentlyAddedAcrossLibraries: one ~1ms index walk per library) was
gated on Offset==0, so a heavy watcher who had already seen the newest items
needed a 2nd chunk and fell through to BrowsePage — a whole-catalog
MIN(first_seen_at) + GROUP BY HashAggregate over ~147k movies measured at
~755ms per call (0.8-1.6s observed end-to-end).

Fetch the entire over-fetch budget (maxScannedRows) in a single merged
fast-path walk instead of paging into BrowsePage, so the loop fills from one
call. The clamp caveat (MaxLimit=1000 leaves a fall-through only for
requestedLimit>200, off the Latest hot path) is documented inline.

Part of the home/browse latency work.

AI-use disclosure: implemented with AI (Claude) assistance.
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/section-fetch-optimization branch from aa06a6a to 18c6656 Compare July 3, 2026 10:05
…fast-path loop

Addresses PR #292 review feedback:

- Codex (P2): the resumeScanMaxRows cap was applied unconditionally in the
  general loop, which also paginates the completed (watched-items) list. Gate it
  on resumeFiltered so the completed path keeps exact TotalRecordCount and deep
  StartIndex pagination. Covered by TestLoadProgressPage_CompletedScanNotCapped.
- CodeRabbit (Critical): the earlier raw-offset fast-path loop — the default
  Continue Watching shape and the sections-fallback route — had the same
  unbounded-scan bug and was not covered by the cap (the existing test forces
  EnableTotalRecordCount=true, routing around it). Bound it with the same
  resumeScanMaxRows guard. Covered by
  TestLoadProgressPage_BoundsFastPathScanForSparseVisibleSet.
- CodeRabbit (Minor): tag the doc's fenced example blocks as text to satisfy
  markdownlint MD040.

AI-use disclosure: implemented with AI (Claude) assistance.
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 1e18fff (pushed):

  • CodeRabbit (Critical) — fast-path scan loop unbounded for sparse visible sets: confirmed and fixed. The earlier raw-offset fast path (loop A, the default Continue Watching shape and the sections-fallback route) now applies the same resumeScanMaxRows bound (if resumeFiltered && offset+rawCount >= resumeScanMaxRows). The previous bounds test forced EnableTotalRecordCount=true and routed around this branch, so a new test TestLoadProgressPage_BoundsFastPathScanForSparseVisibleSet exercises loop A directly (it reads all 5000 rows and fails if the bound is removed).
  • Codex (P2) — cap leaking into watched-items pagination: fixed by gating the general-loop cap on resumeFiltered; completed keeps exact totals. New TestLoadProgressPage_CompletedScanNotCapped.
  • CodeRabbit (Minor, MD040): doc example fences tagged as text.

Both fixes were mutation-tested (each new test fails when its fix is reverted). build / vet / gofmt / tests / verify-local-paths all pass.

Home-screen rails that are identical for everyone who can see the same
libraries (recently added, recently released, genre, trending on server,
most watched, new to library, critically acclaimed, award winners, format
showcase, seasonal, mood, trending discover, admin-curated lists, and
library collections) were rebuilt from Postgres once per request, per user.
Only the overlay on top of each row (watched flags, play position, presigned
poster URLs) is actually per-user.

Insert a process-global resolved-list cache at the FetchOne choke point in
internal/sections. Each cacheable row is built once per access scope, held
with a 15m TTL, and refreshed in the background 3m before expiry;
singleflight collapses cold-miss stampedes into a single build. The per-user
overlay still runs fresh in buildSectionsResponse, so no profile state is
ever shared. Random and per-user rows (continue watching, next up,
recommendations, hidden gems, forgotten favorites, activity feed, user
collections) bypass the cache.

The access-scope key captures every access boundary the fetch path enforces
-- section identity (type + id + config hash) + item limit + accessible and
disabled libraries + max content rating + excluded media types + name prefix
+ allowed-content-id allowlist -- and nothing per-user, so entries are safely
shared. Empty membership is never cached (avoids freezing a transiently empty
rail); background refreshes are bounded by a timeout.

Scale (analytical, derived from the cache behavior -- not a measured
latency): for the user-agnostic rows, Postgres section-query volume collapses
from O(rows x concurrent requests) to O(rows x distinct access scopes) per
15m refresh window, because most users share a handful of access scopes.
Illustrative -- 40 cacheable rows on a home screen, 1000 concurrent users
falling into ~5 distinct access scopes:

  - before: ~40 x 1000 = ~40,000 section queries per wave of home loads
  - after:  ~40 x 5    = ~200 builds per 15m window (plus one background
            refresh per row per scope), i.e. a warm home load runs zero
            section queries for these rows.

That is a ~99% reduction in shared section-query load at that concurrency;
the win grows with concurrency and shrinks as access-scope diversity rises.

Design/plan doc added under docs/superpowers/plans/.
…dded section

A jellyfin-compat per-library /Items/Latest rail is the same user-agnostic
list as the native "recently added" library rail -- both order by
mil.first_seen_at DESC. It was rebuilt on every request through
directContentService.BrowseItems, missing the resolved-list cache entirely.

Route per-library Latest for movies and series libraries through the native
section fetch instead, so it reuses the shared cache. HandleLatest resolves
the library's type once, and for a movies/series library builds a synthetic
SectionRecentlyAdded with the same type + config + limit + access scope the
native rail uses and calls FetchOne; the per-user overlay (favorites,
progress, episode targets, presign) is extracted into buildLatestItemDTOs and
shared by both the native and BrowseItems paths, so no overlay logic is
duplicated. Cached *models.MediaItem values are read-only -- LocalizeItemModels
deep-copies before any presign mutation.

To let the two surfaces share one entry, resolvedListCacheKey no longer
includes the arbitrary section ID: every cacheable section type derives its
membership from type + config + limit + scope, never from its own ID (audited
all 14 cacheable types plus the library-collection path; the sole s.ID read
lives in the non-cacheable user-collection branch). A native recently-added
rail and the compat Latest for the same library + scope now collapse to ONE
cache entry, built once and reused. Access-scope isolation is unchanged --
the removed ID never carried access information, and every access boundary
(libraries, rating cap, excluded types, content allow-list, name prefix)
still keys the entry.

Guardrails: the native path is restricted to movies and series libraries;
every other library type (ebook, music, manga, mixed) is ignored and keeps
its exact BrowseItems behavior -- important because an unfiltered
recently-added fetch would otherwise surface non-video items to Jellyfin
clients that only expect video. Deeper pages, played-filter and
backdrop-required requests, a client asking for a type other than the
library's own, and any FetchOne error also fall back to BrowseItems.

Chosen over an alternative that gave the synthetic section a deterministic ID
(which kept two separate cache entries): both returned identical data with
similar complexity, so the shared-entry design won.
@CoffeeKnyte CoffeeKnyte changed the title perf: cut home-screen, Continue Watching, and Latest browse latency perf: cut home-screen, Continue Watching, and Latest latency; cache shared home rails Jul 3, 2026

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

🧹 Nitpick comments (1)
internal/sections/resolvedlistcache.go (1)

298-303: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Canonicalize JSON config before hashing it.

Hashing raw JSON bytes splits the cache for semantically identical configs with different whitespace or field order, which weakens the native/compat cache-sharing goal.

Proposed direction
 func hashSectionConfig(config json.RawMessage) string {
 	if len(config) == 0 {
 		return "none"
 	}
+	var decoded any
+	if err := json.Unmarshal(config, &decoded); err == nil {
+		if canonical, err := json.Marshal(decoded); err == nil {
+			config = canonical
+		}
+	}
 	sum := sha256.Sum256(config)
 	return hex.EncodeToString(sum[:])
 }
🤖 Prompt for 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.

In `@internal/sections/resolvedlistcache.go` around lines 298 - 303, The cache key
in hashSectionConfig is based on raw json.RawMessage bytes, so semantically
identical configs can hash differently due to whitespace or field order.
Canonicalize the JSON in hashSectionConfig before computing the SHA-256 digest
by unmarshaling and re-encoding into a stable form, then hash that normalized
representation so cache sharing works across native/compat configs.
🤖 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 `@internal/jellycompat/handlers_items.go`:
- Around line 1080-1090: Clamp the Latest page size before constructing the
cached section in the parseItemsQuery/ResolvedSection flow: `parseItemsQuery`
only applies a default, so `query.limit` can still be too large and propagate
into `ResolvedSection.ItemLimit`, affecting both the cache key and the fetch.
Update the `limit` handling in the Latest section builder to enforce the maximum
allowed size before creating `sections.ResolvedSection`, using the existing
`compatDefaultLatestLimit`/limit logic as the place to normalize it.

In `@internal/sections/resolvedlistcache.go`:
- Around line 61-64: Add an eviction path for expired entries in
resolvedListCache so TTL does more than affect lookups. Update the
resolvedListCache/resolvedListEntry logic in resolvedlistcache.go and the code
around the cache access path (including the cleanup area referenced by the later
block) so expired keys are removed from the map instead of lingering forever;
use the existing resolvedListCacheMu and the cache key generation path to locate
the affected code and ensure stale scope/config/limit entries are deleted on
access or via a cleanup routine.
- Around line 154-166: The resolved list cache refresh logs are leaking the raw
cache key, which may contain user-controlled input from the access filter.
Update the logging in resolved list cache refresh handling around the
loader/error path in resolvedListCache to avoid emitting key directly; instead
add a small helper like resolvedListLogKey to hash/digest the key and log that
value in both the warning and panic paths.

---

Nitpick comments:
In `@internal/sections/resolvedlistcache.go`:
- Around line 298-303: The cache key in hashSectionConfig is based on raw
json.RawMessage bytes, so semantically identical configs can hash differently
due to whitespace or field order. Canonicalize the JSON in hashSectionConfig
before computing the SHA-256 digest by unmarshaling and re-encoding into a
stable form, then hash that normalized representation so cache sharing works
across native/compat configs.
🪄 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: 5b4e169d-59c1-44a1-97e1-7c1ea49c87d3

📥 Commits

Reviewing files that changed from the base of the PR and between aa06a6a and a69695b.

📒 Files selected for processing (9)
  • docs/superpowers/plans/2026-07-03-section-fetch-performance.md
  • docs/superpowers/plans/2026-07-03-shared-list-cache.md
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/latest_via_sections_test.go
  • internal/jellycompat/resume_filter_test.go
  • internal/sections/fetcher.go
  • internal/sections/resolvedlistcache.go
  • internal/sections/resolvedlistcache_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/jellycompat/content_direct.go

Comment thread internal/jellycompat/handlers_items.go Resolved
Comment thread internal/sections/resolvedlistcache.go Resolved
Comment thread internal/sections/resolvedlistcache.go Resolved
…e and Latest path

Consolidates fixes from the branch's adversarial review and PR #292 review
comments into one commit:

- Latest fast path: fall back to BrowseItems when a request carries a genre,
  name-prefix, or person filter (the synthetic recently-added section cannot
  express these, so serving it unfiltered would return a wrong, broader set).
  Eligibility is decided by latestFastPathEligible and covered by a test.
- Clamp the /Items/Latest page size to compatBrowseMaxLimit before building the
  section, matching the BrowseItems fallback, so a large client Limit can't drive
  an oversized recently-added fetch or explode the shared cache key with unbounded
  ItemLimit values.
- Evict expired entries from the process-global resolvedListCache: resolvedListSet
  sweeps expired keys at most once per minute, bounding the map to scopes seen
  within one TTL window. Covered by TestResolvedListCacheEvictsExpiredEntries.
- Log a short digest of the cache key (resolvedListLogKey) instead of the raw key
  in the background-refresh panic/error paths, since the key embeds
  user-controlled access-scope fields such as NamePrefix.

Skipped review comments (verified already fixed or stale against current code):
the resume fast-path scan bound and watched-items cap (1e18fff) and the docs
fence-language tags (already addressed).

Build, vet, and go test -race pass for internal/sections and internal/jellycompat.
…ifecycle change

## Problem
Every poster/image on a warm home rail re-read plugin_installations from
Postgres to answer "is this plugin enabled?" and to acquire the plugin client
(Source A: metadata chain buildProviders enabled-check; Source B: ensureClient
-> loadInstallation). Plugin-resolved image URLs are never URL-cached, so the
plugin source and the DB read behind it fired again on every identical warm
request; 100% of images in the target library are plugin-backed.

## Solution
- Guarded in-memory installation cache (map[int]*Installation + RWMutex) in
  plugins.Service. loadInstallation reads through it; the requireEnabled gate
  stays after the cache read so ErrInstallationDisabled semantics are unchanged.
  invalidateInstallationCache clears it and is self-registered as a lifecycle
  hook, so Service.OnLifecycleChange wipes it on install/enable/disable/update/
  uninstall.
- A generation counter closes an invalidate-vs-repopulate race: captured before
  installations.GetByID and re-checked under the write lock, so a row fetched
  before a lifecycle mutation is never written into a freshly cleared cache
  (would otherwise resurrect a just-disabled plugin).
- Route the metadata chain enabled-check through the same cache via a structural
  InstallationEnabledChecker interface (nil-safe: falls back to the pool query
  when no checker is injected), wired in cmd/silo/main.go.

## Post-review fix (auto-update reliability blocker)
AutoUpdateService mutated installations (new InstallPath, old dir deleted) on
the default auto update policy without firing OnLifecycleChange, leaving the
cache stale and breaking plugins with "stored plugin manifest mismatch" until
restart. It now takes an onChange callback wired to Service.OnLifecycleChange
and fires it once per Check run that mutated a row.

## Verification
go build/vet, go test ./internal/plugins/... ./internal/metadata/... (-race).
Tests: cache hit/invalidation, racing-invalidation guard, IsInstallationEnabled,
auto-update fires onChange.

## AI-use disclosure
Implemented with AI assistance (Claude).
…ached Latest path

## Problem
List rails presigned each item's poster/backdrop/logo/still image individually
(~160 singular resolver calls for a 40-item page where 4 batched calls suffice),
and ItemsHandler carried a near-verbatim duplicate of the batch presigner.

## Solution (batching)
Promote the batch presigner to a shared package-level presignCompatListItems
(presign_list.go) with a generic collectImagePaths[T]; convert the per-item
loops (cached home/Latest rail, favorites, batch loaders, userdata favorites) to
one batched PresignImageURLsWithExpiry per image type per page; batch the
season/episode collections; delete the three duplicate presign helpers. URL
output is unchanged (verified byte-for-byte).

## Post-review fix (series Latest data-parity regression)
The native cached Latest fast path built items via compatListItemsFromModels +
buildLatestItemDTOs and never ran the series watch-state rollup, so a series
library's Latest lost Played / UnplayedItemCount and page 1 disagreed with the
BrowseItems fallback. enrichSeriesUserData is promoted to the ContentService
interface and called on the native path (reused, not duplicated).

## Verification
go build/vet, go test ./internal/jellycompat/... ./internal/catalog/...
Tests: bounded presign invocation counts + per-item URL mapping; series rollup
populated on the native Latest path.

## AI-use disclosure
Implemented with AI assistance (Claude).
…n refresh lead

## Problem
1. The shared home-rail cache whitelisted custom_filter/genre sections by TYPE
   alone, but those route through fetchFiltered -> ParseQueryDefinition and can
   carry personalized (per-profile) rules/sorts (watched, favorited,
   in_watchlist, in_progress, last_watched; sorts progress/date_viewed/plays).
   Their membership is per-profile yet the cache key excludes userID/profileID,
   so a personalized rail built for one profile was served to others in the same
   access scope for up to 15m -- a cross-profile watchlist/watch-state leak.
2. The background-refresh lead was tuned so steady traffic is served a warm
   entry from a longer soft window.

## Solution
- Add QueryDefinition.IsPersonalized() (reusing the existing
  QueryFieldRequiresProfile/QuerySortRequiresProfile helpers).
  isCacheableSectionType now parses the section QueryDefinition and refuses to
  cache custom_filter/genre when personalized; non-personalized definitions stay
  cacheable. Seasonal/mood/trending build their definitions server-side and stay
  unconditionally cacheable.
- resolvedListRefreshLead 3m -> 10m (soft threshold builtAt+5min instead of
  builtAt+12min).

## Verification
go build/vet, go test ./internal/sections/... ./internal/catalog/... (-race).
Test: personalized custom_filter/genre not cacheable; non-personalized are.

## AI-use disclosure
Implemented with AI assistance (Claude).
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Pushed three follow-up commits on top of the current PR.

Problem

  • Plugins re-queried on every poster. Each image on a warm home screen kept asking the database "is this plugin enabled?" and re-fetching the plugin — the same near-constant answer, over and over. A separate daily auto-update path could also swap a plugin's files without anything noticing, which would have left stale info around.
  • Poster links fetched one at a time. A row of ~40 items requested each item's poster/backdrop/logo/still link individually — roughly 160 tiny calls where 4 would do.
  • The "Latest" strip for a show library was missing its unwatched counts, and could disagree with the rest of the app depending on how far you scrolled.
  • A shared home-row cache could leak between profiles. Personalized rows (e.g. "On Your Watchlist", "Unwatched") were cached as if they were the same for everyone who can see the same libraries, so one profile could briefly be shown another profile's list.

Solution

  • Remember plugin state in memory and only forget it when a plugin is actually installed, enabled, disabled, updated, or removed — including the daily auto-update, which now refreshes that memory so it can't go stale.
  • Batch the poster links so a whole page is fetched in one call per image type instead of one per item (the image links themselves are unchanged), and merged three near-identical copies of that code into one.
  • Restore the show "Latest" watch-state so unwatched-episode counts are correct and page 1 matches the rest of the app.
  • Never share personalized rows across profiles — the cache now recognizes when a row depends on who's watching and skips caching it, while still sharing the truly identical rows. Also widened the background refresh window so busy servers keep serving a warm copy.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/metadata/service.go (1)

464-475: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Invalidate the chain cache on plugin lifecycle changes

MetadataService already exposes InvalidateChainCache() for admin chain edits, but nothing wires it to plugin install/enable/disable/update/uninstall events. That leaves resolveChainCached serving stale provider chains until chainCacheTTL expires; hook InvalidateChainCache() into pluginService.AddLifecycleHook(...) when wiring the service.

🤖 Prompt for 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.

In `@internal/metadata/service.go` around lines 464 - 475, The chain cache in
MetadataService is not being cleared when plugin lifecycle events change
provider availability, so resolveChainCached can return stale data. Wire
InvalidateChainCache() into the plugin service setup by registering it with
pluginService.AddLifecycleHook(...) for install, enable, disable, update, and
uninstall events, using the existing MetadataService and InvalidateChainCache
symbols so cache entries are dropped whenever plugins change.
internal/jellycompat/batch_loaders.go (1)

313-360: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Batch episode image presigns internal/jellycompat/batch_loaders.go:313-360 and 422-472 still call compatPresignImage inside the per-row loop, and that helper is just a thin wrapper over DetailService.PresignImageURLWithExpiry, so these paths still do one presign per image per episode. The list-rail helpers already batch with PresignImageURLsWithExpiry; this should follow the same collect-then-batch pattern.

🤖 Prompt for 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.

In `@internal/jellycompat/batch_loaders.go` around lines 313 - 360, The episode
batch loaders still presign each image inside the per-row loop via
compatPresignImage, so the loaders in batch_loaders.go are not actually
batching. Update the episode target builders (the compatEpisodeTarget creation
paths) to first collect all unique image paths and then call
DetailService.PresignImageURLsWithExpiry in bulk, matching the existing
list-rail batching pattern; only map the returned URLs back into the per-item
fields afterward.
🧹 Nitpick comments (1)
internal/jellycompat/presign_list.go (1)

16-16: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move ctx to the first parameter for consistency with the other presign helpers.
The parameter order is inconsistent with presignSeason, presignSeasons, and presignEpisodes.

🤖 Prompt for 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.

In `@internal/jellycompat/presign_list.go` at line 16, Move ctx to the first
parameter of presignCompatListItems so its signature matches presignSeason,
presignSeasons, and presignEpisodes. Update the function declaration and all
call sites accordingly, keeping detailSvc and items in the same relative order
after ctx for consistency across the presign helpers.

Source: Coding guidelines

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

Outside diff comments:
In `@internal/jellycompat/batch_loaders.go`:
- Around line 313-360: The episode batch loaders still presign each image inside
the per-row loop via compatPresignImage, so the loaders in batch_loaders.go are
not actually batching. Update the episode target builders (the
compatEpisodeTarget creation paths) to first collect all unique image paths and
then call DetailService.PresignImageURLsWithExpiry in bulk, matching the
existing list-rail batching pattern; only map the returned URLs back into the
per-item fields afterward.

In `@internal/metadata/service.go`:
- Around line 464-475: The chain cache in MetadataService is not being cleared
when plugin lifecycle events change provider availability, so resolveChainCached
can return stale data. Wire InvalidateChainCache() into the plugin service setup
by registering it with pluginService.AddLifecycleHook(...) for install, enable,
disable, update, and uninstall events, using the existing MetadataService and
InvalidateChainCache symbols so cache entries are dropped whenever plugins
change.

---

Nitpick comments:
In `@internal/jellycompat/presign_list.go`:
- Line 16: Move ctx to the first parameter of presignCompatListItems so its
signature matches presignSeason, presignSeasons, and presignEpisodes. Update the
function declaration and all call sites accordingly, keeping detailSvc and items
in the same relative order after ctx for consistency across the presign helpers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9de0ec83-8b46-45b8-8ce5-0530f7924c18

📥 Commits

Reviewing files that changed from the base of the PR and between a69695b and 0d06581.

📒 Files selected for processing (22)
  • cmd/silo/main.go
  • internal/catalog/query_definition.go
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/batch_loaders_test.go
  • internal/jellycompat/batch_progress_test.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/content_service.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_items_test.go
  • internal/jellycompat/latest_via_sections_test.go
  • internal/jellycompat/presign_list.go
  • internal/jellycompat/userdata_direct.go
  • internal/metadata/chain.go
  • internal/metadata/person_refresh.go
  • internal/metadata/service.go
  • internal/plugins/auto_update.go
  • internal/plugins/auto_update_replace_test.go
  • internal/plugins/service.go
  • internal/plugins/service_installation_cache_test.go
  • internal/sections/resolvedlistcache.go
  • internal/sections/resolvedlistcache_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/jellycompat/batch_progress_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/sections/resolvedlistcache.go
  • internal/jellycompat/handlers_items.go

CoffeeKnyte added a commit that referenced this pull request Jul 5, 2026
… chain staleness

Addresses three review findings on PR #292:

- sections: canonicalize section config JSON before hashing so configs
  differing only in whitespace/field order share a cache entry (native +
  jellycompat rail sharing). Added TestHashSectionConfigCanonicalizes.
- metadata: invalidate the resolved-chain cache on plugin lifecycle
  changes; the installation-enabled check already reads the invalidated
  plugin cache, but resolveChainCached could serve a stale provider chain
  for up to chainCacheTTL after a provider's availability changed.
- jellycompat: move ctx to the first parameter of presignCompatListItems
  for consistency with the other presign helpers.

Skipped the episode-image presign batching nitpick: the resolver already
dedupes+singleflights, so it is a Minor perf-only item not worth the
two-pass refactor risk in this pass.
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Addressed the latest review findings in bddf499:

  • Chain cache staleness (Major): metadataService.InvalidateChainCache() is now wired into pluginService.AddLifecycleHook, so install/enable/disable/update/uninstall drops the resolved provider chain immediately instead of serving a stale one for up to chainCacheTTL.
  • Canonicalize section config before hashing (nitpick): hashSectionConfig now decodes+re-marshals JSON so configs differing only in whitespace/field order share a cache entry (with TestHashSectionConfigCanonicalizes).
  • presign helper signature (nitpick): ctx moved to the first parameter of presignCompatListItems, matching the sibling presign helpers.

Skipped the episode-image presign batching item for now — the resolver already dedupes + singleflights, so it's a Minor perf-only change not worth the two-pass loader refactor risk in this pass.

build / vet / gofmt / go test ./internal/sections/... ./internal/jellycompat/... / verify-local-paths all pass.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/architecture/playback-paths-monitoring-kill-matrix.md`:
- Around line 6-8: The top summary in the kill matrix doc has a stale GAP-3
status that conflicts with the Findings section. Update the header note around
the playback-paths monitoring kill matrix summary so GAP-3 is shown consistently
as RESOLVED, or reword the historical note to avoid presenting two different
current statuses. Use the existing GAP-3 and Findings references in the document
to keep the status aligned.
🪄 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: fe720234-fb16-4027-8a81-39aa5ed74eb3

📥 Commits

Reviewing files that changed from the base of the PR and between 0d06581 and bddf499.

📒 Files selected for processing (11)
  • cmd/silo/main.go
  • docs/architecture/playback-paths-monitoring-kill-matrix.md
  • docs/superpowers/plans/2026-07-04-plugin-installation-cache-and-batch-presign.md
  • internal/jellycompat/batch_loaders.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/presign_list.go
  • internal/jellycompat/userdata_direct.go
  • internal/sections/resolvedlistcache.go
  • internal/sections/resolvedlistcache_test.go
✅ Files skipped from review due to trivial changes (1)
  • docs/superpowers/plans/2026-07-04-plugin-installation-cache-and-batch-presign.md
🚧 Files skipped from review as they are similar to previous changes (9)
  • internal/jellycompat/userdata_direct.go
  • cmd/silo/main.go
  • internal/jellycompat/presign_list.go
  • internal/jellycompat/batch_loaders.go
  • internal/sections/resolvedlistcache.go
  • internal/jellycompat/content_direct_test.go
  • internal/sections/resolvedlistcache_test.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/handlers_items.go

… chain staleness

Addresses three review findings on PR #292:

- sections: canonicalize section config JSON before hashing so configs
  differing only in whitespace/field order share a cache entry (native +
  jellycompat rail sharing). Added TestHashSectionConfigCanonicalizes.
- metadata: invalidate the resolved-chain cache on plugin lifecycle
  changes; the installation-enabled check already reads the invalidated
  plugin cache, but resolveChainCached could serve a stale provider chain
  for up to chainCacheTTL after a provider's availability changed.
- jellycompat: move ctx to the first parameter of presignCompatListItems
  for consistency with the other presign helpers.

Skipped the episode-image presign batching nitpick: the resolver already
dedupes+singleflights, so it is a Minor perf-only item not worth the
two-pass refactor risk in this pass.
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/section-fetch-optimization branch from bddf499 to 1880c53 Compare July 5, 2026 03:50
…ath per review

Addresses the eight findings from the deep review of this PR:

- Detach the blocking cold-miss rebuild from the singleflight leader's
  request context (context.WithoutCancel + the shared 30s build timeout)
  so one client disconnect no longer fails every collapsed waiter and
  leaves the entry uncached.
- Stop client-controlled values minting unbounded cache entries: the
  compat Latest fast path now always fetches a fixed 100-row budget and
  slices to the requested limit (one entry per scope+library instead of
  one per Limit value), and an unrecognized MaxOfficialRating string
  disqualifies the fast path instead of entering the global cache key.
- Add release_date to the sections item projection/scan so movies served
  via the Latest fast path keep PremiereDate (Jellyfin default-set field)
  in parity with the BrowseItems fallback.
- Fall back to per-item progress lookups when the batched leaf progress
  query fails, restoring one-item-at-a-time degradation instead of
  blanking played state for the whole page.
- Derive cache eligibility from a single source of truth: fetchSection
  and isCacheableSectionType now share the userAgnosticSectionFetcher
  table, whose no-userID/profileID signature makes a fetcher drop out of
  the cacheable set at compile time if it ever gains per-profile inputs.
- Decide Latest fast-path eligibility off the actual browse params the
  fallback would receive, so any filter later added to buildBrowseParams
  automatically disqualifies the cached path; share one
  compatDefaultBrowseLimit constant between both paths.
- Extract AccessFilter.WriteAccessScopeCacheKey as the shared, security-
  critical serializer for all access-scoped caches (resolved-list,
  editorial candidates, audiobook groups); the editorial key now captures
  ExcludedMediaTypes, which its loaders already applied in SQL.
- Strip leaked agent-transcript markup from the section-fetch plan doc.

go build ./..., go vet, gofmt clean; go test -race on
internal/sections, internal/catalog, internal/jellycompat passes
(TestBeginWebOperation* failures are the known pre-existing flakes).

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Deep-review follow-up — all 8 findings addressed in d75a78c

An 8-angle adversarial review (line-scan, removed-behavior, cross-file tracing, reuse/simplification/efficiency, altitude, conventions; each candidate independently verified) surfaced 8 actionable findings. All are fixed:

# Finding Fix
1 Blocking cold-miss rebuild ran under the singleflight leader's request context — one client disconnect poisoned every collapsed waiter and left the entry uncached Loader now runs on context.WithoutCancel + the shared 30s build timeout (resolvedListBuildTimeout); regression test TestBlockingRebuildDetachedFromLeaderCancellation
2 Client-controlled Limit (1..1000) and, for uncapped profiles, raw MaxOfficialRating strings minted unbounded global cache entries Latest fast path always fetches a fixed 100-row budget (compatLatestCacheFetchLimit) and slices to the requested limit — one entry per scope+library; unknown rating strings disqualify the fast path
3 Movies via the Latest fast path lost PremiereDate (itemColumnsList never selected release_date) release_date::text added to the sections projection + scan — fast path and BrowseItems fallback now emit identical default-set fields
4 One failed batch progress query blanked played state for the whole page On batch failure the loop falls back to per-item enrichDetailUserData, restoring one-item-at-a-time degradation
5 isCacheableSectionType was a hand-list that could silently drift from fetchSection (cross-profile leak hazard) Both now derive from one userAgnosticSectionFetcher table; its no-userID/profileID signature makes a fetcher drop out of the cacheable set at compile time if it gains per-profile inputs
6 latestFastPathEligible hand-mirrored buildBrowseParams' filter set; compatDefaultLatestLimit=24 duplicated BrowseItems' inline default Eligibility now inspects the actual built params against a closed allow-list — any future filter auto-disqualifies (pinned by a test); one shared compatDefaultBrowseLimit
7 Third divergent hand-rolled AccessFilter key serializer; the editorial candidate key omitted ExcludedMediaTypes that its SQL applies New AccessFilter.WriteAccessScopeCacheKey is the single security-critical serializer, now used by the resolved-list, editorial-candidate, and audiobook-groups caches
8 Plan doc ended with leaked agent-transcript markup (</content>, </invoke>) Removed

Also verified-and-noted (not fixed here, low severity): background refresh stamps entries with trigger time (bounded to ~30s skew by the refresh timeout); the plugin-installation cache misses out-of-band DB edits (all supported mutation paths invalidate correctly); presign-before-filter on the isPlayed over-fetch path is pre-existing ordering, not introduced by this PR.

Refuted during verification (no change needed): the resume-cap "empty rail" concern (documented, test-pinned design), a Latest localization mismatch (fallback never applied library-scoped presentation either), and inflated fast-path totals (already an approximate window on main).

Verification: go build ./..., go vet, gofmt clean; go test -race passes on internal/sections, internal/catalog, internal/jellycompat (only the known pre-existing TestBeginWebOperation* flakes fail); make verify-local-paths clean.

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit 5606bee into main Jul 5, 2026
1 check passed
@Quick104
Quick104 deleted the perf/section-fetch-optimization branch July 5, 2026 06:01
Quick104 pushed a commit that referenced this pull request Jul 9, 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 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 to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…hared home rails (Silo-Server#292)

* perf(jellycompat,sections): bound resume scan, batch leaf detail progress, widen section concurrency

Three low-risk fixes from the section-fetch performance investigation
(docs/superpowers/plans/2026-07-03-section-fetch-performance.md):

- jellycompat: bound loadProgressPage at resumeScanMaxRows=300 so a single
  request never pages through more than that many in-progress rows. The cap is
  unconditional: it also covers the sparse-visible-set case (a heavy watcher
  whose recent rows are mostly dismissed/superseded, or a Series/Season-only
  request that matches no leaf in-progress row), where the page never fills and
  the loop would otherwise scan the entire history — previously an O(history)
  scan reaching tens of seconds. In the common case the loop exits far earlier,
  so the cap only bounds the pathological worst case; 300 leaves ample headroom
  to fill a ~20-item Continue Watching page. Beyond the cap the reported total
  is a clamped lower bound. Covered by TestLoadProgressPage_BoundsScanForSparseVisibleSet.
- jellycompat: batch the leaf-item (movie/episode) progress lookup in
  GetItemDetailsByIDs via ListProgressWithCompletedHistory instead of a
  per-item GetProgressWithCompletedHistory (~100 sequential queries for a
  50-item detail page). Series keep the per-item episode-rollup path (they own
  no progress row). Output is unchanged; a batch-lookup failure is now logged
  rather than silently dropping played state for the whole page.
- sections: raise fetchAllMaxConcurrency 4 -> 6 to cut FetchAll wave count for
  large home layouts, staying within the default 20-conn pool.

Part of the home/continue-watching latency work.

AI-use disclosure: implemented with AI (Claude) assistance.

* perf(jellycompat): keep Latest browse on the cross-library fast path under isPlayed

/Items/Latest with isPlayed=false is the highest-frequency compat browse
(~10.8k calls/day). The played overlay can't be pushed into SQL, so browse
over-fetches and filters locally. The cross-library recently_added fast path
(BrowseRecentlyAddedAcrossLibraries: one ~1ms index walk per library) was
gated on Offset==0, so a heavy watcher who had already seen the newest items
needed a 2nd chunk and fell through to BrowsePage — a whole-catalog
MIN(first_seen_at) + GROUP BY HashAggregate over ~147k movies measured at
~755ms per call (0.8-1.6s observed end-to-end).

Fetch the entire over-fetch budget (maxScannedRows) in a single merged
fast-path walk instead of paging into BrowsePage, so the loop fills from one
call. The clamp caveat (MaxLimit=1000 leaves a fall-through only for
requestedLimit>200, off the Latest hot path) is documented inline.

Part of the home/browse latency work.

AI-use disclosure: implemented with AI (Claude) assistance.

* fix(jellycompat): scope resume scan cap to resume path and bound the fast-path loop

Addresses PR Silo-Server#292 review feedback:

- Codex (P2): the resumeScanMaxRows cap was applied unconditionally in the
  general loop, which also paginates the completed (watched-items) list. Gate it
  on resumeFiltered so the completed path keeps exact TotalRecordCount and deep
  StartIndex pagination. Covered by TestLoadProgressPage_CompletedScanNotCapped.
- CodeRabbit (Critical): the earlier raw-offset fast-path loop — the default
  Continue Watching shape and the sections-fallback route — had the same
  unbounded-scan bug and was not covered by the cap (the existing test forces
  EnableTotalRecordCount=true, routing around it). Bound it with the same
  resumeScanMaxRows guard. Covered by
  TestLoadProgressPage_BoundsFastPathScanForSparseVisibleSet.
- CodeRabbit (Minor): tag the doc's fenced example blocks as text to satisfy
  markdownlint MD040.

AI-use disclosure: implemented with AI (Claude) assistance.

* perf(sections): cache shared user-agnostic home rails per access scope

Home-screen rails that are identical for everyone who can see the same
libraries (recently added, recently released, genre, trending on server,
most watched, new to library, critically acclaimed, award winners, format
showcase, seasonal, mood, trending discover, admin-curated lists, and
library collections) were rebuilt from Postgres once per request, per user.
Only the overlay on top of each row (watched flags, play position, presigned
poster URLs) is actually per-user.

Insert a process-global resolved-list cache at the FetchOne choke point in
internal/sections. Each cacheable row is built once per access scope, held
with a 15m TTL, and refreshed in the background 3m before expiry;
singleflight collapses cold-miss stampedes into a single build. The per-user
overlay still runs fresh in buildSectionsResponse, so no profile state is
ever shared. Random and per-user rows (continue watching, next up,
recommendations, hidden gems, forgotten favorites, activity feed, user
collections) bypass the cache.

The access-scope key captures every access boundary the fetch path enforces
-- section identity (type + id + config hash) + item limit + accessible and
disabled libraries + max content rating + excluded media types + name prefix
+ allowed-content-id allowlist -- and nothing per-user, so entries are safely
shared. Empty membership is never cached (avoids freezing a transiently empty
rail); background refreshes are bounded by a timeout.

Scale (analytical, derived from the cache behavior -- not a measured
latency): for the user-agnostic rows, Postgres section-query volume collapses
from O(rows x concurrent requests) to O(rows x distinct access scopes) per
15m refresh window, because most users share a handful of access scopes.
Illustrative -- 40 cacheable rows on a home screen, 1000 concurrent users
falling into ~5 distinct access scopes:

  - before: ~40 x 1000 = ~40,000 section queries per wave of home loads
  - after:  ~40 x 5    = ~200 builds per 15m window (plus one background
            refresh per row per scope), i.e. a warm home load runs zero
            section queries for these rows.

That is a ~99% reduction in shared section-query load at that concurrency;
the win grows with concurrency and shrinks as access-scope diversity rises.

Design/plan doc added under docs/superpowers/plans/.

* perf(jellycompat): serve per-library Latest via the cached recently-added section

A jellyfin-compat per-library /Items/Latest rail is the same user-agnostic
list as the native "recently added" library rail -- both order by
mil.first_seen_at DESC. It was rebuilt on every request through
directContentService.BrowseItems, missing the resolved-list cache entirely.

Route per-library Latest for movies and series libraries through the native
section fetch instead, so it reuses the shared cache. HandleLatest resolves
the library's type once, and for a movies/series library builds a synthetic
SectionRecentlyAdded with the same type + config + limit + access scope the
native rail uses and calls FetchOne; the per-user overlay (favorites,
progress, episode targets, presign) is extracted into buildLatestItemDTOs and
shared by both the native and BrowseItems paths, so no overlay logic is
duplicated. Cached *models.MediaItem values are read-only -- LocalizeItemModels
deep-copies before any presign mutation.

To let the two surfaces share one entry, resolvedListCacheKey no longer
includes the arbitrary section ID: every cacheable section type derives its
membership from type + config + limit + scope, never from its own ID (audited
all 14 cacheable types plus the library-collection path; the sole s.ID read
lives in the non-cacheable user-collection branch). A native recently-added
rail and the compat Latest for the same library + scope now collapse to ONE
cache entry, built once and reused. Access-scope isolation is unchanged --
the removed ID never carried access information, and every access boundary
(libraries, rating cap, excluded types, content allow-list, name prefix)
still keys the entry.

Guardrails: the native path is restricted to movies and series libraries;
every other library type (ebook, music, manga, mixed) is ignored and keeps
its exact BrowseItems behavior -- important because an unfiltered
recently-added fetch would otherwise surface non-video items to Jellyfin
clients that only expect video. Deeper pages, played-filter and
backdrop-required requests, a client asking for a type other than the
library's own, and any FetchOne error also fall back to BrowseItems.

Chosen over an alternative that gave the synthetic section a deterministic ID
(which kept two separate cache entries): both returned identical data with
similar complexity, so the shared-entry design won.

* fix(sections,jellycompat): post-review fixes for the shared-list cache and Latest path

Consolidates fixes from the branch's adversarial review and PR Silo-Server#292 review
comments into one commit:

- Latest fast path: fall back to BrowseItems when a request carries a genre,
  name-prefix, or person filter (the synthetic recently-added section cannot
  express these, so serving it unfiltered would return a wrong, broader set).
  Eligibility is decided by latestFastPathEligible and covered by a test.
- Clamp the /Items/Latest page size to compatBrowseMaxLimit before building the
  section, matching the BrowseItems fallback, so a large client Limit can't drive
  an oversized recently-added fetch or explode the shared cache key with unbounded
  ItemLimit values.
- Evict expired entries from the process-global resolvedListCache: resolvedListSet
  sweeps expired keys at most once per minute, bounding the map to scopes seen
  within one TTL window. Covered by TestResolvedListCacheEvictsExpiredEntries.
- Log a short digest of the cache key (resolvedListLogKey) instead of the raw key
  in the background-refresh panic/error paths, since the key embeds
  user-controlled access-scope fields such as NamePrefix.

Skipped review comments (verified already fixed or stale against current code):
the resume fast-path scan bound and watched-items cap (04d2e795) and the docs
fence-language tags (already addressed).

Build, vet, and go test -race pass for internal/sections and internal/jellycompat.

* perf(plugins): cache plugin installations in-memory, invalidated on lifecycle change

## Problem
Every poster/image on a warm home rail re-read plugin_installations from
Postgres to answer "is this plugin enabled?" and to acquire the plugin client
(Source A: metadata chain buildProviders enabled-check; Source B: ensureClient
-> loadInstallation). Plugin-resolved image URLs are never URL-cached, so the
plugin source and the DB read behind it fired again on every identical warm
request; 100% of images in the target library are plugin-backed.

## Solution
- Guarded in-memory installation cache (map[int]*Installation + RWMutex) in
  plugins.Service. loadInstallation reads through it; the requireEnabled gate
  stays after the cache read so ErrInstallationDisabled semantics are unchanged.
  invalidateInstallationCache clears it and is self-registered as a lifecycle
  hook, so Service.OnLifecycleChange wipes it on install/enable/disable/update/
  uninstall.
- A generation counter closes an invalidate-vs-repopulate race: captured before
  installations.GetByID and re-checked under the write lock, so a row fetched
  before a lifecycle mutation is never written into a freshly cleared cache
  (would otherwise resurrect a just-disabled plugin).
- Route the metadata chain enabled-check through the same cache via a structural
  InstallationEnabledChecker interface (nil-safe: falls back to the pool query
  when no checker is injected), wired in cmd/silo/main.go.

## Post-review fix (auto-update reliability blocker)
AutoUpdateService mutated installations (new InstallPath, old dir deleted) on
the default auto update policy without firing OnLifecycleChange, leaving the
cache stale and breaking plugins with "stored plugin manifest mismatch" until
restart. It now takes an onChange callback wired to Service.OnLifecycleChange
and fires it once per Check run that mutated a row.

## Verification
go build/vet, go test ./internal/plugins/... ./internal/metadata/... (-race).
Tests: cache hit/invalidation, racing-invalidation guard, IsInstallationEnabled,
auto-update fires onChange.

## AI-use disclosure
Implemented with AI assistance (Claude).

* perf(jellycompat): batch per-item presign, and enrich series on the cached Latest path

## Problem
List rails presigned each item's poster/backdrop/logo/still image individually
(~160 singular resolver calls for a 40-item page where 4 batched calls suffice),
and ItemsHandler carried a near-verbatim duplicate of the batch presigner.

## Solution (batching)
Promote the batch presigner to a shared package-level presignCompatListItems
(presign_list.go) with a generic collectImagePaths[T]; convert the per-item
loops (cached home/Latest rail, favorites, batch loaders, userdata favorites) to
one batched PresignImageURLsWithExpiry per image type per page; batch the
season/episode collections; delete the three duplicate presign helpers. URL
output is unchanged (verified byte-for-byte).

## Post-review fix (series Latest data-parity regression)
The native cached Latest fast path built items via compatListItemsFromModels +
buildLatestItemDTOs and never ran the series watch-state rollup, so a series
library's Latest lost Played / UnplayedItemCount and page 1 disagreed with the
BrowseItems fallback. enrichSeriesUserData is promoted to the ContentService
interface and called on the native path (reused, not duplicated).

## Verification
go build/vet, go test ./internal/jellycompat/... ./internal/catalog/...
Tests: bounded presign invocation counts + per-item URL mapping; series rollup
populated on the native Latest path.

## AI-use disclosure
Implemented with AI assistance (Claude).

* perf(sections): gate personalized rails out of the shared cache; widen refresh lead

## Problem
1. The shared home-rail cache whitelisted custom_filter/genre sections by TYPE
   alone, but those route through fetchFiltered -> ParseQueryDefinition and can
   carry personalized (per-profile) rules/sorts (watched, favorited,
   in_watchlist, in_progress, last_watched; sorts progress/date_viewed/plays).
   Their membership is per-profile yet the cache key excludes userID/profileID,
   so a personalized rail built for one profile was served to others in the same
   access scope for up to 15m -- a cross-profile watchlist/watch-state leak.
2. The background-refresh lead was tuned so steady traffic is served a warm
   entry from a longer soft window.

## Solution
- Add QueryDefinition.IsPersonalized() (reusing the existing
  QueryFieldRequiresProfile/QuerySortRequiresProfile helpers).
  isCacheableSectionType now parses the section QueryDefinition and refuses to
  cache custom_filter/genre when personalized; non-personalized definitions stay
  cacheable. Seasonal/mood/trending build their definitions server-side and stay
  unconditionally cacheable.
- resolvedListRefreshLead 3m -> 10m (soft threshold builtAt+5min instead of
  builtAt+12min).

## Verification
go build/vet, go test ./internal/sections/... ./internal/catalog/... (-race).
Test: personalized custom_filter/genre not cacheable; non-personalized are.

## AI-use disclosure
Implemented with AI assistance (Claude).

* fix(sections,metadata): post-review fixes for shared cache and plugin chain staleness

Addresses three review findings on PR Silo-Server#292:

- sections: canonicalize section config JSON before hashing so configs
  differing only in whitespace/field order share a cache entry (native +
  jellycompat rail sharing). Added TestHashSectionConfigCanonicalizes.
- metadata: invalidate the resolved-chain cache on plugin lifecycle
  changes; the installation-enabled check already reads the invalidated
  plugin cache, but resolveChainCached could serve a stale provider chain
  for up to chainCacheTTL after a provider's availability changed.
- jellycompat: move ctx to the first parameter of presignCompatListItems
  for consistency with the other presign helpers.

Skipped the episode-image presign batching nitpick: the resolver already
dedupes+singleflights, so it is a Minor perf-only item not worth the
two-pass refactor risk in this pass.

* fix(sections,jellycompat): harden shared rail cache and Latest fast path per review

Addresses the eight findings from the deep review of this PR:

- Detach the blocking cold-miss rebuild from the singleflight leader's
  request context (context.WithoutCancel + the shared 30s build timeout)
  so one client disconnect no longer fails every collapsed waiter and
  leaves the entry uncached.
- Stop client-controlled values minting unbounded cache entries: the
  compat Latest fast path now always fetches a fixed 100-row budget and
  slices to the requested limit (one entry per scope+library instead of
  one per Limit value), and an unrecognized MaxOfficialRating string
  disqualifies the fast path instead of entering the global cache key.
- Add release_date to the sections item projection/scan so movies served
  via the Latest fast path keep PremiereDate (Jellyfin default-set field)
  in parity with the BrowseItems fallback.
- Fall back to per-item progress lookups when the batched leaf progress
  query fails, restoring one-item-at-a-time degradation instead of
  blanking played state for the whole page.
- Derive cache eligibility from a single source of truth: fetchSection
  and isCacheableSectionType now share the userAgnosticSectionFetcher
  table, whose no-userID/profileID signature makes a fetcher drop out of
  the cacheable set at compile time if it ever gains per-profile inputs.
- Decide Latest fast-path eligibility off the actual browse params the
  fallback would receive, so any filter later added to buildBrowseParams
  automatically disqualifies the cached path; share one
  compatDefaultBrowseLimit constant between both paths.
- Extract AccessFilter.WriteAccessScopeCacheKey as the shared, security-
  critical serializer for all access-scoped caches (resolved-list,
  editorial candidates, audiobook groups); the editorial key now captures
  ExcludedMediaTypes, which its loaders already applied in SQL.
- Strip leaked agent-transcript markup from the section-fetch plan doc.

go build ./..., go vet, gofmt clean; go test -race on
internal/sections, internal/catalog, internal/jellycompat passes
(TestBeginWebOperation* failures are the known pre-existing flakes).

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Quick <[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