Skip to content

fix(sections): fill unsorted collection rows from the members a viewer can open - #3500

Merged
Quick104 merged 2 commits into
mainfrom
fix/sections-unsorted-collection-access
Nov 4, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/sections-unsorted-collection-access

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #3384
Related issue: N/A
Validation tasks: changes #1140 C4; changes #1142 C3; changes Silo-Server/silo-apple#305 C3; changes Silo-Server/silo-apple#306 C3; changes Silo-Server/silo-android#315 C3; changes Silo-Server/silo-android#316 C3 (none run yet; all check restricted-profile rows)

A collection row on Home or a library page can show too few cards, or none, for a viewer with restricted access. This affects manual library collections with no default sort. The row took the collection's first item_limit members and only then removed the ones the viewer can't open, because they sit in a library the viewer can't access or above the profile's rating limit. If those first members were hidden, the row came back short or empty, even though the collection's own page listed the titles the viewer can open. Every client that renders the row sees this. With #2894, the v2 lists will drop an empty row entirely.

This change fills the row from the members the viewer can open, in collection order, up to item_limit, the same way sorted and smart collection rows already work.

Approach

The unsorted branch of fetchCollection (internal/sections/fetcher.go) now calls fetchItemsInListOrder. It is one statement that joins the member IDs, as unnest($1::text[]) WITH ORDINALITY, to media_items, applies the row's library scope and access filters, then orders by member position and applies LIMIT item_limit. The member list stays a single array parameter, so the statement has one shape at every collection size.

fetchItemsByContentIDsFiltered and the new read now build their scope and access conditions through a shared contentIDScopeConditions. The other callers send the same SQL as before. total_count keeps its existing meaning for unsorted rows: the number of cards the row shows.

docs/architecture/api-contract.md no longer names the unsorted collection as an example of a row that loses cards to filtering after the limit.

Validation

  • TestLibraryCollectionRailsMatchTheCollectionPageDB, which is already in db-pins.txt, has a new case. The collection's first two members are in a library the viewer can't open, and the row must match the collection page's first visible members. It fails on main (rail = []) and passes here.
  • All 77 DB pins and contracts for internal/sections, internal/api/handlers, internal/apiv2 and internal/jellycompat, run against a freshly migrated Postgres 18 with pgvector: pass.
  • go test ./internal/sections/, go vet, gofmt and make lint-changed: pass.
  • Not checked on a running deployment or a client.

Evidence

The fetcher output for the new test case: a row with item_limit 2 for a viewer who can open only the "shown" library. The collection is Aardvark and Zulu (hidden), then Delta, Bravo and Alpha (visible).

before: rail = []                total_count 0
after:  rail = [Delta, Bravo]    total_count 2

No client capture.

Risks

  • The old code looked up at most item_limit members. The new read walks the members in order until it has item_limit visible ones, and the whole list when most are hidden. On a test database, a 200,000-member collection whose only visible members were the last 20 took about 1 s. With every member visible it took 23 ms, and a 5,000-member collection took about 1 ms. Collection rows are cached per access scope and collection revision, so the cost is paid once per cache entry. The sorted branch already reads the whole member list.
  • Already on main and not changed here: ListItems orders members by position with NULLs last, while the collection page treats a NULL position as 0. A member with no position can sit in a different place on the row than on the page.
  • fix(home): leave rows with nothing to show out of the v2 section lists #2894 and fix(sections): cut curated lists to item_limit on capped aggregate reads #3419 also edit docs/architecture/api-contract.md. Whichever merges second may need a small rebase.

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
  • Tool(s): Claude Code (one subagent for the adversarial review)
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: An independent subagent reviewed the commit for SQL argument numbering, behaviour changes for the other content-ID readers, access leaks, total_count and cache-key semantics, large-collection cost, and whether the test proves the fix. It ran the new test against the parent commit and timed the statement on a test database. It found no correctness or access issue. It reported the large-collection cost (listed under Risks), a line-wrap nit in the doc edit (fixed), and the pre-existing NULL-position order difference (listed under Risks).

Note

Fix unsorted collection rails to fill rows from viewer-accessible members

  • Unsorted library collection rails now apply access and library-scope filtering to the full membership list before the item limit, so inaccessible members no longer consume slots
  • Adds fetchItemsInListOrder in fetcher.go, which joins an ordered content-ID list to media items and returns the first accessible matches in collection order
  • Adds a shared contentIDScopeConditions builder for type, library-scope, and access conditions, used by both the filtered content lookup and the new helper
  • Updates the DB test to cover manual collections with members split across libraries, asserting the rail matches the first visible cards on the collection page
  • Behavioral Change: unsorted rails can now return more cards than before when leading members are inaccessible; the rail total equals the number of returned cards. The legacy pre-fetch limit test is removed

Macroscope summarized e738448.

…r can open

An unsorted manual collection row took its first item_limit members and
only then applied the viewer's access filter, so a row whose first
members sit in libraries the viewer can't open came back with fewer
cards or none. Read the members in collection order with the access
filter applied before the limit, in one statement, as the sorted and
live collection rows already do.

Closes #3384
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 4, 2026
@silo-kody

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

@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Unsorted collection rails now filter inaccessible members before applying the item limit, preserve collection order, and report the number of visible items returned. A database test covers a manual collection with inaccessible initial members.

Changes: Collection rail filtering

Layer / File(s) Summary
Shared scoped ordered lookup
internal/sections/fetcher.go
The content-ID lookup now shares scope-condition construction with a new lookup that preserves list order and applies the item limit after filtering.
Rail integration and regression coverage
internal/sections/fetcher.go, internal/sections/collection_rail_db_test.go, internal/sections/collection_rail_fetch_test.go, docs/architecture/api-contract.md
Unsorted collection rails use the ordered lookup and report the number of visible items returned. A database test compares rail results with the collection page. The API contract and test descriptions are updated, and a legacy-bound test is removed.

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: quick104

Merge Risk: Minimal · up to e7384

The collection rail change is mergeable: inaccessible members are skipped before filling the limit, ordering is preserved, and no confirmed current-head regression remains.

Architecture risk: Low · up to e7384

The change affects 2 systems.

Changed systems: internal, docs

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — internal (service) was modified; 3 changed files map to changed impact.
  • observed — docs (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in docs/architecture/api-contract.md: The pagination description replaces the specific unsorted-collection/access-filter example with a general statement that applying a fetcher’s limit can cause cards to be missed. It retains the rule to send item_limit only when getHomeCapabilities reports row_item_limit_max as 100.
  • observed — Modified behavior in internal/sections/collection_rail_db_test.go: The test comment now includes manual collections with inaccessible initial members, rather than describing only smart collections and manual collections with a query definition.
  • observed — Modified behavior in internal/sections/collection_rail_db_test.go: Adds a database test for a manual collection containing members from accessible and inaccessible libraries. With the viewer limited to the shown library, the collection page returns the visible members in stored order; the rail matches its first two results and reports a total of two.
  • observed — Modified behavior in internal/sections/collection_rail_fetch_test.go: The models import and TestCollectionRailItemsToFetchPreservesLegacyBoundWithoutDefaultSort test, which checked the 24-item bound and unsorted result, were removed.
Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the main change: unsorted collection rows now fill from members the viewer can open. The changeset matches this. It adds an in-order fetch that applies access and library filters befor…
Description check Passed The description states the problem, the approach, validation, evidence, and risks. It names the unsorted collection row, the fetcher change, the shared contentIDScopeConditions builder, the new DB tes…
Linked Issues check Passed Issue #3384 requires unsorted manual collection rows to select viewer-accessible members in collection order before applying item_limit. The unsorted branch now uses fetchItemsInListOrder with shared …
Out of Scope Changes check Passed The fetcher change implements #3384. The database test verifies the required behavior. The removed legacy-bound test no longer matches the required behavior. The shared condition builder supports the …
Docstring Coverage Passed Docstring coverage is 100.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. Documentat…
Full details: Title check

Explanation

The title names the main change: unsorted collection rows now fill from members the viewer can open. The changeset matches this. It adds an in-order fetch that applies access and library filters before the limit in internal/sections/fetcher.go, and it updates the related test and API contract doc.

Full details: Description check

Explanation

The description states the problem, the approach, validation, evidence, and risks. It names the unsorted collection row, the fetcher change, the shared contentIDScopeConditions builder, the new DB test, and the doc edit. These all appear in the changeset summaries, so the description is on topic.

Full details: Linked Issues check

Explanation

Issue #3384 requires unsorted manual collection rows to select viewer-accessible members in collection order before applying item_limit. The unsorted branch now uses fetchItemsInListOrder with shared library-scope and access conditions. The database test covers inaccessible leading members, verifies collection-page order, and checks item_limit and total_count. The reported section tests and database pins also pass.

Full details: Out of Scope Changes check

Explanation

The fetcher change implements #3384. The database test verifies the required behavior. The removed legacy-bound test no longer matches the required behavior. The shared condition builder supports the new read, and the API contract edit removes obsolete documentation. No unrelated change is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.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 1 functions across 2 files.

Finishing Touches
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
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: c0f6d96e-bba1-4bff-9b37-2428424e51b9
Commits

Reviewing files that changed from the base of the PR and between 6a00ced and e738448.

Files selected for processing: 1
  • internal/sections/fetcher.go

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

@macroscopeapp

macroscopeapp Bot commented Nov 4, 2026

Copy link
Copy Markdown

Visible effect: internal/sections/fetcher.go now fills unsorted collection rows from later members the viewer can access, changing which cards appear. The before-and-after values are fetcher output, not evidence from a client surface or API response, and do not identify the surface or build/commit. Add before-and-after evidence for the same collection row showing its displayed item list, and name the surface and build/commit.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish labels Nov 4, 2026
// Filter before limiting, as the sorted and live branches do: limiting
// first let the access filter empty the row when the first members sit
// in libraries the viewer can't open.
items, err := f.fetchItemsInListOrder(ctx, contentIDs, s.ItemLimit, libraryID, libraryIDs, filter)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

Collection lookup sends an unbounded batch of IDs to PostgreSQL

Passing all of contentIDs to PostgreSQL can create an arbitrarily large query. Call f.fetchItemsInListOrder with bounded, ordered batches, applying the viewer filter until enough visible items are found or the collection is exhausted.

Kody rule violation: Batch scoped Go lookups and bound dependency fan-out

Prompt for LLM
File internal/sections/fetcher.go, line 1472:

Collection lookup sends an unbounded batch of IDs to PostgreSQL

Bound the database batch size instead of passing every collection member to one query. Process IDs in bounded, ordered batches, applying the viewer filter in each batch and continuing until the requested number of visible items is found or the collection is exhausted. This preserves collection order without sending an arbitrarily large array to PostgreSQL.

Kody rule violation: [Batch scoped Go lookups and bound dependency fan\-out](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/d2a64d9a-568c-46c2-9fa4-ad93c54ef90e?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

The member list is already loaded whole by ListItems before this call; the sorted branch sends that same full list to QueryCollectionItemsBySort. It goes to Postgres as one text[] bind, so the statement has one shape at any size. Measured on a test database: 200,000 members all visible, 23 ms; 5,000 members, about 1 ms. Only the worst case of 200,000 members with the visible ones at the end takes about 1 s. Rows are cached per access scope and collection revision. Batching in Go would add round trips to exactly that worst case and save a few milliseconds in the common one, so I am keeping the single statement. The PR Risks section records the cost.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That tradeoff is reasonable. I’ll withdraw the batching recommendation for this PR: the single array parameter keeps the query shape stable, and the measurements and cache behavior support avoiding additional round trips. The documented worst-case cost is worth monitoring.

One clarification: a single bind parameter bounds the number of parameters, not the array’s size or the database work. If very large collections become common, that resource cost may warrant revisiting.

Comment thread internal/sections/fetcher.go Outdated
Comment on lines 1465 to 1467
contentIDs := make([]string, 0, len(collectionItems))
for _, item := range collectionItems {
contentIDs = append(contentIDs, item.MediaItemID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance medium

Unsorted rows query and sort entire collection memberships

Large collections impose full-list database and sorting work on every uncached unsorted row fetch, even when the first item_limit entries are visible. Process collectionItems in bounded, ordered batches until the row fills.

Prompt for LLM
File internal/sections/fetcher.go, lines 1465-1467:

Unsorted rows query and sort entire collection memberships

Every uncached unsorted collection row now sends its entire membership to PostgreSQL and sorts the joined results even when the first `item_limit` entries are visible, replacing the previously bounded metadata lookup. Process members in bounded ordered batches until the row fills, so large collections do not impose full-list database work on every row fetch.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

The member list is already loaded whole by ListItems before this call; the sorted branch sends that same full list to QueryCollectionItemsBySort. It goes to Postgres as one text[] bind, so the statement has one shape at any size. Measured on a test database: 200,000 members all visible, 23 ms; 5,000 members, about 1 ms. Only the worst case of 200,000 members with the visible ones at the end takes about 1 s. Rows are cached per access scope and collection revision. Batching in Go would add round trips to exactly that worst case and save a few milliseconds in the common one, so I am keeping the single statement. The PR Risks section records the cost.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That tradeoff is reasonable given the measurements and caching. I withdraw the batching suggestion: the common-case savings do not clearly justify the extra round trips and complexity, especially when the worst-case cost is documented.

The single-array bind keeps the query shape stable, though it does not by itself bound database work. If large, heavily restricted collections are common in production, the uncached latency would be worth monitoring.

@macroscopeapp

macroscopeapp Bot commented Nov 4, 2026

Copy link
Copy Markdown

Major change: this changes the cards a restricted profile receives from an unsorted collection row: later accessible members now fill the row instead of hidden leading members consuming item_limit. The PR description should explain why those displayed results change; each affected case needs a post-merge validation run. The recorded Results cells for these cases are all Not run, so there is no prior result to invalidate or unblock.

The Validation tasks: line omits the native clients. iOS, tvOS, Android phone/tablet, and Android TV all consume the changed Home section response, and their C3 cases exercise restricted-profile rows. Suggested line:

Validation tasks: changes #1140 C4; changes #1142 C3; changes Silo-Server/silo-apple#305 C3; changes Silo-Server/silo-apple#306 C3; changes Silo-Server/silo-android#315 C3; changes Silo-Server/silo-android#316 C3 (all not run yet)

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

Posted via Macroscope — v1 validation impact

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nitpick comments: 1
internal/sections/collection_rail_db_test.go: 1

227-254: Trivial · Functional Correctness · Quick win

Add a rating-limited member case to the collection-rail DB test.

The current fixture does not set MaturityLimits or any content ratings. Add two shown-library members with content_rating_age above a PG-13 ceiling, set AllowUnratedContent: true, and assert that the collection page and rail skip those members and fill the two-card limit from later members. This protects the explicitly requested rating-limit behavior, which the current library-access case does not cover.

Suggested fix
 import (
+	"github.com/Silo-Server/silo-server/internal/access"
 	"context"
@@
 	t.Run("manual collection whose first members are hidden", func(t *testing.T) {
@@
 	})
+
+	t.Run("manual collection whose first members exceed the rating limit", func(t *testing.T) {
+		ratedAardvark := movie("Rated Aardvark", 2025, shown)
+		ratedZulu := movie("Rated Zulu", 2001, shown)
+		exec(`UPDATE media_items
+			SET content_rating = 'R', content_rating_age = 17
+			WHERE content_id = ANY($1)`, []string{ratedAardvark, ratedZulu})
+
+		manual := create(catalog.CreateLibraryCollectionInput{
+			LibraryIDs:     []int{shown},
+			Title:          "Rating limited",
+			CollectionType: "manual",
+		})
+		if err := repo.ReplaceItems(ctx, manual.ID, []catalog.LibraryCollectionItemInput{
+			{MediaItemID: ratedAardvark, Position: 0},
+			{MediaItemID: ratedZulu, Position: 1},
+			{MediaItemID: delta, Position: 2},
+			{MediaItemID: bravo, Position: 3},
+			{MediaItemID: alpha, Position: 4},
+		}); err != nil {
+			t.Fatalf("store items: %v", err)
+		}
+
+		ratingViewer := catalog.AccessFilter{
+			AllowedLibraryIDs: []int{shown},
+			MaturityLimits: access.MaturityLimits{
+				MaxContentRating:   "PG-13",
+				AllowUnratedContent: true,
+			},
+		}
+		page := collectionPage(manual.ID, ratingViewer)
+		assertContentIDs(t, "collection page", page, delta, bravo, alpha)
+		got, total := rail(manual.ID, nil, ratingViewer)
+		assertContentIDs(t, "rail", got, page[:2]...)
+		if total != 2 {
+			t.Fatalf("rail total = %d, want 2 cards", total)
+		}
+	})
 }
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: 931565cf-abdb-4b1a-96e8-f8daa4e5e89e
Commits

Reviewing files that changed from the base of the PR and between 6aa6791 and 6a00ced.

Files selected for processing: 4
  • docs/architecture/api-contract.md
  • internal/sections/collection_rail_db_test.go
  • internal/sections/collection_rail_fetch_test.go
  • internal/sections/fetcher.go
Files with no reviewable changes: 1
  • internal/sections/collection_rail_fetch_test.go

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

@silo-kody

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

@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Re the CodeRabbit nitpick about a rating-limited case: I am not adding it. The new read gets its rating and library conditions from the same contentIDScopeConditions → catalog.ApplySectionAccessFilter path every other section read uses, and the maturity filter is tested where it lives. The case this PR changes, filtering before the limit, does not depend on which access condition hides a member, and the library-access case already covers it. Per CONTRIBUTING "Decide what to test", each behavior gets one test.

Validation tasks line now lists the iOS, tvOS, Android, and Android TV C3 cases, as Macroscope suggested.

@Quick104
Quick104 merged commit e3af98b into main Nov 4, 2026
30 checks passed
@Quick104
Quick104 deleted the fix/sections-unsorted-collection-access branch November 4, 2026 14:57
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: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish 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.

[bug] Unsorted collection rows come back empty when their first members are hidden from the viewer

2 participants