Repository navigation
perf(collections): speed up collection lists and collection pages - #1993
Conversation
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]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configuration
You can disable this status message by setting the Use the checkbox below for a quick retry:
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 |
There was a problem hiding this comment.
💡 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)) }() |
There was a problem hiding this comment.
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 👍 / 👎.
|
Re-check #193 S2 and S4 after merge before carrying forward their build-specific results. S2 exercises smart-collection 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 |
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/collectionsspent 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:
UNION ALLstatement. Postgres evaluates those counts one after another, so the list waited for their sum.(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.MIN(first_seen_at) … GROUP BY content_idover every row in the library on every page (~460 ms).COALESCE(release_date, <parsed first_air_date>), which no index can serve, so it scanned the whole type.jit_above_cost, and JIT compilation took ~90–120 ms of a query that runs in ~20 ms.Approach
pgx.QueryExecModeCacheDescribe, so each execution is planned for its bound values. Catalog search already does this (searchPlanArgs).media_item_librariesrow. The executor's library scope already requires membership in that library,(content_id, media_folder_id)is the primary key, andfirst_seen_atisNOT NULL. So the join drops no rows and yields the same value as the aggregate, andidx_item_libraries_folder_seen_contentcan supply the order. Episode scope already used this pattern. Multi-library sorts keep the aggregate.((release_date IS NOT NULL AND cmp) OR (release_date IS NULL AND first_air_date cmp)). That is the same value as theCOALESCEform for every combination of NULLs, and the existingrelease_dateindexes can serve the first branch.SET LOCAL jit = off, asrecent_tv.goalready does. A pool-widejit=offwas 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_secondsmetric. A library scan was running during both runs.GET /api/v2/collections(7 smart, 2 imported)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
gofmt,go vet: clean.make lint-changed(baseorigin/feat/collections-revamp): 0 issues.make test-go: passes exceptTestRunStatsWithRealFFmpegininternal/mediasample, which this change does not touch and which depends on the local ffmpeg build.make test-db-pinson a freshly migrated database: all 108 pins pass, including the playable-target and personal-collection query-budget pins.internal/catalogDB suite: passes exceptTestLibraryCollectionContinuationDBandTestOrphanCleanupAfterPlexTableDropPostgres, which fail the same way on the base commit.betweenandgt) 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.Risks
SET LOCALstatement per call.Checklist
AI Disclosure
gtcase 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
CountPersonalCollectionsnow 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.first_seen_atinstead of using the multi-library minimum aggregate subquery in query_builder.go.release_datewhen present and fall back to a validated, trimmedfirst_air_dateonly whenrelease_dateis null; malformed or blank values never match.queryPlayableTargetshelper.episodeParentCompletion,ListCompletedHistoryItems) pass arguments through a newprofilePlanArgshelper that sets pgx cache-describe execution mode.COALESCEonfirst_air_date, so rows with malformed or blankfirst_air_dateand norelease_dateare now excluded from date-rule matches. Count failures now report only definitions that fail twice instead of the whole batch.Macroscope summarized bbdda9d.