Skip to content

fix(collections): count server collections per viewer and hide ones it can't open - #2835

Merged
Quick104 merged 2 commits into
mainfrom
fix/issue-2828-server-collection-viewer-counts
Oct 21, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/issue-2828-server-collection-viewer-counts

Conversation

@Quick104

@Quick104 Quick104 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2828
Related issue: N/A
Validation tasks: changes #193 S1, S3, S4, S6; touches #193 S2 (expected to still pass); #193 S7 not run (blocked by #1615)

Server collections showed every profile the same item count, and listed a collection to a profile even when that profile could open none of its titles. A child profile with a rating limit could see a collection such as "Saw Collection, 9 titles" that opened empty. A profile limited to one library saw counts that included titles from libraries hidden from it. Only the member list was filtered per profile.

Now a profile whose access narrows the catalog sees the number of titles it can open, and a collection whose titles are all hidden from it is not listed. Unrestricted profiles and admins see what they saw before.

Approach

catalog gains LibraryCollectionRepository.ViewerCollectionCounts, which counts each server collection's members the way the collection's catalog page lists them for the viewer: library access, disabled libraries, rating and advisory-age limits, excluded media types, and no manga chapters. Curated and synced collections share one grouped statement. Smart collections resolve their membership as the catalog page does (collection libraries, viewer scope, item limit) and run through the batched, concurrent count runner that personal collections already used, now shared. A smart collection's cached count can be an hour old, so when the viewer can open none of its matches, it is counted again without the viewer's access to decide whether it has any. For a viewer whose access narrows nothing it returns nothing and costs nothing, so the stored counts stand.

catalog.CollectionsShownToViewer applies the counts. For a restricted viewer it leaves out a collection that has members but none the viewer can open, and one whose count could not be read. It never falls back to the stored count, since that number is what leaks. A collection that is empty for everyone stays listed with 0, as #193 S4 requires.

Surfaces:

  • Library Collections tab and server collections (/api/v1 and /api/v2 share these handlers). Server collections now count each collection once per request, even when it spans several libraries, and filter before the per-library cap, so total_count matches what the viewer is shown. Posters are still built only for the capped cards.
  • Jellyfin BoxSets: list, collections containing an item, Ids= lookups, /Items/{id} detail, and session-authorized collection images, which now return 404 for a hidden collection. Jellyfin sessions always exclude audiobooks and podcasts, so they count per viewer for admins too.
  • Admin collection routes and the editor are unchanged.

/api/v1 is frozen, so this is recorded as a critical bridge fix in docs/architecture/v1-scope.md. The response shape is unchanged; only the values narrow for restricted profiles. docs/architecture/collection-posters.md documents the counting rule.

No client change is needed. The apps already render item_count and the listed collections.

Validation

  • Reproduced with a Postgres-backed test through the real handlers. On base 64e7fec a PG-13 profile limited to one library got every server collection with its stored count: a collection of only 17-rated titles listed with 2, a mixed collection with 3 instead of 1, a smart collection with 4 instead of 2. The test also covers a chapter-only collection, a smart collection whose cache predates its matches, one whose cache predates it matching nothing, and an unreadable rule. It passes on this branch. The unrestricted case passes on both. Not reproduced on a live deployment: the dev sandbox host had no capacity to create one.
  • A statement-budget pin: counting 15 server collections costs no statements for an unrestricted viewer, at most 5 for a rating-limited one, and at most 9 when every member is hidden.
  • A jellycompat test covers listing, Ids=, detail and the poster image for a hidden collection.
  • make test-go: all packages pass except internal/mediasample TestRunStatsWithRealFFmpeg, which fails the same way on base with the local FFmpeg build. go vet, make lint-changed, lint-router-recovery and the route-inventory, API v2 OpenAPI/contract/fixtures, local-path, case-collision, size-ratchet and bidi checks pass. The two new database tests are listed in scripts/ci/db-contracts.txt and scripts/ci/db-pins.txt.

Evidence

Test runs before and after, with the seeded collections. No live captures; see Validation.

Evidence: https://evidence.siloserver.org/r/silo-server/admin-collection-viewer-counts/

Risks

  • Restricted profiles now see fewer server collections and smaller counts. This deliberately changes the server-list results recorded under Collections — Server #193 S1, S3, S4 and S6, which need a re-test after merge:
    • S1: a library-limited user's server collections no longer always match the admin's. A collection that spans a hidden library and has no titles the user can open is left out, and counts include only titles the user can open.
    • S4: the admin smart collection whose members were all TV-MA is no longer listed for the PG profile. Reading its members directly still returns an empty list, and a rule that matches nothing for everyone still leaves the collection listed for every profile, so the S4 criterion still holds.
    • S3 and S6: a restricted viewer's server lists can hold fewer cards and smaller totals. Member reads, mutations, direct item and stream checks, stored order and poster resolution are unchanged.
  • S2 (personal counts) is unchanged; it shares only the extracted count runner.
  • Fails closed: if a restricted viewer's count can't be read (a database error, or a saved smart rule that no longer resolves), those collections are left out for that request and the failure is logged. Unrestricted viewers are unaffected.
  • Restricted listings, and every Jellyfin BoxSet listing, run one grouped statement plus up to four concurrent smart-count statements, and up to four more when smart collections have nothing the viewer can open.
  • Conflicts with fix(collections): bound count queries and retain recovery access #2728, which adds count availability to the same files. Whichever lands second has to carry availability alongside the viewer count and keep hiding unavailable counts from restricted viewers.

Follow-ups:

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 says there is none.

AI Disclosure

  • Harness: Claude Code, in T3 Code
  • Tool(s): Claude Code, T3 Code orchestration, Codex (plan review)
  • Model(s): claude-opus-5-5 (implementation), gpt-6.1-sol (plan review)
  • Involvement: Fully AI-generated, not yet human verified
  • Adversarial review: a Codex gpt-6.1-sol round on the plan before implementation. It found that a failed count fell back to the global count, that server collections were counted once per library, and that Jellyfin BoxSet detail kept the global count. All three were fixed as described above. Its concern that this changes Collections — Server #193 S4 does not apply, because collections that are empty for everyone stay listed. A background adversarial review of fe4c7ab (gpt-6.1-sol) posted three findings: a stale smart cache still decided visibility, the Jellyfin image route skipped the decision, and the curated count included manga chapters that the catalog page leaves out. All three are fixed in bd294cd, with test cases that failed on fe4c7ab.

🤖 Generated with Claude Code

Note

Fix server collections to use per-viewer counts and hide unreadable ones

  • Restricted viewers now get live counts of members they can access, instead of stored collection counts. Smart collections are counted live, and manga chapters are excluded from counts
  • Collections whose members are all hidden, or whose counts cannot be read, are omitted from responses. Collections empty for everyone stay listed
  • Unrestricted viewers keep the prior stored counts and collection set
  • Applies to GET /api/v1/collections/server, the library Collections tab, and the Jellyfin BoxSet endpoints (list, detail, ID lookup, Included-In, and collection images) via the new collectionsForViewer helper
  • Core logic lives in ViewerCollectionCounts in library_collection_counts.go, with shared batching from runCollectionCountStatements (4 concurrent statements, batch size 32)
  • Risk: behavioral change for restricted profiles — collections with unreadable counts or all-hidden members disappear from lists and Jellyfin returns 404 for their BoxSet detail; check CollectionsShownToViewer and ViewerCollectionCounts for the exact omission rules

Macroscope summarized bd294cd.

…t can't open

Server collections listed every profile the unfiltered member count, and a
profile saw a collection even when its limits hid every member. A
rating-limited profile could read a collection's name and size and open an
empty page.

Profiles whose access narrows the catalog now see the members they can open
on the library Collections tab, server collections, and Jellyfin BoxSets. A
collection with members the profile can open none of, or whose count could
not be read, is left out. A collection empty for everyone stays listed, and
unrestricted profiles and the admin routes keep the stored counts.

Closes #2828

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 21, 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 the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Oct 21, 2026
@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 01364db9-7cdc-44bc-b85a-746dceb473bc
📥 Commits

Reviewing files that changed from the base of the PR and between fe4c7ab and bd294cd.

📒 Files selected for processing: 8
  • docs/architecture/collection-posters.md
  • internal/api/handlers/library_collections.go
  • internal/api/handlers/server_collection_counts_db_test.go
  • internal/catalog/library_collection_counts.go
  • internal/catalog/library_collection_counts_db_test.go
  • internal/jellycompat/handlers_collections.go
  • internal/jellycompat/handlers_collections_test.go
  • internal/jellycompat/handlers_images.go
🚧 Files skipped from review as they are similar to previous changes: 1
  • docs/architecture/collection-posters.md

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

📝 Walkthrough

Collection counts now reflect the titles each viewer can access. Inaccessible or unreadable collections are omitted. Empty collections remain listed. The behavior applies to library tabs, server listings, and Jellyfin BoxSets.

Changes: Viewer-specific collection visibility

Layer / File(s) Summary
Calculate viewer-visible collection counts
internal/catalog/library_collection_counts.go, internal/catalog/personal_collection_counts.go, internal/catalog/library_collection_counts_db_test.go, scripts/ci/db-pins.txt
Catalog counting applies viewer access filters to stored and smart collections. Shared batching uses four concurrent statements and batches of 32 definitions. Database tests verify counts and statement budgets.
Filter library and server collection responses
internal/api/handlers/library_collections.go, internal/api/handlers/library_views_service.go, internal/api/handlers/server_collections.go, internal/api/handlers/server_collection_counts_db_test.go, scripts/ci/db-contracts.txt, docs/architecture/*
Library tabs and server listings apply viewer-specific counts and visibility. Integration tests cover restricted and unrestricted results. Architecture records describe the response behavior.
Filter Jellyfin BoxSet responses
internal/jellycompat/handlers_collections.go, internal/jellycompat/handlers_collections_test.go, internal/jellycompat/handlers_images.go
Collection hydration, listing, detail, item-inclusion, and image visibility checks filter collections for the viewer. Detail requests return 404 NotFound when no collection remains visible.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant ListServerCollections
  participant LibraryCollectionRepository
  participant PostgreSQL
  participant CollectionsShownToViewer
  ListServerCollections->>LibraryCollectionRepository: Request counts with access filter
  LibraryCollectionRepository->>PostgreSQL: Count accessible collection members
  PostgreSQL-->>LibraryCollectionRepository: Viewer-specific counts
  LibraryCollectionRepository-->>ListServerCollections: Counts and count errors
  ListServerCollections->>CollectionsShownToViewer: Filter collections and apply counts
  CollectionsShownToViewer-->>ListServerCollections: Visible collections
Loading

Possibly related issues

Suggested reviewers: rhainland

Merge Risk: ⚪ Minimal · up to bd294

No actionable merge-blocking risk was established for the viewer-specific collection changes.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 10 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely summarizes the main change: per-viewer collection counts and hiding collections that the viewer cannot open.
Linked Issues check Passed The changes meet the coding requirements in #2828. ViewerCollectionCounts applies viewer library, disabled-library, rating, advisory-age, media-type, and manga-chapter rules. `CollectionsShownToView…
Out of Scope Changes check Passed The changes stay within #2828. The shared count-runner refactor supports the required server and personal collection counting. The architecture documents describe the implemented API and counting rule…
Description check Passed The pull request description directly explains the viewer-specific collection counts, visibility filtering, affected endpoints, tests, risks, and documentation changes summarized in the changeset.
Full details: Linked Issues check

Explanation

The changes meet the coding requirements in #2828. ViewerCollectionCounts applies viewer library, disabled-library, rating, advisory-age, media-type, and manga-chapter rules. CollectionsShownToViewer updates restricted counts, hides fully inaccessible or unreadable collections, and retains globally empty collections with count 0. The behavior applies to library and server collection endpoints and Jellyfin BoxSet listing, lookup, detail, Included-In, and image paths. Unrestricted viewers, admins, and the admin editor retain the prior behavior. The added PostgreSQL, statement-budget, and Jellyfin tests cover the required cases.

Full details: Out of Scope Changes check

Explanation

The changes stay within #2828. The shared count-runner refactor supports the required server and personal collection counting. The architecture documents describe the implemented API and counting rules. The tests verify the requested behavior. No unrelated product behavior or admin editor changes are identified.

Full details: Docstring Coverage

Explanation

Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 10 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: security Auth, privacy, or permission boundary priority: P1 Core-path bug; painful workaround — next after P0 labels Oct 21, 2026

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adversarial review (gpt-6.1-sol, reviewed fe4c7ab)

AI disclosure: Reviewed with the Codex harness in T3 Code, model gpt-6.1-sol.

… and chapters

A smart collection's cached count can be an hour old, so it no longer decides
whether a restricted viewer's zero means "every member hidden" or "empty for
everyone": those collections are counted again without the viewer's access.
Curated counts leave out manga chapters, as the catalog page the card opens
does. The Jellyfin image route now applies the same visibility decision as
BoxSet listing and detail, so a hidden collection's artwork and title poster
are not served to the session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

@macroscopeapp

macroscopeapp Bot commented Oct 21, 2026

Copy link
Copy Markdown

The diff changes the server/library list responses used by #193 S1, S4, and S6: restricted viewers now see different counts and may lose all-hidden or unreadable cards, and smart counts add a live query that gates visibility. The PR must explain why these previously validated outcomes change; S1, S4, and S6 need re-validation after merge. #193 S3's member reads, add/mutation checks, and direct item/stream checks use unchanged handlers, so its recorded result is not affected. The personal-count runner extraction does not change S2's behavior. S7 remains not run and blocked by #1615; this PR does not unblock it.

Suggested replacement:

-Validation tasks: changes #193 S3; touches #193 S2, S4, S7 (expected to still pass)
+Validation tasks: changes #193 S1, S4, S6; touches #193 S2; #193 S7 remains blocked by #1615

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@macroscopeapp

macroscopeapp Bot commented Oct 21, 2026

Copy link
Copy Markdown

Major re-validation required

The server collection lists now recalculate restricted-viewer counts and omit collections the viewer cannot open before applying the per-library cap. That changes the list data covered by earlier Server/API results. These are intentional changes, but the PR must keep explicit why the previously validated result changes; the current description states the rationale. Revalidate the affected cases after merge.

Case Impact
#193 S1 — build 927 · 66f6a52a The shared-collection list path now returns a different set/count for restricted profiles. Revalidate the access-scoped listing.
#193 S3 — build 927 · 66f6a52a A restricted viewer now gets no card for a collection with zero visible members; member and stream checks themselves are unchanged. Revalidate the list result.
#193 S4 — build 927 · 66f6a52a A smart collection with live members all hidden from a PG viewer is omitted; a collection empty for everyone remains listed. Revalidate this distinction.
#193 S6 — builds 927 · 66f6a52a and 941 · 82b5b39e Restricted card sets and totals change before the cap. Recheck the server-list observation; poster resolution and stored ordering are unchanged.

#193 S2 is a no-behavior-change touch: the personal count runner extraction preserves batching, concurrency, fallback, and count semantics. S7 remains Not run behind #1615; this PR does not change personal-collection sharing. The #1616 personal-order finding is outside this diff and is not newly unblocked. #1618 was already closed by pre-base commit e114d102; this PR does not newly unblock it.

Suggested replacement line:
Validation tasks: changes #193 S1, S3, S4, S6; touches #193 S2

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104
Quick104 merged commit 6bfc5ff into main Oct 21, 2026
22 checks passed
@Quick104
Quick104 deleted the fix/issue-2828-server-collection-viewer-counts branch October 21, 2026 16:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: security Auth, privacy, or permission boundary priority: P1 Core-path bug; painful workaround — next after P0 size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Server collections show full item counts, and appear at all, to profiles that can see none of their titles

1 participant