Skip to content

perf(jellycompat): fast-paths for slow Jellyfin-compat queries - #247

Merged
Quick104 merged 2 commits into
mainfrom
perf/jellycompat-fast-paths
Jul 1, 2026
Merged

Quick104 merged 2 commits into
mainfrom
perf/jellycompat-fast-paths

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • "Continue Watching" could take a minute and a half to load. The home-screen resume row averaged ~17 seconds and peaked at 91 seconds for some clients. It got dramatically worse under retry storms, where a single device hammering the server made everyone's resume row slower.
  • Opening a long-running soap opera hung for ~13 seconds. Tapping into shows with very large episode counts (Coronation Street, EastEnders, Emmerdale) stalled the episode view every time a client checked "what's the next episode."
  • The "Watched history" view took ~15 seconds. Filtering a library to already-played movies/episodes was a multi-second wait.
  • The "Recently Added" row took ~2 seconds on every load. The cross-library latest-additions shelf was consistently slow on the home screen.
  • Detail-heavy rows were sluggish. Rows where a client asks for rich metadata (media sources, chapters) took roughly a second.
  • Some home-screen rows were silently blank. Certain Jellyfin-compat "hub" sections rendered as empty rails with no error shown — a query was failing server-side and the failure was being swallowed.

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 ANALYZE against 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 made ApplySectionAccessFilter emit NOT (ece.type = ANY(...)) against episode_catalog_entries — a table with no type column. Postgres returned 42703, 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_rating filtering is preserved.

perf(jellycompat): serve Resume via capped continue-watching fetcher (117cde27)

/UserItems/Resume ran loadProgressPage, whose only early-exit was gated off when enableTotalRecordCount=true, so it scanned the entire in-progress list and re-paginated the whole completed history once per batch. It now delegates to the native sections.Fetcher continue-watching path (hard-capped: page 100, max 1000 scanned, indexed home-dismissal filtering), capped at 50 items. Results re-hydrate through the existing shared hydrateProgressItems so episode DTOs are byte-for-byte identical; a new ResolvedSection.SuppressNextUp keeps the row in-progress-only. The fast path fires for video resume requests (the dominant + slow traffic) and falls back to loadProgressPage for exotic type-only requests.

perf(jellycompat): serve /Shows/{id}/Episodes AdjacentTo from a bounded query (51d6a1cc)

AdjacentTo was unparsed, so the soap-opera autoplay/skip probe fell to the full-series path and materialized every episode (a per-episode correlated EXISTS over ~10k rows). It now parses the param and uses EpisodeRepository.ListAdjacentInSeries — a single UNION ALL of prev/self/next backed by the (series_id, season_number, episode_number) index — mapping only those ≤3 episodes through a shared writeEpisodeModelsPage helper (extracted from writeSeriesEpisodesResponse, non-adjacent behavior unchanged).

perf(jellycompat): push type+library filter into SQL for played-history (d0076f52)

/Items?IsPlayed=true with type + parentId read the full completed history and discarded non-matching rows in memory. A new UserStore.ListProgressFiltered pushes the type+library filter into SQL with EXISTS pre-filters (separate movie and episode branches — episodes join via series_id → media_items), served by the existing idx_uwp_profile_completed partial 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/Latest set LibraryID=0, forcing a MIN(first_seen_at)+GROUP BY across all libraries that the media_folder_id-leading index can't serve (EXPLAIN: 1.5ms single-library vs 373–726ms multi-library). BrowseRecentlyAddedAcrossLibraries runs the fast single-library index walk once per accessible library and merges top-N in Go, deduping on content_id keeping the earliest AddedAt to preserve the old MIN semantics.

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 called GetItemDetail per item (~10 sequential queries each). New DetailService.GetItemDetailsByIDs + ItemRepository.EnsureAccessibleIDs batch the shared work for movies/series (episodes reuse the existing GetEpisodeDetailsForSeries); buildMediaItemDetail takes 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_entries also holds podcast episodes, and a custom-filter home section exposed as a virtual library and browsed with MediaScope=episode scoped to a podcast folder could surface them in a TV section once the media-type clause was dropped. Added AND 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 if AdjacentTo names 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 with reflect.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

  • Resume TotalRecordCount is now the page length, not the full in-progress count, for clients that sent enableTotalRecordCount=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.
  • Resume is capped at 50 items; the largest observed client request was 40, so no current client is affected.
  • AdjacentTo returns prev/self/next (≤3 items), not Jellyfin's exact window — satisfies the autoplay/skip use it is actually called for.
  • Cross-library "Recently Added" dedup is approximate for a content_id present in 2+ libraries (documented in mergeRecentlyAddedItems); acceptable for an approximate recency rail.
  • Played-history tail latency: a profile with a huge completed history but a tiny matching library still walks the index (a few hundred ms in a contrived case) — ~30× better than the 13–15s baseline, no regression. The pre-existing missing ORDER BY updated_at tiebreaker (shared with ListProgress) is unchanged; a , media_item_id tiebreaker is a good future cleanup.
  • Long-term: stop populating podcast episodes into episode_catalog_entries at the migration level (add si.type='series' to migration 142's population paths) so the hydration guard becomes belt-and-suspenders.
  • Confirm prod table stats are fresh so the planner keeps the intended index plans for the played-history and latest queries.
  • The new catalog equivalence test is DB-gated (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 full go test ./... suite pass; all changed files are gofmt clean.
  • Each fix was reviewed by an independent adversarial agent against its committed diff; all six returned SHIP (the nits became the hardening/test commits above). Fix 6's access-control parity (EnsureAccessibleIDs vs EnsureAccessible) was diffed predicate-by-predicate and confirmed identical.
  • Query-plan claims were validated with EXPLAIN ANALYZE on the dev DB: single-library recently_added uses the index-only scan; the played-history filter rides idx_uwp_profile_completed (1.3–1.8ms realistic).
  • Slow/fast request splits were re-derived directly from the production logs per endpoint.

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

    • Faster “recently added,” resume, episode, search, and detail views through new batched and cross-library handling.
    • Episode pages can now show a neighboring-episode window when jumping to a specific episode.
  • Bug Fixes

    • Improved accuracy for episode listings and recently added results across multiple libraries.
    • Fixed cases where some non-TV media could appear in episode-related views.
    • Completed-progress and detail-heavy pages now load more efficiently with fewer delays.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@CoffeeKnyte, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 33 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d4b016d-9597-4c19-b19e-c4d057dd6cff

📥 Commits

Reviewing files that changed from the base of the PR and between c2761de4380476e779c934632880433ffca41ef1 and aa02c27.

📒 Files selected for processing (32)
  • internal/access/resolver_test.go
  • internal/catalog/browse.go
  • internal/catalog/browse_recently_added_merge_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_batch_equivalence_test.go
  • internal/catalog/episode_catalog_entries_executor.go
  • internal/catalog/episode_catalog_select_body_test.go
  • internal/catalog/episode_catalog_source.go
  • internal/catalog/episode_repo.go
  • internal/catalog/item_repo.go
  • internal/jellycompat/audiobook_exclusion_test.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_batch_detail_test.go
  • internal/jellycompat/handlers_items_test.go
  • internal/jellycompat/list_seasons_batch_test.go
  • internal/jellycompat/parent_browse_test.go
  • internal/jellycompat/query.go
  • internal/jellycompat/resume_filter_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/userdata_direct.go
  • internal/sections/fetcher.go
  • internal/sections/types.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
📝 Walkthrough

Walkthrough

This PR implements six jellycompat performance fast-paths identified from production logs: a si.type='series' guard for episode catalog entries, an AdjacentTo episode window query, resume via the native sections fetcher, ListProgressFiltered SQL push-down for played-history, a per-library fan-out merge for /Items/Latest multi-library browsing, and batched GetItemDetailsByIDs to eliminate N+1 detail fetching. A performance plan document is also added.

Changes

Jellycompat slow-query fast-paths

Layer / File(s) Summary
Performance plan document
docs/superpowers/plans/2026-06-29-jellycompat-slow-query-fast-paths.md
Adds a 264-line plan covering the six confirmed slow-endpoint issues, root causes, proposed fixes, compat tradeoffs, implementation ordering, and one out-of-scope background churn note.
Episode catalog si.type='series' guard and access filter fix
internal/catalog/episode_catalog_source.go, internal/catalog/episode_catalog_entries_executor.go, internal/catalog/episode_catalog_select_body_test.go
Adds AND si.type = 'series' to episodeCatalogSelectBody and an EXISTS-based episodeCatalogSeriesParentGuard; introduces applyEpisodeCatalogAccessFilter to zero ExcludedMediaTypes before delegating to ApplySectionAccessFilter at both call sites; test asserts the predicate propagates through library-scoped relations.
AdjacentTo episode window: repo, query parsing, handler routing, tests
internal/catalog/episode_repo.go, internal/jellycompat/batch_loaders.go, internal/jellycompat/query.go, internal/jellycompat/handlers_items.go, internal/jellycompat/parent_browse_test.go, internal/jellycompat/batch_loaders_test.go, internal/jellycompat/handlers_items_test.go
Adds ListAdjacentInSeries (single UNION ALL SQL for prev/self/next); parses AdjacentTo query param; routes HandleEpisodes to writeAdjacentEpisodesResponse with series-membership validation and full-listing fallback; adds fake and handler tests.
Resume via sections fast path: SuppressNextUp + loadResumeViaSections
internal/sections/types.go, internal/sections/fetcher.go, internal/jellycompat/handlers_items.go, internal/jellycompat/router.go
Adds SuppressNextUp to ResolvedSection and gates next_up_mode fetch on it; adds sectionsFetcher field to ItemsHandler; implements loadResumeViaSections (hard cap, suppress next-up, type-trim, paginate, hydrate); wires fetcher in router; handleResumeResponse uses the fast path when available.
Played-history SQL push-down: ListProgressFiltered interface, pgstore, sqlite, handler wiring, tests
internal/userstore/store.go, internal/userstore/pgstore/progress.go, internal/userdb/sqlitestore.go, internal/userstore/storetest/suite.go, internal/jellycompat/content_service.go, internal/jellycompat/userdata_direct.go, internal/jellycompat/handlers_items.go, internal/jellycompat/resume_filter_test.go, internal/access/resolver_test.go
Adds ListProgressFiltered to UserStore; implements it in PostgresUserStore with buildProgressCatalogFilter (EXISTS branches per type + optional library JOIN); stubs in SQLiteUserStore; exposes on UserDataService; wires into loadProgressPage for completed+type-filter path; switches upgradeProgressPageToDetail to batchListItemDetails; adds storetest, handler, and stub coverage.
Multi-library recently-added merge: BrowseRecentlyAddedAcrossLibraries + content_direct fast path
internal/catalog/browse.go, internal/catalog/browse_recently_added_merge_test.go, internal/jellycompat/content_direct.go, internal/jellycompat/content_direct_test.go, internal/jellycompat/audiobook_exclusion_test.go, internal/jellycompat/list_seasons_batch_test.go
Adds BrowseRecentlyAddedAcrossLibraries (per-library BrowsePage fan-out, dedup/sort via mergeRecentlyAddedItems, HasMore/Total lower-bound nudge); refactors ListUserLibraries into accessibleFolders/accessibleLibraryIDs; wires cross-library fast path in BrowseItems (offset==0, 2+ libraries); switches list/search localization to bulk LocalizeItemModels; adds merge and routing tests.
Batch item detail N+1 fix: GetItemDetailsByIDs, EnsureAccessibleIDs, handler wiring, tests
internal/catalog/item_repo.go, internal/catalog/detail.go, internal/catalog/detail_batch_equivalence_test.go, internal/jellycompat/content_service.go, internal/jellycompat/content_direct.go, internal/jellycompat/handlers_items.go, internal/jellycompat/handlers_items_batch_detail_test.go, internal/jellycompat/handlers_items_test.go, internal/jellycompat/batch_progress_test.go
Adds EnsureAccessibleIDs (bulk access map); refactors localization error handling; adds itemDetailPrefetch and GetItemDetailsByIDs on DetailService; exposes on ContentService and implements in content_direct with groupEpisodesBySeries; introduces batchListItemDetails helper with per-item fallback; switches HandleLatest/handleBrowseItems/handleSearchItems/upgradeProgressPageToDetail to batch path; adds Postgres integration equivalence test and handler equivalence test.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-server#69: Both PRs modify upgradeProgressPageToDetail and detail upgrade batching/capping logic in handlers_items.go.
  • Silo-Server/silo-server#115: This PR's applyEpisodeCatalogAccessFilter explicitly clears ExcludedMediaTypes introduced by that PR to avoid invalid SQL on the type-less episode_catalog_entries table.
  • Silo-Server/silo-server#160: Both PRs modify HandleEpisodes/writeSeriesEpisodesResponse series-episode browse routing in handlers_items.go.

Suggested labels

v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.24% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the PR’s main focus on Jellyfin-compat performance fast-paths and is concise.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/jellycompat-fast-paths

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jun 29, 2026
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/jellycompat-fast-paths branch from 4603875 to 7df445c Compare June 29, 2026 14:17

@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: 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.md
  • internal/access/resolver_test.go
  • internal/catalog/browse.go
  • internal/catalog/browse_recently_added_merge_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_batch_equivalence_test.go
  • internal/catalog/episode_catalog_entries_executor.go
  • internal/catalog/episode_catalog_select_body_test.go
  • internal/catalog/episode_catalog_source.go
  • internal/catalog/episode_repo.go
  • internal/catalog/item_repo.go
  • internal/jellycompat/audiobook_exclusion_test.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_collections.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_items_batch_detail_test.go
  • internal/jellycompat/handlers_items_test.go
  • internal/jellycompat/handlers_persons.go
  • internal/jellycompat/handlers_sections.go
  • internal/jellycompat/idcodec.go
  • internal/jellycompat/list_seasons_batch_test.go
  • internal/jellycompat/parent_browse_test.go
  • internal/jellycompat/query.go
  • internal/jellycompat/resume_filter_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/search_guard.go
  • internal/jellycompat/search_guard_test.go
  • internal/jellycompat/userdata_direct.go
  • internal/sections/fetcher.go
  • internal/sections/types.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go

Comment thread internal/catalog/browse.go Resolved
Comment thread internal/jellycompat/content_direct.go Resolved
Comment thread internal/jellycompat/handlers_items.go Resolved
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/jellycompat-fast-paths branch from 7df445c to c2761de Compare June 30, 2026 10:16
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.
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/jellycompat-fast-paths branch from c2761de to 7ad8cea Compare June 30, 2026 10:21
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Fixed all the issues raised above and squashed the change set down into a single commit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@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.md
  • internal/access/resolver_test.go
  • internal/catalog/browse.go
  • internal/catalog/browse_recently_added_merge_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_batch_equivalence_test.go
  • internal/catalog/episode_catalog_entries_executor.go
  • internal/catalog/episode_catalog_select_body_test.go
  • internal/catalog/episode_catalog_source.go
  • internal/catalog/episode_repo.go
  • internal/catalog/item_repo.go
  • internal/jellycompat/audiobook_exclusion_test.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_batch_detail_test.go
  • internal/jellycompat/handlers_items_test.go
  • internal/jellycompat/list_seasons_batch_test.go
  • internal/jellycompat/parent_browse_test.go
  • internal/jellycompat/query.go
  • internal/jellycompat/resume_filter_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/userdata_direct.go
  • internal/sections/fetcher.go
  • internal/sections/types.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/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

Comment thread internal/jellycompat/handlers_items.go Resolved
Comment thread internal/jellycompat/handlers_items.go Resolved
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.
@Quick104
Quick104 merged commit fad08fd into main Jul 1, 2026
1 check passed
@Quick104
Quick104 deleted the perf/jellycompat-fast-paths branch July 1, 2026 13:06
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…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.
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.

2 participants