Repository navigation
perf(collections): stop personal collection lists from scanning every member - #2619
Conversation
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:
|
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Count memo and revision checks internal/catalog/personal_collection_read_memo.go, internal/catalog/personal_collection_read_memo_test.go |
A bounded memo reuses counts when the viewer, collection, access, membership revision, and five-minute expiry match. Unit tests cover cache hits, invalidation, expiry, and capacity behavior. |
API v2 list count wiring internal/api/handlers/collections.go, internal/api/handlers/library_collections.go, internal/api/router.go, internal/api/handlers/collections_item_counts.go, internal/api/handlers/collections_service.go, internal/api/handlers/library_views_service.go, docs/collections-api.md |
The router provides the optional count service to collection and library handlers. Native API v2 list reads use it; other reads retain live counts. The API documentation describes the caching behavior. |
Empty collage-source memo internal/catalog/personal_collection_collages.go, internal/catalog/personal_collection_read_memo_db_test.go, internal/catalog/personal_collection_read_memo_test.go, scripts/ci/db-contracts.txt |
Poster lookup remembers empty source results when membership revisions are available. Database-backed tests cover count and collage behavior, and the CI contract list includes the database test. |
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Refactor
Sequence Diagram(s)
sequenceDiagram
participant Viewer
participant NativeAPIv2ListRoute
participant collectionViewsCounted
participant PersonalCollectionMemberCounts
participant Database
Viewer->>NativeAPIv2ListRoute: Request collection list
NativeAPIv2ListRoute->>collectionViewsCounted: Render list with read-specific counts
collectionViewsCounted->>PersonalCollectionMemberCounts: Count visible collection members
PersonalCollectionMemberCounts->>Database: Load membership revisions and count cache misses
Database-->>PersonalCollectionMemberCounts: Return revisions and counts
PersonalCollectionMemberCounts-->>collectionViewsCounted: Return member counts
collectionViewsCounted-->>Viewer: Return collection list
Possibly related PRs
- Silo-Server/silo-server#2728: Establishes bounded personal-collection count paths that this change extends with memoization.
- Silo-Server/silo-server#2621: Defines the membership ordering used by this change for personal collage source lookup.
- Silo-Server/silo-server#2615: Defines collection revision behavior used to invalidate cached counts and empty collage results.
Suggested reviewers: quick104
Merge Risk: 
Minimal · up to af621
-
The change appears mergeable after normal checks. Native API v2 collection lists may show catalog-only changes up to five minutes later, as documented.
Security architecture risk: 
Low · up to af621
-
The reviewed changes preserve existing viewer and creator access checks and keep single-collection reads live. Catalog-only changes may remain visible in list summaries for up to five minutes. No newly introduced access bypass was identified, but production recovery behavior was not verified.
Retained concerns
No architecture-level concerns identified.Security review details
-
Security Blast Radius
- inferred — The changed path affects collection summary responses and empty-collage lookup suppression. Reuse is separated by account, collection, and effective viewer access, limiting the observed stale-data effect to previously computed summaries within that scope rather than establishing cross-account or cross-profile cache sharing.
Trust Boundaries and Controls
- observed — The existing creator-access boundary remains before memo lookup: another creator's collection uses intersected viewer and creator library and maturity restrictions. Creator lookup failures mark collections unavailable, and rendering drops them rather than using viewer-only access. Count and collage cache misses retain account and visibility predicates.
Resilience and Maintainability Implications
- inferred — Concurrent mutation or an older read completing late can populate an older-revision entry, but subsequent reads observing the advanced revision reject it. Query failures do not populate count entries or empty-source markers. This contains cache-state failures without changing the authority of the underlying visibility query; database failover freshness remains unverified.
-
Pre-merge checks: 
5
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 10 functions across 10 files. (2 skipped: 2 unsupported.)
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
|
The Evidence section says there is no user-visible change, but these list responses can now retain catalog-derived values for up to five minutes:
Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
|
The five-minute delay changes what clients can show: after a catalog-only change, collection counts or missing artwork can stay stale while a single-collection read is already current. That makes Please add before-and-after captures of the affected collection count/artwork with the same data, identify the builds, and show the cached result refreshing after a catalog-only change. Include phone-width web captures if that surface is affected, or explain why it is not. The benchmark tables cover latency, but not this visible behavior change. |
|
Major validation impact — #193 S2: The recorded result is build 1012 ( #193 S7 and #195 W7 remain blocked by #1615. Both use the affected collection-list count path, but this change does not resolve the sharing/owner model. The Web cards also render Replace the Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
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:
|
Quick104
left a comment
There was a problem hiding this comment.
Review of 8ecb33a. The memo's invalidation holds up: every write that changes membership, order, definition or sharing bumps user_collection_revisions through the triggers, deletes leave a tombstone, and the access key covers the intersected viewer and creator access. The COALESCE order matches the expression index. Three findings below. I'm fixing all three in commits on this branch, so there's no need to change anything yourself. The branch also conflicts with main (a struct field next to #2559's ArtworkSigner), so I'll rebase it.
8ecb33a to
67d9993
Compare
Maintainer review summaryReviewed head: af62105, rebased onto main 01cb809 and rewritten with a lease on 67d9993. The only conflict was the new test's entry in The memo's invalidation holds up. The triggers bump Addressed
Left for the maintainers
TestsThe new DB test exercises types this PR adds, so it can't run on the base. Unit tests for ValidationThe recorded passed cases of #193 (S1, S2, S3, S5) don't change any catalog data, so none of them observes the delay. The PR's Related work#2615 (list sync writes only membership changes) and #2621 (curated collection order from the membership index) touch none of these files. #2615 stops no-op syncs from bumping a collection's revision, which helps this memo keep its entries, so the order of merging doesn't matter. User manual and clientsThe user manual's collections page doesn't describe how fresh counts or collages are, so it needs no change. There are no API shape changes, so the Apple and Android apps need nothing. Adversarial reviewA second review by a different model (gpt-6.1-sol) found the Fit: 8/10 · Readiness: 8/10, conditional (assuming CI is green) Fit: it removes a cost that grows with library size from a read every client makes on launch, and checking every read against the shared revision keeps the cache safe in a cluster. The bounded staleness for catalog-only changes is a deliberate trade the maintainers should accept explicitly. Readiness: the code and tests are sound. Nobody in this review checked the timing on a live server; that evidence comes from the author's benchmark and evidence page. 🤖 Claude Code (claude-opus-5-5) |
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:
|
Collection lists counted every member and scanned for collage posters on every read. Remember a hand-picked or imported collection's viewer count and an empty collage lookup per membership revision and viewer access for up to five minutes, and order the collage lookup by the continuation index so it stops at the first titles with a poster. Single-collection reads still count live, since their ETag binds the count.
When a full memo's expiry sweep freed even one slot, put skipped the trim, so the memo refilled at once and the next new key swept all 50,000 entries again under the lock. Trim to nine tenths whenever the sweep leaves the memo above that, and move the eviction into its own method.
The frozen /api/v1 list routes share the handlers with /api/v2, so they picked up the count memo and could return an item_count up to five minutes old. Use the memo only on /api/v2 reads, as collages already do. When the revision read fails, count every collection without the memo instead of dropping all counts. Main dropped the waitForStoredCollage helper the DB test used, so the catalog test package no longer compiled. Wait on the generator composing the collage instead, and list the test in db-contracts.txt so CI runs it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
67d9993 to
af62105
Compare
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:
|
Problem
Related issue: N/A
Validation tasks: changes #193 S2; changes #193 S7 (blocked by #1615); changes #195 W7 (blocked by #1615)
Every time the web app loads, it lists the profile's personal collections. Each list read counted every member of every collection and scanned every member for collage posters. Read cost grew with total membership, not with the number of collections. On a profile with 24 collections and 87,400 members,
listCollectionstook about 180 ms, and the library tab'slistLibraryUserCollectionstook about the same. This change makes those reads cost about the same whatever the collection sizes.Two statements did the work:
CountVisiblePersonalCollectionMembers): about 60 ms per call.upci.position, which no index serves, so Postgres read and sorted every member even when the first titles had posters.Approach
user_collection_revisionsrevision on every read, and expires after five minutes. A change to members, order or definition, or to the viewer's or creator's access, shows on the next read. A catalog change alone, such as a title leaving a library, a new rating or new artwork, reaches a list within five minutes.docs/collections-api.mdnow says so./api/v2list reads use the memo. The frozen/api/v1list routes share the same handlers but keep counting live.getCollection,updateCollectionand the other single-collection responses still count live, because their strong ETag bindsitem_count(seedocs/architecture/api-contract.md). Only the list reads use the memo.COALESCE(upci.position, 0), media_item_id, which matchesuser_collection_items_continuation_idx.positionisNOT NULL, so the order is unchanged and the scan stops at the first titles with a poster. The same memo remembers when a collection has no title with a poster, so that case no longer rescans on every read.Out of scope: the library Collections tab (
getLibraryCollections) gets most of its cost from admin (server) collections, not personal ones. There,ListByLibraryruns an unfilteredCOUNT(DISTINCT)(about 80 ms), and the server collage lookup still scans every member when no title has a poster (about 50 ms). The Jellyfin BoxSet list uses the same code, so those belong with that work.Validation
internal/catalog,internal/api/handlers,internal/usercollectionsandinternal/api, with DB tests against a migrated Postgres: pass. New DB tests cover memo hits, recounts after a membership change, a separate entry per access, and the remembered no-collage result and its rebuild after a membership change. Unit tests cover expiry and the size bound.go build,gofmt,go vet,make lint-changedandmake lint-router-recovery: clean.make test-go(no database, as CI runs it): passes except three playback tests the branch does not touch. Two jellycompat Dolby Vision tests fail the same way onmainon this machine.TestHandleStartPlaybackV3DoesNotWaitForSessionSynchits its 1 s deadline under load and passes when run alone.make test-db-pinson a fresh migrated database: all 267 pins pass.make test-db-contracts: one recommendations contract failed in the batch run and passes when run alone, on this branch and onmain.TestPersonalCollectionReadsRememberedDBis now listed inscripts/ci/db-contracts.txtand passes on a freshly migrated Postgres, alone and through thedbpinsrunner with the existing collection and collage pins.getCollectionshows the live count.Benchmark: 12,000 synthetic movies, 24 personal collections (200 to 10,000 titles, 87,400 members), warm reads, concurrency 1, 10 s per path
p50 latency per request (ms), same dataset and machine, server restarted before each run:
GET /api/v2/collectionsGET /api/v2/collections?contains_item=…GET /api/v2/library/1/user-collectionsGET /api/v2/library/1/collections(admin collections, unchanged)pg_stat_statements, mean time per call:The test machine was shared with other work, so absolute numbers are noisy. The before-to-after ratios held across repeated runs.
Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-2619/
Surface: web app Collections page, Shared with me row, signed in as a PG-13 profile, at desktop and phone width, plus the list and single-collection API reads. Main (df107b7) and this branch (8ecb33a) ran the same steps on the same seeded data: open the list, re-rate one member R, attach posters to the first four members of a collection without a collage, then open the list again after 30 seconds and after five minutes. At 30 seconds main shows the new count (8 to 7) and the collage. This branch still shows 8 and no collage, while
getCollectionalready returns 7. After five minutes it matches main. Phone width shows the same cards and counts.Risks
/api/v2list'sitem_countand its "no collage" result can stay old for up to five minutes on each node. Examples: a title removed from a library, a rating crossing a profile's ceiling, or posters arriving after an import. Membership, definition and access changes are not delayed, and single-collection reads always count live.Checklist
AI Disclosure
Note
Add per-viewer member-count and no-source collages memo for personal collection lists
Stops personal collection list reads from scanning every member on each request. Adds a
catalog.PersonalCollectionMemberCountsservice in personal_collection_read_memo.go that remembers visible member counts per viewer, collection, and access key, validated against the collection's membership revision with a five-minute expiry./api/v2list routes use the memo; other API versions and single-collection reads still count live. Wired through collections_item_counts.go, collections_service.go, and library_views_service.go.Macroscope summarized af62105.