Skip to content

perf(sections): bind content ID lookups as one array - #2958

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/home-id-lookups-any-array
Oct 23, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/home-id-lookups-any-array

Conversation

@blurbery

@blurbery blurbery commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none. The changed lookups are reached by #1183 C1 and C2 and #1184 C2 (favourite and watchlist state on list and Home cards, per profile), #1252 C4 and C9 (Continue Watching and Next Up) and #1140 C4, none of which has a passed result on the board yet, and they return the same rows. #1184 C1 isn't reached: item detail reads favourite and watchlist state one item at a time, which this change doesn't touch.

Home rows look titles, episodes, favourites and watchlist entries up by content ID, and four of those lookups wrote the ID list as IN ($1, $2, ... $n) with one bind parameter per ID. Every list length is different SQL text. With pgx's default statement cache, each new length costs an extra Parse and Describe round trip and leaves another prepared statement on the connection, where they can push other hot queries out of the cache (pgx keeps 512 per connection by default). Card counts vary from render to render, so the lengths keep changing. ListProgressByMediaItems already avoids this for the same reason ("Keep one statement shape for every batch size").

A list also can't be longer than the 65,535 parameters Postgres binds. A personal collection rail with no default sort sends every member to the title lookup, and nothing caps a collection's size, so a collection with more than 65,535 members fails to load. I haven't seen one that large; the statement churn is the common cost.

This change binds each list as one text[] parameter and compares with = ANY, so each lookup is one statement whatever the length.

Approach

The four queries are fetchItemsByContentIDsFiltered and fetchEpisodeTargetsByContentIDs in the section fetcher, and ListFavoritesByMediaItems and ListWatchlistByMediaItems in the Postgres user store. The fetcher callers are Continue Watching, Next Up, the Watchlist and Favourites rows (up to 10,000 IDs) and personal collection rails, and the store lookups set the favourite and watchlist state on every card list. None of the queries ordered by the list; callers reorder the rows themselves. The library, access and profile filters are unchanged, and the lookups keep using their content ID indexes (checked with EXPLAIN on the prepared statements).

I left buildRecentlyAddedSingleLibraryQuery alone. Its list holds the viewer's library IDs, so its length only varies with the number of libraries.

The SQLite user store still builds IN lists for the same two lookups. This change doesn't touch it.

Validation

  • Database test, added to scripts/ci/db-pins.txt: the title and episode lookups run the same single statement for 2 and 70,002 IDs and return the requested movie and episode, not the second movie and episode in the same library. On main the 70,002-ID call fails with extended protocol limited to 65535 parameters.
  • Store conformance test, run against both the Postgres and SQLite stores: the favourites, watchlist and Not interested batch lookups report only the requested rows of the acting profile, and leave out its other rows, removed and unknown IDs, and another profile's rows. This replaces the Not interested lookup assertion that covered only that one list.
  • Locally on Postgres 18.6: go test for internal/sections, internal/userstore/pgstore and internal/userdb passes with SILO_TEST_DATABASE_URL set, and go vet passes on the changed packages.
  • CI on 355e08fa9 (run): every job passed: Repository checks, Go lint, Go test, Go integration, Go DB pins (which runs the new statement-shape test) and Go DB external auth. The web jobs were skipped because no web files changed.

Benchmarks

Baseline db95c13bd (upstream main), changed 355e08fa9. Local Postgres 18.6 on an Apple M5 Pro Mac, one pgx connection over localhost TCP with pgx's default statement cache. Data: 20,000 movies and 5,000 series in one library, and a profile with 6,667 favourites. Two runs per commit gave the same picture; the table shows the first.

200 calls with list lengths 1 to 200, once each, then the prepared statements left on the connection:

Lookup Before After
fetchItemsByContentIDs 108.9 ms, 200 statements 61.3 ms, 1 statement
ListFavoritesByMediaItems 32.7 ms, 200 statements 16.9 ms, 1 statement

Large lists, median of 9 lists of n to n+8 IDs: the first call with each length, then the same list again.

Lookup, IDs Before, new length After, new length Before, repeated After, repeated
items, ~100 0.58 ms 0.31 ms 0.41 ms 0.28 ms
items, ~1,000 3.22 ms 1.85 ms 3.04 ms 1.81 ms
items, ~5,000 9.37 ms 7.68 ms 8.48 ms 7.48 ms
items, ~10,000 15.62 ms 14.38 ms 13.53 ms 14.26 ms
favourites, ~100 0.22 ms 0.14 ms 0.16 ms 0.13 ms
favourites, ~1,000 0.86 ms 0.47 ms 0.71 ms 0.46 ms
favourites, ~5,000 2.92 ms 1.72 ms 1.86 ms 1.67 ms
favourites, ~10,000 4.91 ms 3.09 ms 3.33 ms 2.88 ms

One case is slower: around 10,000 IDs, repeating a length the connection had already prepared took about 0.5 ms longer with the array (13.5 to 13.9 ms before, 14.3 to 14.4 ms after, across both runs). Every other case was faster. Limitations: a local database with no network latency, so each avoided Parse and Describe round trip would save more on a real network; synthetic data; 9 samples per size. The harness was a temporary test file and is not part of the change.

Evidence

No screen shows anything different: the lookups return the same rows, which the tests above check. The one exception is a personal collection rail with more than 65,535 members, which failed before and now loads; I don't have a collection that large to capture.

Risks

None identified. The queries keep their filters, and each now has one prepared form instead of one per list length.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (Claude desktop app)
  • Tool(s): Claude Code, including its subagents
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: a separate Claude Code subagent with no part in writing the change reviewed the full diff for result parity (collation, index use, duplicates, ordering), bind-parameter numbering in the fetcher's filter helpers, profile and library scoping, missed lookups on the Home path, and the tests. It found no defects. It noted that the tests could not tell a lookup that ignored its ID list from a correct one, so both now seed rows that are not asked for.

Home rows looked titles, episodes, favourites and watchlist entries up
with an IN list holding one placeholder per ID. Every list length was new
SQL, so each one cost a Parse/Describe round trip and a prepared
statement on the connection, and a list longer than the 65,535
parameters Postgres binds failed. A personal collection rail without a
default sort sends every member, and nothing caps a collection's size.

The four lookups now bind the list as one text[] and compare with
= ANY, as ListProgressByMediaItems already does.
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@silo-kody

silo-kody Bot commented Oct 23, 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 23, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 34 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ 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: 649dc43b-7d1b-41b5-b1ea-8180fed35ed5
📥 Commits

Reviewing files that changed from the base of the PR and between 8c90021 and 355e08f.

📒 Files selected for processing: 5
  • internal/sections/content_id_lookup_db_test.go
  • internal/sections/fetcher.go
  • internal/userstore/pgstore/favorites.go
  • internal/userstore/storetest/suite.go
  • scripts/ci/db-pins.txt
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@silo-triage silo-triage Bot added go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

The Validation tasks: line includes #1184 C1, but that case exercises item-detail toggles. The detail path reads state through IsFavorite/InWatchlist and the toggle mutations; it does not call the changed batch lookups. #1184 C2 is the relevant list-card path. The changed batch and section queries retain the same profile, content-ID, and access predicates and preserve caller ordering, so I found no recorded result whose behavior changes. #1140 C4's zero-row omission is separate section-list filtering; this diff does not change that behavior, and the task's Results table has no validator result.

Suggested replacement: Validation tasks: none

I could not read the mobile validation tasks because GitHub denied access to silo-apple#305, #306, #324, #325, #337, #338 and silo-android#315, #316, #334, #335, #347, #348. I have not classified those cases.

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 355e08fa9)

I found no defects. Nothing needed fixing, so I pushed no commits.

What I checked

  • Bind numbering. Each fetcher query binds the array as $1 and starts argIdx at 2. Every helper that runs after it (applyConfigTypeFilter, buildLibraryScope, applyEpisodeTargetLibraryAccess, the access filters) numbers from argIdx. The favourites and watchlist queries bind $1–$3 to three arguments.
  • Results. All four columns are text (001_schema.sql), so = ANY($n::text[]) matches the same rows as the old IN list. Duplicate IDs behave the same, and callers reorder the rows themselves. An empty list still returns before any query runs, so pgx never receives a nil array.
  • Plans. I ran EXPLAIN against a migrated Postgres 18 database seeded with 50,000 titles. The forced generic plan for the title lookup probes media_items_pkey in a nested loop, and the custom plan uses a bitmap scan on the same index. The favourites lookup uses user_favorites_pkey with user_id, profile_id and media_item_id together. Nothing in the repo sets an exec mode or plan_cache_mode that would change this.
  • Tests. TestContentIDLookupsKeepOneStatementPostgres passes on this head. On the merge base it fails with extended protocol limited to 65535 parameters, so it detects the change. db-pins.txt is the right list for a statement-shape test. The reworked store conformance test passes on both the head and the base: it adds coverage but doesn't detect this change. It keeps the cases the removed Not interested assertion covered: your own row, another profile's row, and an unknown ID. go test passes for internal/sections, internal/userstore/pgstore and internal/userdb against Postgres.
  • Repository checks. make lint-changed, verify-size-ratchet, verify-bidi and verify-local-paths are clean against current main. The branch merges into main without conflicts.
  • Other feedback. There are no inline review threads. The bot's note about Watchlist / Favorites / Ratings — Web #1184 C1 is already reflected in the body.

Related open PRs. #2953 changes fetchAllWithRunner and the imports in internal/sections/fetcher.go. #2891 adds entries to scripts/ci/db-pins.txt. Neither collides with this branch textually, and #2894 shares no files. These PRs can merge in any order.

Validated features. No passed case on the 1.0 board is reached. #1183, #1184, #1252 and #1140 have no passed cases yet, so this PR's line is accurate context. Strictly, the line is Validation tasks: none.

User manual. Unaffected. Apple/Android. No API change, so neither app needs follow-up. jellycompat. It has no placeholder-built IN lists for these lookups.

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

  • Fit: this is a contained performance fix that follows the pattern ListProgressByMediaItems and the other Postgres batch lookups already use. It adds no new surface.
  • Readiness: I have no open concerns, and the new database test fails on the base.

@Quick104
Quick104 merged commit 5d593af into Silo-Server:main Oct 23, 2026
16 checks passed
@blurbery
blurbery deleted the perf/home-id-lookups-any-array branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish 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