Skip to content

perf(jellycompat): make Items/Latest skip the library count and browse by index - #3096

Merged
Quick104 merged 3 commits into
mainfrom
perf/jellycompat-latest-no-total
Oct 27, 2026
Merged

Quick104 merged 3 commits into
mainfrom
perf/jellycompat-latest-no-total

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1246 C1; changes #1246 C2. Jellyfin Latest and library browsing, including restricted-profile library lists and home rows, now take a faster query path with unchanged results; both cases should be re-tested on the merged build.

In Jellyfin apps, the "Latest" rows for a large movie library loaded slowly, and much more slowly with watched items hidden. On one production server this took up to 42 seconds and affected up to 10 users. Two separate costs caused it:

  • The server counted every movie in the library for a number the Latest response never includes. With watched items hidden, that count checked each movie against the viewer's watch history.
  • To find the 20 newest movies, the server read, sorted and grouped every movie in the library.

Solution

  • Latest no longer counts the library. A request with Limit=0 returns an empty list without querying.
  • A library browse that also carries the viewer's allowed libraries, as every Jellyfin browse does, now reads the newest items straight from the existing "newest first" library index and stops after one page.

Result

Same data (150,000 movies, 20 cards), before → after:

  • "Latest" with watched items hidden: 2,479 ms → 7.5 ms
  • "Latest" movies in Infuse: 621 ms → 52 ms
  • "Latest" movies in Android TV: 632 ms → 45 ms

In production, the slowest "Latest" request with watched items hidden dropped from 42 s to 2.3 s after the count fix. The browse fix removes most of what's left.

Technical details

  • buildLatestBrowseParams sets include_total=false. Clients leave EnableTotalRecordCount on, and IsPlayed=false turns off the cached Latest path, so the catalog ran a full count that HandleLatest then discarded.
  • HandleLatest returns [] when Limit=0 (countOnly). Before, count_only still ran that count.
  • buildBrowsePlan already skips the GROUP BY for a one-library browse, so ORDER BY mil.first_seen_at can walk idx_item_libraries_folder_seen_content. Requests that also set LibraryIDs missed that path. Now, when LibraryID is in LibraryIDs, the list no longer restricts the library join; when it isn't, the browse returns nothing, as the two conditions together already did. LibraryIDs still limits the file-level audio and subtitle language predicates to files the viewer can open. Native API browses don't reach this path: they set either LibraryID or LibraryIDs, never both.

Validation

  • Unit tests: Latest sends include_total=false with the watched filter; Limit=0 answers [] without browsing; a library inside the allowed list builds the single-library plan, still limits language matches to allowed libraries, and one outside it returns nothing. Each of these fails without its fix.
  • go test for internal/catalog, internal/jellycompat, internal/sections and internal/api/... against a fresh local Postgres 18 database passes, except TestAttachmentServesActualFontAndRejectsWrongRoute, which fails the same way on main on this machine.
  • make lint-changed: clean.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3096/

Risks

The browse change affects every single-library browse that carries an allowed-library list. Today only jellycompat sends both. The results are the same by construction, and the existing browse tests pass.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: a separate Claude Code agent (claude-opus-5-5) reviewed all three commits and the review comments. For the browse change it checked items in several libraries, ordering, the added-at value, counts, facets, disabled libraries and every caller of the plan builder. It found one defect: dropping the allowed list also dropped it from the audio and subtitle language file filter, so a restricted viewer could match on a file in a library they cannot open. That is fixed and has a test. It confirmed CodeRabbit's two comments, which are fixed.

Note

Skip total-count and library-scope join for Jellyfin Items/Latest browsing

  • buildLatestBrowseParams in query.go now sets include_total=false, so Latest requests never trigger a total-record count from the browse.
  • buildBrowsePlan in browse.go uses a separate library scope: when the requested LibraryID is in the LibraryIDs allowlist, the plan omits the library ANY condition and skips GROUP BY on the single-library path. A library outside the allowlist returns an early-empty plan.
  • ItemsHandler.HandleLatest in handlers_items.go returns HTTP 200 with an empty JSON array for count-only requests before running the browse.
  • Behavioral Change: Latest responses with count-only queries now get 200 [] instead of proceeding through full handler logic; file-level language predicates still honor the original allowlist.

Macroscope summarized 59f0232.

@silo-triage silo-triage Bot added the size/S 0–49 added + deleted lines (all files); change volume, not priority. label Oct 26, 2026
@silo-kody

silo-kody Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 74f3a40d-b204-49c3-a437-53e4a197ec67
Commits

Reviewing files that changed from the base of the PR and between 6ddbf9e and 59f0232.

Files selected for processing: 4
  • internal/catalog/browse.go
  • internal/catalog/browse_library_scope_test.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/latest_via_sections_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Walkthrough

Latest-item requests now disable total-count inclusion and return an empty array for count-only requests. Catalog browse planning adjusts library-row scope when an explicit library is checked against an allowlist.

Changes: Latest-item requests

Layer / File(s) Summary
Latest request handling
internal/jellycompat/query.go, internal/jellycompat/handlers_items.go, internal/jellycompat/latest_via_sections_test.go
Latest browse parameters set include_total to false. HandleLatest returns an empty array for count-only requests. Tests cover the parameter and HTTP response behavior.

Catalog browse library scope

Layer / File(s) Summary
Explicit library with an allowlist
internal/catalog/browse.go, internal/catalog/browse_library_scope_test.go
When an explicit library is excluded from LibraryIDs, browse planning returns an empty plan. When included, it uses the single-library SQL path and retains the allowlist for file-level predicates. Tests cover SQL shape, language constraints, and the excluded-library case.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested labels: bug, impact: usability

Suggested reviewers: quick104

Merge Risk: Minimal · up to 59f02

The unplayed Latest regression case is now covered, and the count-only test protects the early return. No actionable issue remains before merge.

Security architecture risk: Minimal · up to 59f02

The optimization preserves authenticated viewer and library restrictions while removing counting work whose result was not returned. No material security risk introduced or worsened by this PR was identified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The security-sensitive scope is catalog visibility through shared page and count planning, not only Latest. In the inspected production path, account and profile scope still constrain request-selected libraries; the optimization does not confer additional service authority.

Security Findings and Attack Paths

  • inferred — The proposed bypass through a client-chosen explicit library is not supported: excluded libraries terminate with an empty plan, while admitted libraries retain the exact library predicate and independent disabled-library and maturity checks. This preserves the previous authorization intersection.

Trust Boundaries and Controls

  • observed — Items and Latest routes use session-or-API-key authentication. The resolved session supplies account and profile identity to access resolution; the Latest early return remains behind session validation and rejection of a mismatched route-user ID.

Resilience and Maintainability Implications

  • observed — Changing include_total does not broaden eligibility for the existing shared-cache path: the gate already accepts that parameter regardless of value and rejects parameters it cannot reproduce. Played-state filtering therefore does not become cache-eligible through this change.
Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title "perf(jellycompat): make Items/Latest skip the library count and browse by index" matches the main change. The PR skips the total count for Latest requests, returns an empty array for Limit=…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the problem (slow Jellyfin Latest rows caused by an unnecessary total count and a full library scan), the two fixes (skipping the count for Limit=0 and Latest requests, and a si…
Full details: Title check

Explanation

The title "perf(jellycompat): make Items/Latest skip the library count and browse by index" matches the main change. The PR skips the total count for Latest requests, returns an empty array for Limit=0, and lets library browses use the newest-first index. The title names the Latest count change but not the browse-plan change in catalog, so it covers the primary change without every detail. It is specific and not vague.

Full details: Description check

Explanation

The description states the problem (slow Jellyfin Latest rows caused by an unnecessary total count and a full library scan), the two fixes (skipping the count for Limit=0 and Latest requests, and a single-library browse path that reads the existing index), the measured results, validation, and risks. It is directly related to the changeset, and the level of detail is more than sufficient.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@macroscopeapp

macroscopeapp Bot commented Oct 26, 2026

Copy link
Copy Markdown

/Items/Latest with an unplayed filter now responds sooner by skipping the full-library total count (internal/jellycompat/query.go); this user-perceived loading-time change is not shown by Evidence: none, no user-visible change. Please add a short before-and-after recording of the same client screen and request on the same library, showing the timing difference and naming the surface and builds or commits, or explain why capture was unavailable.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@coderabbitai coderabbitai Bot added bug Something isn't working go Pull requests that update go code impact: usability Core flow broken or severely blocked labels Oct 26, 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: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 192ef82c-5b46-411a-ac8a-b98bd374b63f
Commits

Reviewing files that changed from the base of the PR and between 44b563e and 6ddbf9e.

Files selected for processing: 2
  • internal/jellycompat/latest_via_sections_test.go
  • internal/jellycompat/query.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Comment thread internal/jellycompat/query.go Resolved
CoffeeKnyte and others added 2 commits October 26, 2026 14:46
Items/Latest returns a bare array, but its browse params asked for a
total whenever the client left EnableTotalRecordCount on, which is the
default. With an unplayed filter that disables the cached Latest path, the
count scanned every item in the library against the profile's progress:
27–42 s on a 141,000-movie library, and the slowest Latest requests were
waiting on a number nobody reads. Latest now always sends
include_total=false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Latest returns a bare array with no total, but Limit=0 still set
count_only, so the catalog counted every matching item (with an unplayed
filter, the whole library against the profile's progress) only for the
handler to write an empty array. Latest now answers [] straight away,
as Jellyfin does.

The include_total test now uses the unplayed filter the original fix
was about.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@macroscopeapp

macroscopeapp Bot commented Oct 26, 2026

Copy link
Copy Markdown

Validation impact

The October 23 report in #1246 records C1 and C2 results on local integration build 31fabc723 with #2934, #2935, and #2970; the issue body's Results table still says Not run. Both reports include home-row browsing through the Jellyfin Latest path. This PR skips the count that Items/Latest discards, so the fallback can load faster while returning the same item array and preserving access filters. Classify C1 and C2 as minor changes and re-check after merge.

Suggested line:
Validation tasks: changes #1246 C1; changes #1246 C2

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

…ibrary list

A browse of one library skips the GROUP BY so ORDER BY mil.first_seen_at
can walk idx_item_libraries_folder_seen_content and stop after a page.
Jellyfin library browses, Items/Latest included, also carry the viewer's
allowed libraries, which turned that off: the query joined, sorted and
grouped every row in the library to return 20. On 150,000 movies that
was about 0.7 s, and 2-3 s with an unplayed filter.

When the library is in the allowed list, the list adds nothing and is
dropped; when it is not, the browse returns nothing, as the two
conditions together already did.
The allowed list still limits the file-level predicates (audio and
subtitle languages), so a match only counts files the viewer can open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CoffeeKnyte
CoffeeKnyte force-pushed the perf/jellycompat-latest-no-total branch from 6ddbf9e to 59f0232 Compare October 27, 2026 00:44
@silo-triage silo-triage Bot added size/M 50–199 added + deleted lines (all files); change volume, not priority. and removed size/S 0–49 added + deleted lines (all files); change volume, not priority. labels Oct 27, 2026
@silo-kody

silo-kody Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@CoffeeKnyte CoffeeKnyte changed the title perf(jellycompat): stop counting the whole library for Items/Latest perf(jellycompat): make Items/Latest skip the library count and browse by index Oct 27, 2026
@coderabbitai coderabbitai Bot removed the go Pull requests that update go code label Oct 27, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 27, 2026

Copy link
Copy Markdown

Validation impact

The PR lists #1246 C1 but omits C2. The October 23 C2 run covered restricted-profile library lists and home rows; this PR changes those requests to the single-library query plan. The exact library predicate and out-of-allowlist empty result remain, so this is a minor change; please include C2 for a re-check after merge.

Suggested line:
Validation tasks: changes #1246 C1; changes #1246 C2

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104

Copy link
Copy Markdown
Contributor

Review summary (head 59f0232)

No defects found. The three changes do what the description says, and the browse change returns the same rows as before.

What I checked

  • Single-library scope. media_item_libraries has primary key (content_id, media_folder_id). A filter on one library therefore matches at most one row per item, so dropping the GROUP BY leaves rows, counts, and the added-at value (MIN(first_seen_at) of one row) unchanged. A library outside the allowed list, or an empty allowed list, still returns nothing. Person joins keep their grouping. Disabled-library exclusion and the file-level language filters still use the allowed list.
  • Latest totals. HandleLatest reads only the items. Paging takes HasMore from the extra row it fetches, and browseConfiguredUserState picks the same page with or without a total.
  • Limit=0. countOnly is set only by an explicit Limit=0. A request without a limit still gets the default page. Upstream Jellyfin applies Take(0) here, so [] matches it. The early return runs after the session and pseudo-user checks.
  • Tests. All three new tests fail on the merge base for the reason they name and pass on this head. The branch merges cleanly with current main, and internal/catalog and internal/jellycompat pass on the merged tree. I didn't run the Postgres-backed tests locally; CI's DB jobs are green.
  • Cross-provider review. Codex (gpt-6.1-sol, one round) found no defects. It also confirmed the C2 point below.

PR body edits

  • Native API browses never set both LibraryID and LibraryIDs: catalogBrowseFilters (internal/catalog/catalog_resolver.go) picks one or the other. Only jellycompat reaches the new path, so I removed the claims that the native API benefits.
  • The 2026-10-23 report on Compatibility layers (Jellyfin / Audiobookshelf) — Jellyfin compatibility #1246 also covers C2 (restricted-profile library lists and home rows), which the browse change reaches. The validation line now reads changes #1246 C1; changes #1246 C2.

Validated features: #1246 C1 and C2 (minor change, same results by construction). Both should be re-tested on the merged build.

User manual: unaffected. This changes query speed, not a setting or a visible behavior the manual describes.

Apple and Android: no client change needed. The change is server-side and keeps the Jellyfin wire responses the same.

Fit: 9/10 · Readiness: 9/10 — ready

  • Fit: a targeted speed fix on a common Jellyfin path. It adds no new surface and is placed where the cost comes from: the unused count at the compatibility boundary and the redundant scope check in the catalog planner.
  • Readiness: tests that fail on the base cover each change, result equivalence follows from the schema's primary key, and CI is green. The author's timings are on the evidence page; I didn't reproduce them.

AI disclosure: reviewed with Claude Code (claude-opus-5-5), with a Codex (gpt-6.1-sol) cross-provider round.

@Quick104
Quick104 merged commit 418af4a into main Oct 27, 2026
30 checks passed
@Quick104
Quick104 deleted the perf/jellycompat-latest-no-total branch October 27, 2026 13:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working impact: usability Core flow broken or severely blocked size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants