Repository navigation
perf(notifications): rebuild interest from grouped completed history - #4378
Merged
Merged
Conversation
The interest rebuild and the per-series recompute only need to know which media items have visible completed history. Both paged through ListCompletedHistory with LIMIT/OFFSET, and that query's watched_at/id ordering has no matching index, so Postgres sorted the profile's whole completed history again for every page. For profiles with long watch histories the rebuild's cost grew roughly with the square of the history size. Use ListCompletedHistoryItems instead: one row per media item, the same completed and hidden-history visibility rules, and an index-only scan on the completed-history index with no sort. The per-series recompute keeps its 500-ID chunks but no longer needs paging, since each chunk returns at most one row per requested ID. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis 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. |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Contributor
Merged
4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: none. #1234 C1 delivers new-episode notifications, which read the interest rows this rebuilds; the set of items that count as watched does not change.
Other clients: N/A (no client-visible change)
The notification interest rebuild takes time roughly proportional to the square of a profile's completed watch history, and it runs at every server start. To find the media items a profile has finished,
rebuildProfileInterestpages throughListCompletedHistory500 rows at a time withOFFSET. That query orders bywatched_at, idand filters oncompleted. On long histories the planner reads and sorts the profile's whole completed history again for every page, as the plan below shows. For profiles with long watch histories, such as ones filled by a history import, therebuild_release_interesttask (at startup and daily at 04:30) does that sort once per 500 rows.RecomputeSeriesrepeats the pattern for each 500-episode chunk.This change reads the set of watched items directly instead of walking history rows.
Approach
Both callers need only the set of media items with visible completed history.
ListCompletedHistoryItemsalready returns one row per item. It applies the samecompletedfilter and hidden-history rule asListCompletedHistoryand plans each profile's query for that profile's values (profilePlanArgs). In the synthetic run below, Postgres answered it with an index-only scan onidx_user_watch_history_profile_item_completedand no sort; the exact plan depends on table statistics and visibility-map state.rebuildProfileInterestmakes one call for the whole profile.RecomputeSerieskeeps its 500-episode chunks but drops the offset paging, since each chunk returns at most one row per requested ID.Neither caller used the per-row fields the grouped query drops (
watched_atper row, source, order). An emptyMediaItemIDsfilter means "all items" in both the Postgres and SQLite stores, and the notifications store decorator passes the call through. The otherListCompletedHistorycallers are unchanged.Validation
go mod tidy -diff, vet,make lint-changedandmake lint-router-recoverypass.make test-gopasses when run with umask 022 (the upload and backup tests reject group-writable temp directories), exceptinternal/mediasampleTestRunStatsWithRealFFmpegandinternal/playbackTestCopyRemuxSubtitleRenditionRealFFmpeg. Both fail the same way onmainwith the local ffmpeg 6.1.1, and neither package depends on notifications.notifications,userstoreanduserdbtests pass against a migrated PostgreSQL 18 database, including theRecomputeSeriesPostgres tests.make test-db-pinsreports no failures. Its only problems are backup tests that skip becausepg_dumpandpg_restoreare not installed locally.verify-actionlint,verify-shellcheckandverify-prometheus-ruleswere not run because the tools are not installed; no workflow, shell script or rule file changed. The web gate was not run; no web file changed.Evidence
Synthetic data on a scratch PostgreSQL 18 (pgvector image) database, commit
ae111cfa2f. One profile has 200,000 completed history rows over 20,000 items and 10,000 incomplete rows. 500 of its items are hidden entirely and 500 are hidden only before a cutoff, so later rewatches stay visible. A second profile on the same account adds 50,000 rows. A throwaway Go program called the Postgres user store both ways and compared the resulting item sets. Times are from three runs on a client on another machine, so every call includes a network round trip.Server-side plans (EXPLAIN ANALYZE, trimmed)
Old, one page at
OFFSET 150000(each of the 389 pages sorts the whole history):New, once per profile:
Risks
None identified. #2888 removes both of these history reads, so whichever of the two merges second resolves a small conflict at the same lines.
Checklist
AI Disclosure
TestCompactMediaItemIDsReturnsEmptySliceForNilInputalready pins the behavior that path depends on, so none was added. Its notes on overstated plan wording were applied to this description.🤖 Generated with Claude Code
Note
Replace paginated completed-history fetches with
ListCompletedHistoryItemsin notifications interest rebuildRebuilds profile interest from grouped completed history using a single
ListCompletedHistoryItemscall instead of paginating through completed-history entries.notifications.System.rebuildProfileInterestnow fetches all completed media-item IDs for the profile in one call and passes them tobatchResolveSeries(system.go).notifications.InterestUpdater.RecomputeSeriesnow makes oneListCompletedHistoryItemsrequest per episode-ID chunk, passing the returned item IDs tomarkCompleted(interest_updater.go).Macroscope summarized ae111cf.