Repository navigation
perf(jellycompat): fast-paths for slow Jellyfin-compat queries - #247
Conversation
|
Warning Review limit reached
Next review available in: 33 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between c2761de4380476e779c934632880433ffca41ef1 and aa02c27. 📒 Files selected for processing (32)
📝 WalkthroughWalkthroughThis PR implements six jellycompat performance fast-paths identified from production logs: a ChangesJellycompat slow-query fast-paths
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related issues
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
4603875 to
7df445c
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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/catalog/browse.go`:
- Around line 158-161: `BrowseRecentlyAddedAcrossLibraries` is using the raw
`base.Limit` when trimming the merged result, so the final page can exceed the
normal `MaxLimit` contract. Update the limit handling in
`BrowseRecentlyAddedAcrossLibraries` to clamp the requested limit against
`BrowseFilters.MaxLimit` before merging/truncating results, keeping the existing
fallback behavior for non-positive limits. Use the existing `base.Limit`,
`MaxLimit`, and `BrowsePage` flow to locate the change.
In `@internal/catalog/episode_catalog_entries_executor.go`:
- Around line 35-50: Keep the entry scan and hydrated results aligned by not
dropping ExcludedMediaTypes in applyEpisodeCatalogAccessFilter unless the same
media-type exclusion is also enforced in the episodeCatalogSelectBody hydration
path. The page/count queries currently still admit podcast/audiobook ece rows
that later fail the si.type = 'series' guard, so update the filtering logic in
applyEpisodeCatalogAccessFilter and the related query builders to apply the same
media-type constraint consistently before counting or paging.
In `@internal/jellycompat/content_direct.go`:
- Around line 337-342: The fan-out ID collection in accessibleLibraryIDs is
including compat-hidden folders, which lets the fast path query libraries that
ListUserLibraries intentionally excludes. Update the ID gathering logic to apply
the same Jellyfin compat filtering used for audiobook/podcast folders before
appending IDs, so only exposed libraries are returned and later used by
/Items/Latest. Use accessibleLibraryIDs and ListUserLibraries as the key places
to keep the filtering consistent.
In `@internal/jellycompat/handlers_items_batch_detail_test.go`:
- Around line 144-151: The fallback test in handlers_items_batch_detail_test is
too weak because it only verifies per-item fetches and can miss a regression
where handleBrowseItems skips the batched path entirely. Tighten the assertion
for the fallback branch by also checking that the batch path was attempted once
for the perItemContent run, using the existing batchCalls and perItemCalls
counters around GetItemDetailsByIDs and the fallback fetch logic.
In `@internal/jellycompat/handlers_items.go`:
- Around line 1493-1519: The AdjacentTo fast path in handlers_items.go bypasses
library authorization by querying episodeRepo directly without first applying
resolveAccessFilter(...). Update this path to enforce the caller’s
AllowedLibraryIDs before any DTOs are returned, either by routing through an
access-filtered content lookup or by passing the allowed library IDs into both
the target lookup and ListAdjacentInSeries calls. Ensure the target episode
validation and neighbor fetch both use the same access-filtered scope so
episodes from unauthorized libraries cannot be returned.
In `@internal/jellycompat/handlers_sections.go`:
- Around line 96-127: `fetchSectionItems` and `handleSectionBrowse` are ignoring
pagination state, so hub-section virtual-library requests always return the
first page and a fake total. Update the browse flow to accept and propagate
`StartIndex` and `Limit` through `fetchSectionItems`, `handleSectionBrowse`, and
any related section fetch logic so the upstream fetch uses the requested offset.
Return the real `TotalRecordCount` from the section result instead of
`len(items)` and ensure the sliced items reflect the requested page.
🪄 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: a1a07485-e918-477d-a651-3932593de0b6
📥 Commits
Reviewing files that changed from the base of the PR and between ba80e6f and 46038759dd2b819edabf21234888790c42f00a3b.
📒 Files selected for processing (39)
docs/superpowers/plans/2026-06-29-jellycompat-slow-query-fast-paths.mdinternal/access/resolver_test.gointernal/catalog/browse.gointernal/catalog/browse_recently_added_merge_test.gointernal/catalog/detail.gointernal/catalog/detail_batch_equivalence_test.gointernal/catalog/episode_catalog_entries_executor.gointernal/catalog/episode_catalog_select_body_test.gointernal/catalog/episode_catalog_source.gointernal/catalog/episode_repo.gointernal/catalog/item_repo.gointernal/jellycompat/audiobook_exclusion_test.gointernal/jellycompat/batch_loaders.gointernal/jellycompat/batch_loaders_test.gointernal/jellycompat/batch_progress_test.gointernal/jellycompat/content_direct.gointernal/jellycompat/content_direct_test.gointernal/jellycompat/content_service.gointernal/jellycompat/handlers_collections.gointernal/jellycompat/handlers_items.gointernal/jellycompat/handlers_items_batch_detail_test.gointernal/jellycompat/handlers_items_test.gointernal/jellycompat/handlers_persons.gointernal/jellycompat/handlers_sections.gointernal/jellycompat/idcodec.gointernal/jellycompat/list_seasons_batch_test.gointernal/jellycompat/parent_browse_test.gointernal/jellycompat/query.gointernal/jellycompat/resume_filter_test.gointernal/jellycompat/router.gointernal/jellycompat/search_guard.gointernal/jellycompat/search_guard_test.gointernal/jellycompat/userdata_direct.gointernal/sections/fetcher.gointernal/sections/types.gointernal/userdb/sqlitestore.gointernal/userstore/pgstore/progress.gointernal/userstore/store.gointernal/userstore/storetest/suite.go
7df445c to
c2761de
Compare
Rebuilds the jellycompat slow-query fast-paths cleanly on main, without
the hub-sections virtual-library feature (which is intentionally absent
on this branch). Each path is bounded so behavior stays predictable
under load.
Fast-paths:
- Episode catalog: add the load-bearing `si.type = 'series'` hydration
guard plus a matching entry-scan series-parent guard, so the page and
count scans stay aligned with hydration (no under-filled pages, no
inflated TotalRecordCount from podcast/audiobook episode rows).
- /Shows/{id}/Episodes AdjacentTo: serve a bounded prev/self/next
neighbor window with series-membership validation and a cross-series
id guard, falling back to the full listing.
- Resume: serve Continue Watching through the capped native
continue-watching fetcher (next-up suppressed, in-progress only)
instead of loadProgressPage's unbounded scan. Wires only the
sections read-time fetcher (StoreProvider) into ItemsHandler; no
hub-section/virtual-library exposure.
- Played-history: push the type + library filter down into SQL.
- recently_added: fan a no-parentId browse out across libraries with an
app-side dedup merge, clamped to BrowseFilters.MaxLimit, and exclude
compat-hidden (audiobook/podcast) libraries from the fan-out.
- Detail fields: batch per-item GetItemDetail in the Latest/browse
detail-field paths via GetItemDetailsByIDs, with per-item fallback.
- Search: term-length and result-count guards for aux search.
c2761de to
7ad8cea
Compare
|
Fixed all the issues raised above and squashed the change set down into a single commit. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/jellycompat/handlers_items.go`:
- Around line 1771-1795: The fallback in batchListItemDetails only retries
per-item fetches when GetItemDetailsByIDs fails entirely, but successful batch
responses can still omit some IDs that need detail data. Update
ItemsHandler.batchListItemDetails so it merges missing entries by calling
GetItemDetail for any contentIDs not present in the batch result, preserving the
existing nil/empty behavior and keeping list fallback only for truly unresolved
IDs. Apply the same gap-filling logic in the other batch detail helpers
referenced by the review so callers still get MediaSources, Chapters, and People
for IDs that the batch path skips.
- Around line 2236-2268: The resume fast path is still letting a large
client-supplied StartIndex expand the scan beyond the intended cap. In
loadResumeViaSections, adjust the fetch sizing logic so ItemLimit cannot exceed
maxResumeItems even when query.startIndex is large, while still allowing slicing
of the returned page; use the existing maxResumeItems, query.startIndex, and
resolved.ItemLimit handling in ItemsHandler.loadResumeViaSections to keep the
capped fetch bounded.
🪄 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: a21d7ac3-afb9-413c-8a37-7d8f5634b1e9
📥 Commits
Reviewing files that changed from the base of the PR and between 46038759dd2b819edabf21234888790c42f00a3b and c2761de4380476e779c934632880433ffca41ef1.
📒 Files selected for processing (33)
docs/superpowers/plans/2026-06-29-jellycompat-slow-query-fast-paths.mdinternal/access/resolver_test.gointernal/catalog/browse.gointernal/catalog/browse_recently_added_merge_test.gointernal/catalog/detail.gointernal/catalog/detail_batch_equivalence_test.gointernal/catalog/episode_catalog_entries_executor.gointernal/catalog/episode_catalog_select_body_test.gointernal/catalog/episode_catalog_source.gointernal/catalog/episode_repo.gointernal/catalog/item_repo.gointernal/jellycompat/audiobook_exclusion_test.gointernal/jellycompat/batch_loaders.gointernal/jellycompat/batch_loaders_test.gointernal/jellycompat/batch_progress_test.gointernal/jellycompat/content_direct.gointernal/jellycompat/content_direct_test.gointernal/jellycompat/content_service.gointernal/jellycompat/handlers_items.gointernal/jellycompat/handlers_items_batch_detail_test.gointernal/jellycompat/handlers_items_test.gointernal/jellycompat/list_seasons_batch_test.gointernal/jellycompat/parent_browse_test.gointernal/jellycompat/query.gointernal/jellycompat/resume_filter_test.gointernal/jellycompat/router.gointernal/jellycompat/userdata_direct.gointernal/sections/fetcher.gointernal/sections/types.gointernal/userdb/sqlitestore.gointernal/userstore/pgstore/progress.gointernal/userstore/store.gointernal/userstore/storetest/suite.go
✅ Files skipped from review due to trivial changes (3)
- internal/jellycompat/list_seasons_batch_test.go
- internal/jellycompat/batch_loaders_test.go
- docs/superpowers/plans/2026-06-29-jellycompat-slow-query-fast-paths.md
🚧 Files skipped from review as they are similar to previous changes (25)
- internal/catalog/browse_recently_added_merge_test.go
- internal/jellycompat/handlers_items_batch_detail_test.go
- internal/catalog/episode_catalog_select_body_test.go
- internal/sections/types.go
- internal/userstore/storetest/suite.go
- internal/userstore/store.go
- internal/catalog/episode_catalog_entries_executor.go
- internal/jellycompat/content_service.go
- internal/jellycompat/audiobook_exclusion_test.go
- internal/jellycompat/userdata_direct.go
- internal/jellycompat/batch_progress_test.go
- internal/userdb/sqlitestore.go
- internal/jellycompat/resume_filter_test.go
- internal/catalog/episode_repo.go
- internal/jellycompat/handlers_items_test.go
- internal/jellycompat/query.go
- internal/jellycompat/parent_browse_test.go
- internal/jellycompat/batch_loaders.go
- internal/catalog/browse.go
- internal/catalog/item_repo.go
- internal/sections/fetcher.go
- internal/userstore/pgstore/progress.go
- internal/access/resolver_test.go
- internal/jellycompat/content_direct_test.go
- internal/jellycompat/content_direct.go
A large client-supplied StartIndex on /UserItems/Resume inflated loadResumeViaSections' fetchLimit (pageSize + StartIndex) and fed it straight into ResolvedSection.ItemLimit, letting the continue-watching fetcher scan up to its continueProgressMaxScanned hard cap (1000 rows) instead of stopping near maxResumeItems. Clamp fetchLimit to maxResumeItems and short-circuit to an empty page when StartIndex is at or beyond the cap (no visible row can land there), keeping the capped fetcher's scan bounded and predictable under load. Addresses CodeRabbit review finding on PR #247.
…Server#247) * perf(jellycompat): fast-paths for slow Jellyfin-compat queries Rebuilds the jellycompat slow-query fast-paths cleanly on main, without the hub-sections virtual-library feature (which is intentionally absent on this branch). Each path is bounded so behavior stays predictable under load. Fast-paths: - Episode catalog: add the load-bearing `si.type = 'series'` hydration guard plus a matching entry-scan series-parent guard, so the page and count scans stay aligned with hydration (no under-filled pages, no inflated TotalRecordCount from podcast/audiobook episode rows). - /Shows/{id}/Episodes AdjacentTo: serve a bounded prev/self/next neighbor window with series-membership validation and a cross-series id guard, falling back to the full listing. - Resume: serve Continue Watching through the capped native continue-watching fetcher (next-up suppressed, in-progress only) instead of loadProgressPage's unbounded scan. Wires only the sections read-time fetcher (StoreProvider) into ItemsHandler; no hub-section/virtual-library exposure. - Played-history: push the type + library filter down into SQL. - recently_added: fan a no-parentId browse out across libraries with an app-side dedup merge, clamped to BrowseFilters.MaxLimit, and exclude compat-hidden (audiobook/podcast) libraries from the fan-out. - Detail fields: batch per-item GetItemDetail in the Latest/browse detail-field paths via GetItemDetailsByIDs, with per-item fallback. - Search: term-length and result-count guards for aux search. * perf(jellycompat): clamp Resume fast-path fetch to maxResumeItems A large client-supplied StartIndex on /UserItems/Resume inflated loadResumeViaSections' fetchLimit (pageSize + StartIndex) and fed it straight into ResolvedSection.ItemLimit, letting the continue-watching fetcher scan up to its continueProgressMaxScanned hard cap (1000 rows) instead of stopping near maxResumeItems. Clamp fetchLimit to maxResumeItems and short-circuit to an empty page when StartIndex is at or beyond the cap (no visible row can land there), keeping the capped fetcher's scan bounded and predictable under load. Addresses CodeRabbit review finding on PR Silo-Server#247.
Part of #246
Six performance/correctness fixes for the Jellyfin-compat path, derived from a 3-hour production log analysis and each verified by an independent adversarial review. Ordered by impact-per-risk; commits are split one-per-fix with separate hardening/test follow-ups.
Problem
A production log window (08:27–11:27, ~62k requests) showed the Jellyfin-compat surface — the API that Infuse, Wholphin, and the Jellyfin clients talk to — was responsible for 473 of the 500 slowest requests. The user-visible symptoms:
Solution
Each fix prefers reuse of an existing fast Silo path and accepts reduced Jellyfin fidelity where it is safe (never reduced access control). Verified with
EXPLAIN ANALYZEagainst the dev DB where a query plan was in question.fix(catalog): drop media-type exclusion on column-less episode_catalog_entries (
0e5c954e)The blank hub rails were a swallowed SQL error. Jellycompat injects
ExcludedMediaTypes=[audiobook,podcast]into every section access filter, which madeApplySectionAccessFilteremitNOT (ece.type = ANY(...))againstepisode_catalog_entries— a table with notypecolumn. Postgres returned42703, the handler degraded to an empty array, and the rail rendered blank. The exclusion is dropped on this path (internal/catalog/episode_catalog_entries_executor.go);content_ratingfiltering is preserved.perf(jellycompat): serve Resume via capped continue-watching fetcher (
117cde27)/UserItems/ResumeranloadProgressPage, whose only early-exit was gated off whenenableTotalRecordCount=true, so it scanned the entire in-progress list and re-paginated the whole completed history once per batch. It now delegates to the nativesections.Fetchercontinue-watching path (hard-capped: page 100, max 1000 scanned, indexed home-dismissal filtering), capped at 50 items. Results re-hydrate through the existing sharedhydrateProgressItemsso episode DTOs are byte-for-byte identical; a newResolvedSection.SuppressNextUpkeeps the row in-progress-only. The fast path fires for video resume requests (the dominant + slow traffic) and falls back toloadProgressPagefor exotic type-only requests.perf(jellycompat): serve /Shows/{id}/Episodes AdjacentTo from a bounded query (
51d6a1cc)AdjacentTowas unparsed, so the soap-opera autoplay/skip probe fell to the full-series path and materialized every episode (a per-episode correlatedEXISTSover ~10k rows). It now parses the param and usesEpisodeRepository.ListAdjacentInSeries— a singleUNION ALLof prev/self/next backed by the(series_id, season_number, episode_number)index — mapping only those ≤3 episodes through a sharedwriteEpisodeModelsPagehelper (extracted fromwriteSeriesEpisodesResponse, non-adjacent behavior unchanged).perf(jellycompat): push type+library filter into SQL for played-history (
d0076f52)/Items?IsPlayed=truewith type +parentIdread the full completed history and discarded non-matching rows in memory. A newUserStore.ListProgressFilteredpushes the type+library filter into SQL with EXISTS pre-filters (separate movie and episode branches — episodes join viaseries_id → media_items), served by the existingidx_uwp_profile_completedpartial index. Identical result set/ordering; SQLite (no catalog tables) returns the coarse page and the in-memory backstop narrows it.perf(jellycompat): fan out no-parent recently_added across libraries (
be9e7420)No-parent
/Items/LatestsetLibraryID=0, forcing aMIN(first_seen_at)+GROUP BYacross all libraries that themedia_folder_id-leading index can't serve (EXPLAIN: 1.5ms single-library vs 373–726ms multi-library).BrowseRecentlyAddedAcrossLibrariesruns the fast single-library index walk once per accessible library and merges top-N in Go, deduping oncontent_idkeeping the earliestAddedAtto preserve the oldMINsemantics.perf(jellycompat): batch per-item GetItemDetail in detail-field paths (
0cf1242a)When a list request asks for
MediaSources/Chapters/etc., the Latest/browse/search/Resume-detail loops calledGetItemDetailper item (~10 sequential queries each). NewDetailService.GetItemDetailsByIDs+ItemRepository.EnsureAccessibleIDsbatch the shared work for movies/series (episodes reuse the existingGetEpisodeDetailsForSeries);buildMediaItemDetailtakes an opt-in prefetch and falls back inline, so the per-item path is unchanged. Output DTOs are identical.Hardening / tests from the adversarial review
fix(catalog): guard episode catalog hydration to series-parented episodes(8c9aa4aa). The review upgraded a latent risk to a reachable one:episode_catalog_entriesalso holds podcast episodes, and a custom-filter home section exposed as a virtual library and browsed withMediaScope=episodescoped to a podcast folder could surface them in a TV section once the media-type clause was dropped. AddedAND si.type = 'series'to the shared hydration body (free on the hot path; the page query stays index-only) so non-series episodes are dropped on every episode-scope surface, plus a regression test and a corrected comment.fix(jellycompat): guard AdjacentTo against cross-series episode ids(0f2cac44). Returns an empty page ifAdjacentTonames an episode from a different series than the path{id}(was silently mislabeled); also corrects a stale index reference.test(catalog): equivalence test for batched GetItemDetailsByIDs vs per-item(46038759). The original equivalence test was tautological (both stubs returned identical canned data). Added a DB-gated catalog-level test that drives the real batch vs per-item code over shared repos withreflect.DeepEqual, covering access checks, localization, credits ordering, and an access-control rejection case; verified non-tautological by injecting a divergence.docs(catalog): note cross-library dup ranking limitation(05f522c5).Risk / follow-ups
TotalRecordCountis now the page length, not the full in-progress count, for clients that sentenableTotalRecordCount=true(~1/3 of sampled traffic). The field/type are unchanged (no v1 contract break) and no client renders a total on this row, but a "see all" affordance driven by it would under-count.AdjacentToreturns prev/self/next (≤3 items), not Jellyfin's exact window — satisfies the autoplay/skip use it is actually called for.content_idpresent in 2+ libraries (documented inmergeRecentlyAddedItems); acceptable for an approximate recency rail.ORDER BY updated_attiebreaker (shared withListProgress) is unchanged; a, media_item_idtiebreaker is a good future cleanup.episode_catalog_entriesat the migration level (addsi.type='series'to migration 142's population paths) so the hydration guard becomes belt-and-suspenders.SILO_TEST_DATABASE_URL); it skips when unset, matching the repo's existing integration-test pattern — ensure CI provides the DB to run it.Verification
go build ./...,go vet ./..., and the fullgo test ./...suite pass; all changed files aregofmtclean.EnsureAccessibleIDsvsEnsureAccessible) was diffed predicate-by-predicate and confirmed identical.EXPLAIN ANALYZEon the dev DB: single-library recently_added uses the index-only scan; the played-history filter ridesidx_uwp_profile_completed(1.3–1.8ms realistic).AI-use disclosure
The log analysis, root-causing, implementation, and adversarial review were performed with AI assistance (Claude Code). Each fix and its review were run as separate agents; all changes were build/vet/test-verified, and query plans were checked against a live dev database. Findings and code were reviewed before commit.
Summary by CodeRabbit
New Features
Bug Fixes