Skip to content

perf(collections): speed up collection lists and collection pages - #1993

Merged
Quick104 merged 1 commit into
feat/collections-revampfrom
t3code/speed-up-collections-api
Oct 6, 2026
Merged

Quick104 merged 1 commit into
feat/collections-revampfrom
t3code/speed-up-collections-api

Conversation

@Quick104

@Quick104 Quick104 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #193 S2, S4 (same results from different SQL; re-check suggested)

The Collections page takes over a second to show its collections, and scrolling a collection waits on each next page. On a deployment with a large catalog, GET /api/v2/collections spent 1.2 s on the server for a profile with seven smart collections. Collection pages spent 300–600 ms per page. This change brings the collection list to about 130 ms and most collection pages under 100 ms, without changing what any request returns.

The time went to five queries:

  • Collection list. The list counted every smart collection in one UNION ALL statement. Postgres evaluates those counts one after another, so the list waited for their sum.
  • Watched state on series cards. Series completion and completed-history reads ran as cached prepared statements. After five runs Postgres switches them to a generic plan whose row estimate for (user_id, profile_id) is the average across profiles. For a profile with ~49k history rows, that plan reads every history row: 300–430 ms instead of 3 ms, and 70–90 ms instead of 0.2 ms.
  • Date-added sort in one library. The sort built MIN(first_seen_at) … GROUP BY content_id over every row in the library on every page (~460 ms).
  • Release-date rules. The rule compared COALESCE(release_date, <parsed first_air_date>), which no index can serve, so it scanned the whole type.
  • Playable targets. The planner's cost estimate for the playable-target query crosses jit_above_cost, and JIT compilation took ~90–120 ms of a query that runs in ~20 ms.

Approach

  • Smart collection counts run as up to four concurrent statements of up to 32 definitions each. Deduplication of identical definitions, per-batch failure isolation, and the no-cross-request-cache rule are unchanged.
  • The two profile-scoped user-state reads pass pgx.QueryExecModeCacheDescribe, so each execution is planned for its bound values. Catalog search already does this (searchPlanArgs).
  • A date-added sort scoped to exactly one library joins that library's media_item_libraries row. The executor's library scope already requires membership in that library, (content_id, media_folder_id) is the primary key, and first_seen_at is NOT NULL. So the join drops no rows and yields the same value as the aggregate, and idx_item_libraries_folder_seen_content can supply the order. Episode scope already used this pattern. Multi-library sorts keep the aggregate.
  • Release-date rules emit ((release_date IS NOT NULL AND cmp) OR (release_date IS NULL AND first_air_date cmp)). That is the same value as the COALESCE form for every combination of NULLs, and the existing release_date indexes can serve the first branch.
  • Both playable-target queries (general and Postgres-store) run in a read-only transaction with SET LOCAL jit = off, as recent_tv.go already does. A pool-wide jit=off was not used because a startup parameter or session setting does not survive transaction-mode connection poolers.
Server-side request time, old and new build on the same deployment (mean of 8 requests each)

From the server's streamapp_apiv2_request_duration_seconds metric. A library scan was running during both runs.

Request Before After
GET /api/v2/collections (7 smart, 2 imported) 1,246 ms 130 ms
Smart movies, release-date rule, one library: page 1 / next page 558 / 399 ms 93 / 54 ms
Smart movies, date-added sort, one library: page 1 / next page 608 / 574 ms 58 / 55 ms
Smart series, release-date rule: page 1 / next page 408 / 308 ms 246 / 148 ms
Smart series, date-added sort, one library: page 1 / next page 333 / 380 ms 267 / 237 ms
Imported list: page 1 / next page 104 / 90 ms 34 / 37 ms

Series collections remain the slowest. Their page query still sorts all matching series (~95–160 ms), because the keyset seek gives Postgres no range bound to start an index scan from. That needs a change to the shared cursor-seek SQL and is left for a follow-up.

Validation

  • Go build, gofmt, go vet: clean. make lint-changed (base origin/feat/collections-revamp): 0 issues.
  • make test-go: passes except TestRunStatsWithRealFFmpeg in internal/mediasample, which this change does not touch and which depends on the local ffmpeg build.
  • make test-db-pins on a freshly migrated database: all 108 pins pass, including the playable-target and personal-collection query-budget pins.
  • Full internal/catalog DB suite: passes except TestLibraryCollectionContinuationDB and TestOrphanCleanupAfterPlexTableDropPostgres, which fail the same way on the base commit.
  • New DB tests cover release-date matching (release date wins over first air date, malformed and blank first air dates, between and gt) and date-added paging across cursor pages for one and two libraries. Both pass on the old and new code. The count test also passes under -race.
  • Ran the new build on a shared development deployment and compared it with the old build there (table above).
  • Web and generated-contract checks were not run; the change has no web, API contract, route, or settings changes.

Risks

  • A collection-list request can hold up to four database connections while counting, up from one. With the default pool of 20 connections, about five concurrent list loads can fill the pool briefly.
  • Playable-target lookups now open a read-only transaction and run one extra SET LOCAL statement per call.
  • No migration, API, or client-visible change. jellycompat reads the same catalog executor and gets the same results.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code, GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; human review pending
  • Adversarial review: A separate Claude Code review agent (claude-opus-5-5) read the full diff and checked NULL handling of the release-date rewrite, every caller of the single-library sort for the membership guarantee, concurrency and cancellation in the count batches, transaction and nil-pool handling in the playable-target helper, and pgx handling of the exec-mode argument. It found no correctness regressions. It flagged connection-pool pressure (now listed under Risks) and thin coverage for release-date operators and races; the release-date test gained a gt case and the count test was run under -race.

🤖 Generated with Claude Code

Note

Speed up collection lists and pages with batched counts and faster query plans

  • CountPersonalCollections now runs count statements concurrently through a four-slot semaphore with batches of up to 32 definitions. A failed batch retries each definition individually and keeps successful counts.
  • Added_at sorting in single-library scopes orders directly by that library's first_seen_at instead of using the multi-library minimum aggregate subquery in query_builder.go.
  • Release-date rules now use release_date when present and fall back to a validated, trimmed first_air_date only when release_date is null; malformed or blank values never match.
  • Playable-target queries run in a read-only transaction with PostgreSQL JIT disabled via a shared queryPlayableTargets helper.
  • Profile-scoped user-store reads (episodeParentCompletion, ListCompletedHistoryItems) pass arguments through a new profilePlanArgs helper that sets pgx cache-describe execution mode.
  • Behavioral Change: release-date filtering no longer uses COALESCE on first_air_date, so rows with malformed or blank first_air_date and no release_date are now excluded from date-rule matches. Count failures now report only definitions that fail twice instead of the whole batch.

Macroscope summarized bbdda9d.

The collections list waited for every smart collection's count in one
statement, and collection pages spent most of their time in queries that
could not use an index or paid for query planning they did not need.

- Run personal collection counts as up to four concurrent batches.
- Plan series/season completion and completed-history reads per execution,
  so a profile with a long watch history no longer gets a generic plan that
  scans every history row.
- Sort added_at within a single library through a plain join on that
  library's row, which idx_item_libraries_folder_seen_content can order,
  instead of aggregating the whole library.
- Compare release_date rules per source column so the release_date indexes
  can serve them.
- Run playable-target queries with JIT off.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-05T22:36:06.034848Z bbdda9d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 646035d9-dbdd-4d94-8514-6cb702f367e6

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autopilot · 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bbdda9dc12

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if err != nil {
return err
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bound rollback cleanup after cancellation

If a playable-target request is canceled while PostgreSQL or its connection is stalled, context.WithoutCancel(ctx) removes both cancellation and the request deadline, so the deferred rollback can block the handler and retain the pool connection until a network-level timeout. The analogous JIT-disabled transaction in recent_tv.go bounds rollback with a one-second context; apply the same bounded cleanup here so failure or reconnect scenarios cannot indefinitely consume request and database resources.

AGENTS.md reference: AGENTS.md:L73-L75

Useful? React with 👍 / 👎.

@macroscopeapp

macroscopeapp Bot commented Oct 5, 2026

Copy link
Copy Markdown

Re-check #193 S2 and S4 after merge before carrying forward their build-specific results. S2 exercises smart-collection item_count, whose count batches now run concurrently; S4 exercises smart membership through the query builder, whose release-date predicate and one-library added_at sort now use different SQL. The PR says results are intended to be equivalent, but these paths postdate builds 1012 and 927. No blocked case is unblocked: #1615’s sharing model and #1616’s cross-profile ordering remain outside this diff. The sibling Web, Web admin, Apple, and Android Collections tasks have no recorded results.

Suggested fix: No diff; have a human re-run S2 and S4 on the merged build and append the evidence to #193.

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

Posted via Macroscope — v1 validation impact

@Quick104
Quick104 merged commit 53a7603 into feat/collections-revamp Oct 6, 2026
16 checks passed
@Quick104
Quick104 deleted the t3code/speed-up-collections-api branch October 6, 2026 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant