Skip to content

perf(notifications): rebuild interest from grouped completed history - #4378

Merged
Quick104 merged 1 commit into
mainfrom
perf/notifications-interest-rebuild
Nov 16, 2026
Merged

Quick104 merged 1 commit into
mainfrom
perf/notifications-interest-rebuild

Conversation

@Quick104

@Quick104 Quick104 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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, rebuildProfileInterest pages through ListCompletedHistory 500 rows at a time with OFFSET. That query orders by watched_at, id and filters on completed. 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, the rebuild_release_interest task (at startup and daily at 04:30) does that sort once per 500 rows. RecomputeSeries repeats 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. ListCompletedHistoryItems already returns one row per item. It applies the same completed filter and hidden-history rule as ListCompletedHistory and plans each profile's query for that profile's values (profilePlanArgs). In the synthetic run below, Postgres answered it with an index-only scan on idx_user_watch_history_profile_item_completed and no sort; the exact plan depends on table statistics and visibility-map state.

  • rebuildProfileInterest makes one call for the whole profile.
  • RecomputeSeries keeps 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_at per row, source, order). An empty MediaItemIDs filter means "all items" in both the Postgres and SQLite stores, and the notifications store decorator passes the call through. The other ListCompletedHistory callers are unchanged.

Validation

  • Go: build, gofmt, go mod tidy -diff, vet, make lint-changed and make lint-router-recovery pass. make test-go passes when run with umask 022 (the upload and backup tests reject group-writable temp directories), except internal/mediasample TestRunStatsWithRealFFmpeg and internal/playback TestCopyRemuxSubtitleRenditionRealFFmpeg. Both fail the same way on main with the local ffmpeg 6.1.1, and neither package depends on notifications.
  • Database: the notifications, userstore and userdb tests pass against a migrated PostgreSQL 18 database, including the RecomputeSeries Postgres tests. make test-db-pins reports no failures. Its only problems are backup tests that skip because pg_dump and pg_restore are not installed locally.
  • Contracts and hygiene: settings bindings, playback fixtures, route inventory, the API v2 OpenAPI, web types, contract and fixtures checks, the router artifact test, local paths, case collisions, size ratchet, bidi and migrations pass. verify-actionlint, verify-shellcheck and verify-prometheus-rules were 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.
  • No test added. The user-store suites cover the grouped query's visibility rules, and the callers only collect the returned IDs.

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.

Path Old New Same item set
Whole profile (rebuild) 389 pages, 67 to 71 s 1 call, 46 to 54 ms yes, 19,500 items
One 500-episode chunk (recompute) 2.2 s 6 to 7 ms yes, 250 items
Server-side plans (EXPLAIN ANALYZE, trimmed)

Old, one page at OFFSET 150000 (each of the 389 pages sorts the whole history):

Limit (actual time=103.741..111.383 rows=500.00 loops=1)
  ->  Gather Merge (rows=150500.00)
        ->  Sort (rows=50627.67 loops=3)
              Sort Key: h.watched_at, h.id
              Sort Method: external merge  Disk: 4048kB
              ->  Hash Anti Join (rows=64666.67 loops=3)
                    ->  Parallel Seq Scan on user_watch_history h
Execution Time: 112.503 ms

New, once per profile:

GroupAggregate (actual time=0.090..70.661 rows=19500.00 loops=1)
  ->  Merge Anti Join (rows=194000.00)
        ->  Index Only Scan using idx_user_watch_history_profile_item_completed on user_watch_history h
              Heap Fetches: 0
        ->  Index Scan using user_history_hidden_items_pkey on user_history_hidden_items hhi
Execution Time: 71.498 ms

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

  • 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 how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code, GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: a separate claude-fable-5-2 agent reviewed the diff read-only for parity with the old reads (completed filter, hidden-history rule, empty media-item filter meaning every item, wrapper stores), lost per-row data, plan and memory cost, and cancellation and checkpoint behavior. It found no defects. It asked for a test of the empty-filter path; the existing TestCompactMediaItemIDsReturnsEmptySliceForNilInput already 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 ListCompletedHistoryItems in notifications interest rebuild

Rebuilds profile interest from grouped completed history using a single ListCompletedHistoryItems call instead of paginating through completed-history entries.

  • notifications.System.rebuildProfileInterest now fetches all completed media-item IDs for the profile in one call and passes them to batchResolveSeries (system.go).
  • notifications.InterestUpdater.RecomputeSeries now makes one ListCompletedHistoryItems request per episode-ID chunk, passing the returned item IDs to markCompleted (interest_updater.go).
  • Behavioral Change: both paths return the same item IDs as before; only the query shape changes, so watch the chunk queries still filter by profile ID and media-item IDs.

Macroscope summarized ae111cf.

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]>
@silo-triage silo-triage Bot added the size/S 0–49 added + deleted lines (all files); change volume, not priority. label Nov 16, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T02:23:30.705214Z ae111cf PR opened
🔒 Security Review ✅ Completed 2026-11-16T02:24:43.728739Z ae111cf 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.

@silo-kody

silo-kody Bot commented Nov 16, 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 ❌

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

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Two notification-interest rebuild paths now use ListCompletedHistoryItems instead of paginating ListCompletedHistory. They retain wrapped errors and process the returned items for completion status or series resolution.

Changes: Notification Interest Rebuild

Layer / File(s) Summary
Replace paginated completed-history reads
internal/notifications/interest_updater.go, internal/notifications/system.go
RecomputeSeries loads completed history for each episode-ID chunk with ListCompletedHistoryItems and marks returned items as completed. rebuildProfileInterest uses the same method to retrieve profile history and adds returned media IDs to the series-resolution set. Both paths retain wrapped errors.

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

Change: Refactor

Suggested reviewers: rangodj, coffeeknyte

Merge Risk: Minimal · up to ae111

This change makes notification-interest rebuilds faster by querying distinct watched items in one call instead of paging through history rows. No behavior change is expected, and no concrete defect was found, so it looks safe to merge.

Security architecture risk: Minimal · up to ae111

The change reuses existing queries without expanding access or changing notification-interest ownership. Profile-wide reads now temporarily hold all distinct completed items, but the previous implementation already accumulated their IDs. No material security or failure-containment regression was established.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: notification interest rebuild now reads grouped completed history instead of paging history rows. The title uses the perf(notifications) prefix and matches the changes…
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 explains the problem (slow OFFSET paging of ListCompletedHistory during interest rebuild), the approach (one ListCompletedHistoryItems call per profile, and per-chunk calls in Recomput…
Full details: Title check

Explanation

The title names the main change: notification interest rebuild now reads grouped completed history instead of paging history rows. The title uses the perf(notifications) prefix and matches the changeset (ListCompletedHistoryItems replacing ListCompletedHistory paging in interest_updater.go and system.go). It is specific and concise.

Full details: Description check

Explanation

The description explains the problem (slow OFFSET paging of ListCompletedHistory during interest rebuild), the approach (one ListCompletedHistoryItems call per profile, and per-chunk calls in RecomputeSeries), the validation performed, and benchmark evidence. It is directly related to the changeset described in the raw summary and objectives, so it is not off-topic.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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: 9106dc9a-91a6-42b4-8d94-e5a631add853
Commits

Reviewing files that changed from the base of the PR and between 0cc3ec6 and ae111cf.

Files selected for processing: 2

  • internal/notifications/interest_updater.go
  • internal/notifications/system.go

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

@Quick104
Quick104 merged commit ffd7f94 into main Nov 16, 2026
18 checks passed
@Quick104
Quick104 deleted the perf/notifications-interest-rebuild branch November 16, 2026 02:43
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/S 0–49 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant