Skip to content

perf(notifications): read a profile's progress items in one query during interest rebuild - #4384

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

Quick104 merged 1 commit into
mainfrom
perf/interest-rebuild-one-query

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte 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 interest rebuild still slows down with the square of a profile's watch progress. #4378 made the rebuild read completed history in one call. It still reads watch progress 500 rows at a time, and each page sorts the profile's entire progress set again. A profile filled by a history import can hold hundreds of thousands of progress rows; one with 300,000 takes about 90 seconds of database time per rebuild, which runs at every server start and daily at 04:30.

This change reads the profile's progress items in one query.

Approach

  • New UserStore.ListProgressItemIDs (internal/userstore/store.go:131) returns the media item of every row the full ListProgress listing returns, unordered and without the per-row fields. rebuildProfileInterest only collected those IDs (internal/notifications/system.go:716).
  • Both stores build the new query and their existing progress listings from one shared scope clause, progressVisibleFrom (internal/userstore/pgstore/progress.go, internal/userdb/progress.go), so the hidden-history rule cannot drift between them.
  • The progress keyset conformance suite now also runs on Postgres as TestPostgresProgressPage, listed in scripts/ci/db-contracts.txt. It checks the new listing against the full listing, with a second profile on the same account whose progress must not appear.

This overlaps #2888 only in rebuildProfileInterest. #2888 keeps this progress loop, so a rebase of it takes this side of the conflict.

Validation

  • Go: build, gofmt, go mod tidy -diff, vet, make lint-changed and make lint-router-recovery pass. make test-go (with umask 022) passes except internal/metadata/nfo TestProvider_DirectoryListingFollowsChanges, which fails locally on every run; this branch does not change that package or anything it imports.
  • Database: against a fresh migrated PostgreSQL 18 database, the userstore, userdb and notifications tests pass, including the new TestPostgresProgressPage. 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: playback fixtures, route inventory, API v2 OpenAPI, contract and fixtures checks, the router artifact test, settings bindings (Go side), local paths, case collisions, size ratchet, bidi and migrations pass. The web half of verify-settings-bindings-all and verify-apiv2-web-types could not run (no pnpm locally); no web or settings file changed. The web gate, verify-actionlint, verify-shellcheck and verify-prometheus-rules were not run; this change touches none of their inputs.

Evidence

Synthetic data on a scratch PostgreSQL 18 (pgvector image) database at this branch's migrations: one profile with 300,000 progress rows (100,000 in progress, 200,000 completed), 500 of them hidden from history after their last write, and a second profile on the same account with 20,000 rows. A PL/pgSQL block ran the old page loop and the new query server-side and compared the item sets. Three runs:

Path Old New Same item set
Whole profile (rebuild) 600 pages, 89.2 to 89.9 s 1 query, 152 to 165 ms yes, 299,500 items

On a real deployment, the largest profile has about 302,000 progress rows, and the same one-query read of its visible progress items took 144 ms.

Server-side plans (EXPLAIN ANALYZE, trimmed)

Old, one page at OFFSET 150000 (each of the 600 pages sorts the whole progress set):

Limit (actual rows=500.00 loops=1)
  ->  Gather Merge (actual rows=150500.00 loops=1)
        ->  Sort (actual rows=50932.00 loops=3)
              Sort Key: user_watch_progress.updated_at DESC
              Sort Method: external merge  Disk: 4280kB
              ->  Hash Anti Join (actual rows=99833.33 loops=3)
                    ->  Parallel Seq Scan on user_watch_progress (actual rows=100000.00 loops=3)
Execution Time: 103.497 ms

New, the whole profile:

Hash Anti Join (actual rows=299500.00 loops=1)
  ->  Seq Scan on user_watch_progress (actual rows=300000.00 loops=1)
  ->  Hash (actual rows=500.00 loops=1)
        ->  Seq Scan on user_history_hidden_items hhi (actual rows=500.00 loops=1)
Execution Time: 79.550 ms

Risks

  • The rebuild now holds one profile's progress item IDs in memory at once instead of 500 at a time. At 300,000 items that is roughly 20 MB, and the rebuild already builds a map of the same IDs.
  • UserStore gains a method. Both implementations add it; test fakes that embed the interface are unaffected.

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
  • Tool(s): Claude Code, including one subagent
  • Model(s): claude-opus-5-5, claude-fable-5-2 (review subagent)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: a separate Claude Code subagent on claude-fable-5-2 reviewed the diff for result-set equivalence with the old paging (on SQLite and Postgres, including hidden and rewatched items), unchanged text and placeholders of the existing progress queries, every UserStore implementer, cancellation and row handling, large-profile plans, lint and the tests. It found no defects; nothing changed.

Note

Add ListProgressItemIDs to userstore.UserStore and use it for interest rebuild

  • Replaces the paginated ListProgress loop in notifications.System.rebuildProfileInterest with a single ListProgressItemIDs call that fetches all visible progress media item IDs in one query
  • Implements the new method for both SQLite and Postgres backends, with shared progressVisibleFrom SQL fragments in each store to reuse the profile scope and hidden-history exclusion
  • Extends the shared progress conformance suite to check the new listing's result and profile scoping, and adds a Postgres conformance test gated on SILO_TEST_DATABASE_URL
  • Risk: ListProgressItemIDs is now on the UserStore interface, so any out-of-tree implementations must add it

Macroscope summarized f58e994.

…ing interest rebuild

rebuildProfileInterest still found the items a profile has progress on by
paging ListProgress 500 rows at a time with OFFSET. Every page sorts the
profile's whole progress set again, so the rebuild grows with the square of
the row count. A profile filled by a history import can hold hundreds of
thousands of progress rows, and the rebuild runs at startup and daily.

ListProgressItemIDs returns the same items in one read: the full listing's
profile scope and hidden-history exclusion, without the sort or the per-row
fields the rebuild never used. Both stores build it and their listing select
from one shared clause, so the two cannot drift apart. The progress keyset
conformance suite now also runs on Postgres and checks the new listing
against the full listing and a second profile on the same account.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label 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

The progress-store interface and SQLite and Postgres implementations now expose visible progress item IDs. Profile-interest rebuilding uses this lookup instead of paginated progress listing. Tests cover completed items and profile isolation.

Changes: Progress item ID lookup

Layer / File(s) Summary
Store contract, lookup, and conformance checks
internal/userstore/store.go, internal/userdb/progress.go, internal/userdb/sqlitestore.go, internal/userstore/pgstore/progress.go, internal/userstore/storetest/suite.go, internal/userstore/pgstore/conformance_test.go, scripts/ci/db-contracts.txt
The store interface and SQLite and Postgres implementations add a lookup for visible progress item IDs. The shared query filter excludes items hidden by the history watermark. Conformance checks cover completed items and exclude an item from another profile.
Profile-interest integration
internal/notifications/system.go
rebuildProfileInterest uses the ID lookup and adds each returned ID to its item set, replacing the paginated progress listing.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: quick104, rhainland

Merge Risk: Minimal · up to f58e9

This change replaces a slow paged scan with a single query when rebuilding profile interest, which the author measured at about 150 ms versus about 90 seconds for 300,000 rows. Visibility rules are shared with the existing listing, and tests cover completed items and profile isolation. Merge risk is minimal.

Security architecture risk: Minimal · up to f58e9

The optimization preserves existing account, profile, and hidden-history restrictions. No introduced or worsened security, ownership, or recovery risk was identified in the inspected change.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — One Postgres lookup is restricted to the store-bound account and supplied profile; SQLite restricts the query to the supplied profile within its per-user database. The outer rebuild already processes multiple accounts and profiles, but that job-wide authority is not newly granted by this lookup.

Trust Boundaries and Controls

  • observed — The changed caller uses profile IDs returned by server-side store enumeration. SQL parameters preserve account and profile identity rather than interpolating those values. Downstream recomputation still resolves profile access scope and filters series-library memberships before writing interest rows.

Resilience and Maintainability Implications

  • observed — A progress-read failure returns before interest mutation. Existing recovery behavior remains: a dedicated advisory-lock session coordinates full rebuilds, checkpoints advance per profile, and recomputation upserts rows before deleting stale rows while preserving the fanout-owned notification cursor. This is not an atomic whole-profile replacement; logged series failures and checkpoint advancement are pre-existing behavior, not introduced by the new lookup.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the interest rebuild now reads a profile's progress items in one query. It also gives the scope (notifications, perf type) and matches the PR summary and objectives. I…
Description check Passed The description explains the problem (quadratic slowdown from paged progress reads in the interest rebuild), the approach (new ListProgressItemIDs on both stores with shared visibility scope), the con…
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.
Full details: Title check

Explanation

The title names the main change: the interest rebuild now reads a profile's progress items in one query. It also gives the scope (notifications, perf type) and matches the PR summary and objectives. It is specific and concise.

Full details: Description check

Explanation

The description explains the problem (quadratic slowdown from paged progress reads in the interest rebuild), the approach (new ListProgressItemIDs on both stores with shared visibility scope), the conformance test, validation steps, and synthetic benchmark evidence. It is directly related to the changeset.

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: 440fef5a-9fc6-47a3-9f2b-7b8a34196659
Commits

Reviewing files that changed from the base of the PR and between abd85d0 and f58e994.

Files selected for processing: 8

  • internal/notifications/system.go
  • internal/userdb/progress.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/conformance_test.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
  • scripts/ci/db-contracts.txt

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

@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 bug Something isn't working impact: perf Unusable slowness on normal hardware labels Nov 16, 2026
@CoffeeKnyte
CoffeeKnyte marked this pull request as ready for review November 16, 2026 05:08
@Quick104

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: f58e994

I found nothing to fix. The new query returns the same items as the old paged loop, and the rebuild no longer re-sorts the whole progress set for every page.

What I checked

  • Same result set. Both ListProgressItemIDs queries reuse the scope clause that ListProgress already uses (profile scope plus the hidden-history exclusion). progressStatusPredicate("") adds nothing to that clause, so the new query is the full listing minus ORDER BY/LIMIT/OFFSET. The primary key (user_id, profile_id, media_item_id) rules out duplicates.
  • Existing listings. The progressListSelect text that ListProgress, ListProgressPage and the completed-since listing build on is unchanged after the split.
  • Implementers. The only stores are the SQLite and Postgres ones, and both add the method. interestTrackingStore embeds the interface, so the new read passes straight through to the store it wraps. That's correct because it's a read.
  • Measurement. I seeded a scratch Postgres database at this head and called the real store methods: one profile with 300,000 progress rows (500 of them hidden from history), plus a second profile on the same account with 20,000 rows. The old 500-row offset loop took 55.3 s. ListProgressItemIDs took 97 ms. Both returned the same 299,500 items, and neither included any of the second profile's rows.
  • Tests. TestPostgresProgressPage passes against that database, and ./internal/userdb and ./internal/notifications pass. The new conformance check calls a method this PR adds, so it can't run on main. It guards the new listing against drift, while the measurement above covers the behavior. CI is green.

Validated features: I couldn't check the board automatically. Going by the code, #1234 C1 (new-episode notifications) reads the interest rows this rebuild writes. The set of items that feed those rows is unchanged, so I agree with the PR's Validation tasks: line.

User manual: unaffected (internal performance change, no setting or visible behavior).

Other clients / jellycompat: N/A. No API or client-visible change.

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

  • Fit: this fixes a real slowdown for large libraries in a job that runs at every start and every day, without adding any setting or API surface. The fix lives in the store layer, and the shared scope clause stops the hidden-history rule from drifting between listings.
  • Readiness: I found no correctness concern, and I measured the speedup and the result-set match independently at this head.

🤖 Claude Code (claude-opus-5-5)

@Quick104
Quick104 merged commit 17d5376 into main Nov 16, 2026
18 checks passed
@Quick104
Quick104 deleted the perf/interest-rebuild-one-query branch November 16, 2026 14:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working impact: perf Unusable slowness on normal hardware 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