Skip to content

feat(search): add TV episode search support - #397

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
Rhainland:fix/episode-search
Jul 23, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
Rhainland:fix/episode-search

Conversation

@Rhainland

@Rhainland Rhainland commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • search available TV episodes by title and overview in PostgreSQL and Meilisearch
  • rank mixed movie, series, and episode results before page hydration without copying episodes into media_items
  • keep Meilisearch episode documents vectorless, push library filtering into the provider, and recheck authorization during set-based hydration
  • add retry-safe episode indexes and statement-level outbox triggers for episode and library changes
  • preserve explicit All Media scope while the user continues typing in the search bar

Why

TV episodes live in episodes, but both catalog search providers only queried and indexed media_items. Searches such as Who Are You? for Silo S03E01 therefore returned no result. The web catalog also converted an explicit all-media selection back to movie-and-series scope during query changes.

Rollout

PostgreSQL support and concurrent indexes are deployed first. The Meilisearch schema version is bumped, so an old index safely falls back to PostgreSQL until the normal admin rebuild creates and atomically swaps the mixed catalog index. Explicit Meilisearch index_types settings must include episode or all.

Validation

  • go test ./internal/catalog
  • focused legacy route and database-backed episode/outbox tests
  • focused Meilisearch request, federation-classification, and mixed hydration tests
  • pnpm test search regressions pass; full frontend run has 1,259 passing tests and four unrelated existing harness failures (ResizeObserver and missing QueryClientProvider)
  • pnpm run lint (no errors; existing warnings only)
  • pnpm run format:check
  • pnpm run build
  • make migrate-validate
  • make verify-local-paths
  • full Go run passes all touched packages; unrelated existing failures remain in an auth DB fixture with a null email and an API-handler TempDir cleanup race

Part of #396

AI-use disclosure

Implemented and reviewed with Codex. The changes were validated with focused PostgreSQL, Meilisearch, API, and frontend regression tests plus repository build, formatting, migration, and path checks.

Summary by CodeRabbit

  • New Features
    • Added episode search support with mixed media-and-episode results, plus improved ranking for episode title and overview.
    • Improved Meilisearch indexing/search to support library_ids filtering and mixed federated semantic behavior.
  • Bug Fixes
    • Fixed legacy search handling to accept type=episode.
    • Refined search navigation so query submissions preserve selected filters and the “All Media” scope.
    • Tightened access-aware filtering to correctly apply allowed/disabled library permissions (including episode access).
  • Tests
    • Expanded unit/integration coverage for episode search, Meilisearch federated behavior, indexing triggers, and search URL behavior.

Add mixed PostgreSQL and Meilisearch episode search with access-safe hydration, incremental indexing, and regression coverage for explicit all-media searches.\n\nPart of Silo-Server#396
@Rhainland Rhainland changed the title feat(search): add scalable TV episode search feat(search): add TV episode search support Jul 13, 2026
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ff17ca78-9fa9-4453-954d-5f533a322962

📥 Commits

Reviewing files that changed from the base of the PR and between e487253 and 6da6cf7.

📒 Files selected for processing (5)
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_postgres_mixed.go
  • internal/catalog/search_provider_test.go

📝 Walkthrough

Walkthrough

Episode search support spans legacy routing, PostgreSQL mixed search, Meilisearch federation and filtering, indexing and database event capture, and catalog URL state handling.

Changes

Episode catalog search

Layer / File(s) Summary
PostgreSQL mixed search
internal/api/handlers/*, internal/catalog/item_repo*, internal/catalog/search_postgres_mixed.go
Legacy routing accepts type=episode; PostgreSQL search ranks media and episode candidates, applies episode library access checks, and hydrates mixed results.
Mixed search indexing and schema
internal/catalog/search_indexer.go, internal/catalog/search_provider.go
Indexed documents include library IDs, episode documents are loaded without vectors, and eligible-document counts include episodes.
Meilisearch episode and federated search
internal/catalog/search_meilisearch_*.go, internal/catalog/search_provider_test.go
Meilisearch adds episode access filters, federated mixed semantic queries, unsupported-federation fallback, and mixed-result hydration.
Episode indexes and catalog events
migrations/sql/*episode_search*.sql, internal/catalog/search_episode_db_test.go
Migrations add episode full-text indexes and gated triggers for search index upsert/delete events.
Catalog query URL state
web/src/components/SearchBar.*, web/src/pages/Catalog.tsx, web/src/pages/catalogSearchParams*
Catalog URL builders and SearchBar wiring preserve filters and type=all while updating query text.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Catalog
  participant SearchProvider
  participant Meilisearch
  participant ItemRepository
  Catalog->>SearchProvider: submit mixed media and episode query
  SearchProvider->>Meilisearch: send federated search with access filters
  Meilisearch-->>SearchProvider: return ranked content IDs
  SearchProvider->>ItemRepository: hydrate IDs with access checks
  ItemRepository-->>Catalog: return mixed search results
Loading

Possibly related issues

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% 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 clearly summarizes the main change: adding TV episode search support across the search stack.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@Rhainland
Rhainland marked this pull request as ready for review July 13, 2026 22:23
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 13, 2026

@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: 808883cf8f

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

settings := map[string]any{
"displayedAttributes": []string{"content_id", "type"},
"filterableAttributes": []string{"type"},
"filterableAttributes": []string{"type", "library_ids"},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Force a Meilisearch rebuild for the new document schema

Adding library_ids as a filterable/document field (and indexing episode documents) changes the on-index schema, but catalogSearchMeilisearchSchemaVersion still derives the same value for existing settings. In installs with an already-active Meilisearch index, the provider will accept the old index instead of forcing a rebuild, so unrestricted searches keep missing all pre-existing episodes and library-scoped searches can fall back/error because the served index was created without library_ids as a filterable attribute. Bump the schema identity/version when adding this field so existing indexes are marked stale and rebuilt.

Useful? React with 👍 / 👎.

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.

Confirmed this is already covered by the PR: SearchMeilisearchSchemaVersion is bumped from 2 to 3, and catalogSearchMeilisearchSchemaVersion includes that base as the million component of the derived identity. Existing v2 indexes therefore mismatch, search falls back to PostgreSQL, and incremental sync remains disabled until rebuild. The focused schema-version tests pass.

@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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/catalog/item_repo_test.go (1)

493-512: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Exercise the episode branch in the lean-CTE regression test.

The test claims to protect broad episode searches but only builds a movie-scoped query. Run the assertion for episode or unscoped search too.

Proposed adjustment
-	dataSQL, countSQL, _ := repo.buildSearchSQL("avatar", []string{"movie"}, 20, 0, AccessFilter{})
-
-	for _, sql := range []string{dataSQL, countSQL} {
+	for _, itemTypes := range [][]string{{"movie"}, {"episode"}, nil} {
+		dataSQL, countSQL, _ := repo.buildSearchSQL("avatar", itemTypes, 20, 0, AccessFilter{})
+		for _, sql := range []string{dataSQL, countSQL} {
 			// Existing assertions.
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/catalog/item_repo_test.go` around lines 493 - 512, The regression
test TestItemRepo_Search_ScoredCTEIsLean currently exercises only the movie
branch; update it to build and validate an episode-scoped or unscoped query as
well, while preserving the existing wide-column assertions for both dataSQL and
countSQL.
internal/catalog/search_meilisearch_provider.go (1)

102-104: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

federationUnsupported is cached forever with no expiry/reset.

Once a Meilisearch response is classified as federation-unsupported, markFederationUnsupported() sets the flag permanently for the process lifetime — there's no TTL or re-probe, unlike the neighboring capMu/capCache/capCachedAt semantic-capability cache which is explicitly "rate-limited" and re-checked. A one-off misclassification, transient error, or a live Meilisearch upgrade would permanently downgrade mixed episode+media searches to keyword-only until the process restarts.

Consider mirroring the existing capability-cache pattern (add a cached-at timestamp and re-probe after a TTL) so federation support can recover without a restart.

♻️ Suggested direction
 	federationMu          sync.Mutex
 	federationUnsupported bool
+	federationCheckedAt   time.Time
 }
@@
-func (p *MeilisearchSearchProvider) isFederationUnsupported() bool {
+func (p *MeilisearchSearchProvider) isFederationUnsupported() bool {
 	p.federationMu.Lock()
 	defer p.federationMu.Unlock()
+	if p.federationUnsupported && time.Since(p.federationCheckedAt) > federationRecheckInterval {
+		return false
+	}
 	return p.federationUnsupported
 }

Also applies to: 514-525

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/catalog/search_meilisearch_provider.go` around lines 102 - 104,
Update the federation capability state managed by markFederationUnsupported and
its callers to include a cached-at timestamp and TTL-based expiry, mirroring the
existing capMu/capCache/capCachedAt pattern. Re-probe Meilisearch after the TTL
instead of treating federationUnsupported as permanent, while preserving
synchronized access and resetting the unsupported state when a probe succeeds.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/catalog/search_postgres_mixed.go`:
- Around line 33-34: Update the episode hydration conditions near
appendEpisodeLibrarySearchAccess to always require the episode’s current library
membership, mirroring the unconditional availability predicate used in the
corresponding flow around line 128. Preserve the existing access-filter behavior
while preventing stale Meilisearch IDs from hydrating after all
episode_libraries rows are removed.

---

Nitpick comments:
In `@internal/catalog/item_repo_test.go`:
- Around line 493-512: The regression test TestItemRepo_Search_ScoredCTEIsLean
currently exercises only the movie branch; update it to build and validate an
episode-scoped or unscoped query as well, while preserving the existing
wide-column assertions for both dataSQL and countSQL.

In `@internal/catalog/search_meilisearch_provider.go`:
- Around line 102-104: Update the federation capability state managed by
markFederationUnsupported and its callers to include a cached-at timestamp and
TTL-based expiry, mirroring the existing capMu/capCache/capCachedAt pattern.
Re-probe Meilisearch after the TTL instead of treating federationUnsupported as
permanent, while preserving synchronized access and resetting the unsupported
state when a probe succeeds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ae6f19fe-0e5c-4ab4-b34e-e6041b5ef12d

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 808883c.

📒 Files selected for processing (19)
  • internal/api/handlers/legacy_read_routes.go
  • internal/api/handlers/legacy_read_routes_test.go
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/search_episode_db_test.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_meilisearch_client_test.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_postgres_mixed.go
  • internal/catalog/search_provider.go
  • internal/catalog/search_provider_test.go
  • migrations/sql/20260713233000_episode_search_indexes.sql
  • migrations/sql/20260713233100_episode_search_outbox_triggers.sql
  • web/src/components/SearchBar.test.tsx
  • web/src/components/SearchBar.tsx
  • web/src/pages/Catalog.tsx
  • web/src/pages/catalogSearchParams.test.ts
  • web/src/pages/catalogSearchParams.ts

Retry federated episode searches after the capability cache expires, clear the downgrade after a successful probe, and exercise lean ranking for episode and mixed catalog branches.
@Rhainland

Copy link
Copy Markdown
Contributor Author

Addressed the remaining CodeRabbit review follow-ups in e487253a:

  • Federation capability downgrades now expire after five minutes, permitting a re-probe after a Meilisearch upgrade or stale capability result. A successful federated request clears the cached downgrade.
  • TestItemRepo_Search_ScoredCTEIsLean now exercises movie-only, episode-only, and unscoped mixed searches for both data and count SQL.
  • The episode hydration membership suggestion was verified as already enforced inside episodeCatalogBaseRelation; I replied inline with the rendered relation path.
  • The schema-version suggestion was verified as already handled by the v2-to-v3 base bump; I replied inline with the derived identity behavior.

Validation:

  • focused federation and lean-CTE tests
  • full go test ./internal/catalog
  • focused tests with -race
  • git diff --check

Quick104 and others added 2 commits July 23, 2026 11:01
# Conflicts:
#	internal/catalog/item_repo.go
A userProvided Meilisearch embedder rejects any document that omits
_vectors entirely, failing the whole indexing task once episode documents
enter a rebuild batch. Episode docs now carry the documented
`_vectors.<embedder>: null` opt-out, and attachDocumentVectors runs the
per-document pass even for episode-only batches.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Pushed two commits to make this mergeable and fix a blocker found during dev validation (maintainer edit):

2e45a9c0 — merge of main. The conflict with #386's typo-tolerant fallback is semantic, not textual: SearchPage now routes through buildSearchSQLFromParsed, so the mixed builder was reworked to accept the parsed query (buildMixedSearchSQLFromParsed, using searchTextFromParsed) and qualifiedItemColumnRefs was restored (the fuzzy builder still needs it). Note: the trigram fuzzy fallback remains media-only — episodes get no typo tolerance yet (suggest a follow-up issue).

6da6cf7a — fix(search): opt episode documents out of embedder vectors explicitly. With semantic search enabled (userProvided embedder), Meilisearch rejects any document that omits _vectors entirely — the first rebuild batch containing episodes fails with "no vectors provided for document … and at least 60 other document(s)", so episode indexing could never activate on semantic-enabled servers. Episode docs now carry the documented _vectors.<embedder>: null opt-out, and attachDocumentVectors runs the per-document pass even for episode-only batches (it previously early-returned, which covers most batches of a large episode rebuild).

Dev validation (large catalog, semantic enabled):

  • Migrations applied cleanly at boot; both concurrent GIN builds valid (45 MB / 238 MB); all 10 triggers installed. DB-backed episode search + outbox trigger tests pass against a freshly migrated scratch DB.
  • PostgreSQL mixed search works end-to-end (episodes correctly top-ranked, access re-checked at hydration).
  • Full Meilisearch v3 rebuild completed after the fix: 1,318,000 docs, 186,528 vector docs (media only, as intended), zero dead-letters. Mixed + episode-scoped searches serve in 60–90 ms; federated hybrid (semantic media + keyword episodes) verified on Meilisearch 1.48.
  • jellycompat search hints gain episode results automatically (compat layer already requests movie,series,episode).

Known traps to consider before/right after merge:

  1. Worst-case PG path: common-token queries rank every candidate (the = 429k candidates → ~33 s on the dev catalog vs 6.3 s pre-PR media-only). Live-typing debounce can hit this whenever PG serves (default provider, and every Meilisearch fallback). Biggest lever: stored generated tsvector columns so ranking stops recomputing normalize_search_text/tsvectors per row.
  2. Deployments with a legacy explicit index_types=movie,series silently keep episodes out of Meilisearch (dev had exactly this). Consider auto-migrating the stored value or warning in admin search status.
  3. type=all includes audiobook/ebook/manga, so any explicit index_types setting routes every All-Media search to the slow PG path — and the web change intentionally makes All-Media stickier.
  4. The episode UPDATE trigger enqueues upserts even when no search-relevant column changed; a metadata refresh over a big series floods the outbox. Cheap fix: gate on IS DISTINCT FROM for title/overview/episode_number/air_date.
  5. Client repos: unscoped searches now return type=episode items — silo-android / silo-apple search UIs should be checked for episode-result rendering.

AI-use disclosure: merge resolution, fix, and dev validation performed with Claude Code (Fable); all changes verified by the repo's Go/frontend test suites plus the live dev deployment above.

@Quick104
Quick104 merged commit 4d1c976 into Silo-Server:main Jul 23, 2026
1 check was pending
@zZebrahz zZebrahz mentioned this pull request Sep 26, 2026
12 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants