Skip to content

fix(catalog): use semi-joins for discovery library scope - #88

Merged
Quick104 merged 2 commits into
mainfrom
codex/discovery-library-scope-fix
Jun 8, 2026
Merged

Quick104 merged 2 commits into
mainfrom
codex/discovery-library-scope-fix

Conversation

@Quick104

@Quick104 Quick104 commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Qualify discovery SELECT projections with the mi alias so library-scoped discovery queries no longer hit ambiguous content_id references.
  • Replace direct media_item_libraries joins in discovery queries with the existing buildLibraryScopeJoin semi-join helper to avoid multi-library row fanout.
  • Keep empty allowed-library semantics, and make disabled-library filtering an item-level exclusion matching the rest of catalog access filtering.
  • Reuse the full provisional orphan predicate for late orphan collect/delete cleanup.

Supersedes #80.

Root Cause

The discovery queries for hidden gems, critically acclaimed, and forgotten favorites could join media_item_libraries for library-scoped viewers while selecting the unqualified itemColumns projection. Since both media_items and media_item_libraries expose content_id, PostgreSQL can reject those queries with SQLSTATE 42702.

The direct join form also fans out items that belong to multiple matching libraries, which can duplicate rows and interact badly with limits. The new shape keeps media_items mi as the only outer relation and scopes libraries with EXISTS / NOT EXISTS predicates.

Validation

  • go test ./internal/catalog -run 'Discovery|RatingThreshold|Unplayed|ForgottenFavorites|TestLateOrphanCleanupUsesProvisionalSafetyPredicate' -count=1
  • go test ./internal/catalog -count=1
  • git diff --check
  • Dev deployment validation on 100.86.116.20:
    • /api/v1/ready returned OK.
    • The old bad SQL shape reproduced ERROR: column reference "content_id" is ambiguous.
    • The fixed discovery query shapes executed successfully.
    • GET /api/v1/home/sections returned 200 for a restricted profile.
    • GET /api/v1/home/sections/127245166910046212/items returned 200 for hidden_gems.
    • Logs after the requests had no SQLSTATE 42702, no ambiguous content_id, and no affected discovery fetch errors.
    • Fanout check: old qualified join returned duplicate rows for some items; new EXISTS shape returned exactly one row per item.

AI Use

Implemented with Codex.

Summary by CodeRabbit

  • Refactor

    • Optimized discovery query performance and library access filtering logic.
    • Improved orphaned media item cleanup process.
  • Tests

    • Expanded test coverage for discovery features with enhanced validation.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 67d3f0aa-721d-4971-a654-47c8a884ac28

📥 Commits

Reviewing files that changed from the base of the PR and between ed8619c and 0df2b39.

📒 Files selected for processing (2)
  • internal/catalog/discovery_repo.go
  • internal/catalog/discovery_repo_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/catalog/discovery_repo.go

📝 Walkthrough

Walkthrough

This PR refactors discovery query construction to centralize SQL generation and library-scoping logic via helper functions that return empty strings when access rules exclude all libraries, updates all three discovery recipes (rating-threshold, unplayed-high-rated, forgotten-favorites) to use semi-join EXISTS patterns for library filtering, and replaces tests with shared assertion helpers. It also updates the WHERE-clause filter for orphaned provisional media items.

Changes

Discovery Query Centralization

Layer / File(s) Summary
Shared library scoping and test infrastructure
internal/catalog/discovery_repo.go, internal/catalog/discovery_repo_test.go
appendDiscoveryLibraryScope helper centralizes library-scoping logic: pinned LibraryID, semi-join EXISTS for allowed libraries, NOT EXISTS for disabled libraries, and explicit "exclude all" signal. Shared test assertion helpers validate qualified SELECT lists, prevent plain JOINs, and verify slice arguments.
Query builders with centralized SQL and library scoping
internal/catalog/discovery_repo.go
Three new helpers (buildRatingThresholdQuery, buildUnplayedHighRatedQuery, buildForgottenFavoritesQuery) construct SQL for each discovery recipe, apply the shared library-scoping helper, and return empty query strings when access rules exclude all libraries.
Public list methods refactored to use builders
internal/catalog/discovery_repo.go
ListByRatingThreshold and ListUnplayedHighRated delegate SQL/bind construction to their respective builder helpers and return empty slices when the helper returns empty strings. ListForgottenFavorites uses the same pattern within its builder's range.
Rating threshold query tests
internal/catalog/discovery_repo_test.go
Tests validate qualified SELECT lists, library scoping as EXISTS semi-joins for allowed libraries and NOT EXISTS for disabled libraries, absence of plain JOINs, and slice-based ANY($N) library-ID binding.
Unplayed high rated query tests
internal/catalog/discovery_repo_test.go
Tests validate qualified SELECT lists, omission of media_item_libraries scope when no filter is set, EXISTS semi-joins for allowed libraries, and correct parameterization of watch-history and content-rating filters.
Forgotten favorites query tests
internal/catalog/discovery_repo_test.go
Tests validate omission of media_item_libraries scope when no filter is set, EXISTS semi-joins for allowed libraries, and explicit default lookback behavior verification when LookbackDays is 0.
Consolidated cross-query discovery tests
internal/catalog/discovery_repo_test.go
New tests verify consistent content_id qualification, absence of plain library JOINs, and NOT EXISTS enforcement for disabled-library filtering across all three discovery query types.

Orphaned Provisional Media Items Condition

Layer / File(s) Summary
Condition update
internal/catalog/folder_repo.go
WHERE-clause filters in collectOrphanedProvisionalIDsByContentIDSQL and deleteOrphanedProvisionalIDsByContentIDSQL are updated to reference orphanedProvisionalMediaItemConditions instead of a prior condition set.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Silo-Server/silo-server#76: Modifies orphaned-item deletion logic in internal/catalog/folder_repo.go to align with provisional safety predicates.
  • Silo-Server/silo-server#72: Changes how catalog.AccessFilter is built (allowed vs. disabled library lists), which this PR consumes in appendDiscoveryLibraryScope to generate or exclude discovery SQL paths.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing direct joins with semi-joins for discovery library scope handling to fix ambiguous column references and prevent row duplication.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/discovery-library-scope-fix

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

@Quick104
Quick104 marked this pull request as ready for review June 8, 2026 13:09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed8619c844

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +291 to +294
whereSQL, scopeArgs, ok := buildLibraryScopeJoin(
filter.AllowedLibraryIDs,
filter.DisabledLibraryIDs,
*argIdx,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require membership for deny-only discovery filters

When a viewer has DisabledLibraryIDs but no allowlist, this new semi-join path calls buildLibraryScopeJoin(nil, disabled, ...), which emits only a NOT EXISTS against the disabled folders. That condition is true for media_items with no media_item_libraries rows, so orphan/stale rows can now appear in rating, unplayed, and forgotten-favorites discovery for users who merely disabled a library; the previous INNER JOIN shape excluded those rows, and ItemRepository.GetByIDsWithAccess explicitly preserves that positive-membership requirement for the same deny-only case.

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit 5393ee8 into main Jun 8, 2026
1 check passed
@Quick104
Quick104 deleted the codex/discovery-library-scope-fix branch June 8, 2026 13:33
Quick104 added a commit that referenced this pull request Jun 11, 2026
* fix(catalog): use semi-joins for discovery library scope

* fix(catalog): require membership for deny-only discovery
Quick104 added a commit that referenced this pull request Jun 17, 2026
* fix(catalog): use semi-joins for discovery library scope

* fix(catalog): require membership for deny-only discovery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant