Skip to content

perf(catalog): add episode browse index fast path - #16

Merged
Quick104 merged 3 commits into
mainfrom
codex/episode-catalog-performance
May 27, 2026
Merged

Quick104 merged 3 commits into
mainfrom
codex/episode-catalog-performance

Conversation

@Quick104

@Quick104 Quick104 commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add the episode_catalog_entries read model with backfill, maintenance triggers, and indexes for episode library browse.
  • Route supported episode library sort/filter shapes through ID-first fast paths, with user-state-first plans for watched/progress/date-viewed cases and generic fallback for unsupported combinations.
  • Stop requesting exact totals by default from the Library tab and add a credential-free episode catalog benchmark helper.

Verification

  • go test ./internal/catalog ./internal/scanner ./internal/userstore -count=1
  • cd web && pnpm vitest run src/pages/LibraryBrowse.test.tsx
  • cd web && pnpm run lint (passes with existing warnings)
  • git diff --check
  • make verify-local-paths
  • Dev deploy completed; silo-silo-1 is healthy.

Performance Notes

  • Library 2 backfilled 767,464 episode catalog entries, matching episode_libraries.
  • Warm HTTPS timings with include_total=false were roughly 180-245 ms for added_at, title, resolution, and bitrate first-page requests.
  • Exact totals remain more expensive; Library Browse now avoids them by default.

AI Use

  • Implemented with Codex assistance.

Note

High Risk
Large schema migration with triggers on hot tables (media_files, episodes) plus new query routing; incorrect refresh or planner fallback could affect browse correctness or write load in production.

Overview
This PR speeds up episode library catalog browse for large libraries by introducing a maintained episode_catalog_entries read model (migration 142) with backfill, refresh triggers, and btree/GIN indexes, plus an idx_episodes_sort_key_content index for title sort.

Catalog execution now tries ID-first fast paths before the generic executor: a user-state-first plan (watched, in progress, last_watched, date_viewed, plays, progress) and a read-model plan for supported metadata/technical sorts and filters, then hydrates only the page’s episode IDs. Unsupported shapes still fall back. PreviewPage drops COUNT(*) OVER () on the page query; exact totals run via a separate count that omits sort-only joins. Episode title, added_at, and name prefix paths use projected sort_key and tighter single-library episode_libraries joins.

Library browse UI requests includeTotal: false by default and no longer shows an exact filtered item count. ReconcileFolderMembership restores missing memberships before pruning stale rows. A scripts/benchmark_episode_catalog.py harness and a performance plan doc support measurement.

Reviewed by Cursor Bugbot for commit 1b326f4. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Faster episode catalog browsing with reduced first-page latency for large libraries and improved pagination; exact total counts are now skipped by default to speed responses.
  • Chores

    • Database migrations and indexing to support the episode catalog read model.
    • Added a benchmarking CLI for catalog performance.
  • Documentation

    • Added an Episode Catalog Performance Plan describing strategy and rollout phases.
  • Tests

    • Expanded backend and frontend tests covering episode catalog queries, sorting, and item-count UI.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c23b0292-8935-4b10-b443-8d07506ed47d

📥 Commits

Reviewing files that changed from the base of the PR and between 6facf2e and 1b326f4.

📒 Files selected for processing (8)
  • docs/superpowers/plans/2026-05-27-episode-catalog-performance.md
  • internal/catalog/episode_catalog_entries_executor.go
  • internal/catalog/episode_catalog_entries_executor_test.go
  • migrations/142_episode_catalog_entries.down.sql
  • migrations/142_episode_catalog_entries.up.sql
  • scripts/benchmark_episode_catalog.py
  • web/src/pages/LibraryBrowse.test.tsx
  • web/src/pages/LibraryBrowse.tsx

📝 Walkthrough

Walkthrough

This PR adds a durable per-library episode read model, separates paged queries from exact-count SQL, implements episode-scoped sort/prefix behavior and a user-state preview path, includes migrations/backfill and triggers to maintain the read model, updates tests and frontend to avoid exact-counts by default, and adds a benchmarking CLI.

Changes

Episode Catalog Performance Optimization

Layer / File(s) Summary
Performance plan and strategy documentation
docs/superpowers/plans/2026-05-27-episode-catalog-performance.md
Performance goals, measured timings, root-cause analysis, prototype validation, proposed episode_catalog_entries schema, planner design (ID-first pages, user-state-first rules), multi-mode count strategy, and phased rollout/testing checklist.
Database schema and synchronization
migrations/141_episode_title_sort_index.up.sql, migrations/141_episode_title_sort_index.down.sql, migrations/142_episode_catalog_entries.up.sql, migrations/142_episode_catalog_entries.down.sql
Adds episode_catalog_entries table, helper functions (rating/resolution/ranks), refresh_episode_catalog_entry and wrapper functions, triggers on episode_libraries/media_files/episodes/media_items, initial backfill, indexes (btree/GIN/partial), incremental post-migration refresh, and down-migration cleanup; also adds an idempotent episode title sort index.
Episode catalog executor and rule translation
internal/catalog/episode_catalog_entries_executor.go, internal/catalog/episode_catalog_entries_executor_test.go
Implements two preview entrypoints (user-state-driven and generic), rule→SQL clause builders, user-state CTE generation and rebind, ordered ID-first pagination with hydration to media items, added-at selection logic, availability error classification, and unit tests for order-by, where-clause translation, user-state plans, and gate predicates.
Query execution refactoring—separate paging from totals
internal/catalog/query_executor.go, internal/catalog/window_count_test.go, internal/catalog/query_executor_test.go
Refactors PreviewPage to emit paged SQL without COUNT window, adds fromClauseCount and countSQL() that omits sort-only joins and uses separate arg binding, derives hasMore from extra row or exact count when requested, and adds/updates tests for the new shapes.
Query builder support for episode scope and sorting
internal/catalog/query_builder.go, internal/catalog/query_builder_test.go, internal/catalog/episode_catalog_source.go, internal/catalog/name_prefix_sql_test.go
Special-cases normalized title to mi.sort_key in episode scope, threads explicit nullsLast from addedAtSortPlan for single vs multi-library episode joins, computes episode sort_key and show_status projection, and updates name-prefix SQL generation/tests to use the episode sort key.
Repository and executor tests
internal/catalog/episode_library_repo.go, internal/catalog/*_test.go
ReconcileFolderMembership restored-to-then-delete behavior for folder membership reconciliation; expanded tests cover query-builder/preview SQL, name-prefix behavior, window-count omission, and episode-catalog executor behaviors.
Library browse frontend integration
web/src/pages/LibraryBrowse.tsx, web/src/pages/LibraryBrowse.test.tsx
Sets catalog queries to includeTotal: false, removes exact-count display/props, and updates tests to assert totals are not requested or shown as exact counts when disabled.
Benchmarking and observability
scripts/benchmark_episode_catalog.py
New CLI to benchmark catalog API cases (sorts/filters) with concurrency and optional exact-count mode, emitting CSV and latency summaries for verification and tuning.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A catalog of swift episodes now takes flight,
A read-model hums beneath the night,
Pages come quick while counts step aside,
User-state sorts help the first page glide,
Benchmarks sing — performance feels light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.21% 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: adding an episode browse index fast path for performance. It is concise, specific, and clearly describes the primary modification.
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/episode-catalog-performance

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

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 6facf2e. Configure here.

@Quick104
Quick104 marked this pull request as ready for review May 27, 2026 16:08

@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: 3

🧹 Nitpick comments (2)
docs/superpowers/plans/2026-05-27-episode-catalog-performance.md (2)

506-521: ⚡ Quick win

Consider adding trigger reliability and backfill safety to risks.

The risks section is comprehensive, but could benefit from explicitly mentioning:

  • Trigger lag monitoring: How will the system detect if episode_catalog_entries refresh triggers fall behind or fail silently?
  • Backfill safety: The doc mentions 22s for dev data (line 124), but production backfill duration, locking behavior, and safe execution strategy aren't covered.
  • Degradation strategy: What happens if the read model becomes stale or corrupted? Is there a fallback plan beyond "use the generic executor"?

Adding these to the risks section would make operational readiness clearer for Phase 2 deployment.

🤖 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 `@docs/superpowers/plans/2026-05-27-episode-catalog-performance.md` around
lines 506 - 521, Add explicit operational risks and mitigations: mention trigger
lag monitoring for episode_catalog_entries (describe a metric/alert for refresh
lag or failed runs tied to the refresh trigger), add backfill safety guidance
(estimate production backfill time, recommend running backfills in chunked,
idempotent transactions with low-locking strategies and a documented rollback
plan), and define a clear degradation strategy beyond the generic executor
(automated read-model health checks, a read-model stale threshold that triggers
fallback to generic executor plus a remediation runbook). Reference the read
model name episode_catalog_entries, the backfill process, and the generic
executor in the added bullets so operators can find and act on them.

197-248: ⚡ Quick win

Consider documenting index maintenance cost and disk space.

The plan proposes 12 btree indexes plus 3 GIN indexes on episode_catalog_entries. For a table with 767k rows and continuous trigger-based updates, this could have measurable write overhead and disk space requirements.

Consider adding a brief note in the "Risks and Open Questions" section about:

  • Expected disk space for the table + indexes
  • Write amplification during scanner operations
  • Index maintenance cost vs query performance tradeoff

This would help operators plan capacity and monitor the read model's impact on write workloads.

🤖 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 `@docs/superpowers/plans/2026-05-27-episode-catalog-performance.md` around
lines 197 - 248, Add a short "Index maintenance, disk & write amplification"
bullet in the "Risks and Open Questions" section that calls out the proposed
indexes on episode_catalog_entries (e.g., idx_episode_catalog_entries_title,
idx_episode_catalog_entries_added, idx_episode_catalog_entries_air_date, the GIN
indexes like idx_episode_catalog_entries_genres_gin) and documents expected
operational impacts: estimated disk space for table+indexes, write amplification
during scanner/trigger updates, and index maintenance/latency tradeoffs vs query
performance so operators can plan capacity and monitoring.
🤖 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 `@migrations/142_episode_catalog_entries.up.sql`:
- Around line 592-647: The migration misses pairs deleted from episode_libraries
during the backfill window, leaving stale episode_catalog_entries; fix by
extending changed_entries to also include DISTINCT episode_id, media_folder_id
from public.episode_catalog_entries where there is NO matching row in
public.episode_libraries (i.e., NOT EXISTS (SELECT 1 FROM
public.episode_libraries el WHERE el.episode_id =
episode_catalog_entries.episode_id AND el.media_folder_id =
episode_catalog_entries.media_folder_id)), so those deleted pairs are fed into
public.refresh_episode_catalog_entry(...) for cleanup; update the
changed_entries CTE to add this UNION so the subsequent SELECT calls
refresh_episode_catalog_entry for deleted memberships as well.

In `@scripts/benchmark_episode_catalog.py`:
- Around line 153-176: The code currently swallows HTTP status on payload/parse
failures because JSON parsing errors fall into the broad except Exception path
which returns status 0; to fix, wrap json.loads(body) and subsequent payload
handling in a narrower try/except that catches json.JSONDecodeError (and
optionally KeyError/TypeError for unexpected shapes) and in that handler return
a CaseResult using response.status and the parse error message; keep the
existing urllib.error.HTTPError except as-is and only use the broad except
Exception for true connection/other failures (refer to the with
urllib.request.urlopen(...), json.loads(body), CaseResult(...) and the final
except Exception handler for where to insert the nested try/except).
- Around line 129-155: The code must reject non-http(s) SILO_BASE_URL before
performing network I/O: in fetch_case, after computing url = build_url(config,
params, include_total) (and/or by parsing config.base_url earlier in build_url),
parse the URL with urllib.parse.urlparse and verify parsed.scheme is "http" or
"https"; if not, fail fast (raise a ValueError or return a CaseResult error)
with a clear message referencing config.base_url/SILO_BASE_URL so
urllib.request.urlopen() is never called for non-http(s) schemes. Ensure this
check references build_url, fetch_case, and config.base_url so reviewers can
locate the change.

---

Nitpick comments:
In `@docs/superpowers/plans/2026-05-27-episode-catalog-performance.md`:
- Around line 506-521: Add explicit operational risks and mitigations: mention
trigger lag monitoring for episode_catalog_entries (describe a metric/alert for
refresh lag or failed runs tied to the refresh trigger), add backfill safety
guidance (estimate production backfill time, recommend running backfills in
chunked, idempotent transactions with low-locking strategies and a documented
rollback plan), and define a clear degradation strategy beyond the generic
executor (automated read-model health checks, a read-model stale threshold that
triggers fallback to generic executor plus a remediation runbook). Reference the
read model name episode_catalog_entries, the backfill process, and the generic
executor in the added bullets so operators can find and act on them.
- Around line 197-248: Add a short "Index maintenance, disk & write
amplification" bullet in the "Risks and Open Questions" section that calls out
the proposed indexes on episode_catalog_entries (e.g.,
idx_episode_catalog_entries_title, idx_episode_catalog_entries_added,
idx_episode_catalog_entries_air_date, the GIN indexes like
idx_episode_catalog_entries_genres_gin) and documents expected operational
impacts: estimated disk space for table+indexes, write amplification during
scanner/trigger updates, and index maintenance/latency tradeoffs vs query
performance so operators can plan capacity and monitoring.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 570fdc64-a9c9-45e3-8174-23c7e3d8980f

📥 Commits

Reviewing files that changed from the base of the PR and between e46f608 and 6facf2e.

📒 Files selected for processing (18)
  • docs/superpowers/plans/2026-05-27-episode-catalog-performance.md
  • internal/catalog/episode_catalog_entries_executor.go
  • internal/catalog/episode_catalog_entries_executor_test.go
  • internal/catalog/episode_catalog_source.go
  • internal/catalog/episode_library_repo.go
  • internal/catalog/name_prefix_sql_test.go
  • internal/catalog/query_builder.go
  • internal/catalog/query_builder_test.go
  • internal/catalog/query_executor.go
  • internal/catalog/query_executor_test.go
  • internal/catalog/window_count_test.go
  • migrations/141_episode_title_sort_index.down.sql
  • migrations/141_episode_title_sort_index.up.sql
  • migrations/142_episode_catalog_entries.down.sql
  • migrations/142_episode_catalog_entries.up.sql
  • scripts/benchmark_episode_catalog.py
  • web/src/pages/LibraryBrowse.test.tsx
  • web/src/pages/LibraryBrowse.tsx

Comment thread scripts/benchmark_episode_catalog.py Resolved
Comment thread scripts/benchmark_episode_catalog.py Resolved

@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: 6facf2ecbe

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

public.episode_catalog_normalized_resolution(mf.resolution) AS normalized_resolution,
public.episode_catalog_resolution_rank(mf.resolution) AS resolution_rank,
mf.bitrate,
COALESCE(mf.hdr, false) AS hdr,

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 Preserve nullable HDR semantics in the read model

For episodes with older or unprobed files where media_files.hdr is NULL, this coalesces the value to false and then sets has_non_hdr via BOOL_OR(NOT hdr). The new fast path uses that flag for hdr is false, but the existing generic filter checks mf.hdr = false, so NULL files previously did not match; single-library episode catalog queries can now return unknown-HDR episodes as non-HDR while fallback paths do not. Consider tracking BOOL_OR(mf.hdr IS FALSE) instead of converting NULL to false.

Useful? React with 👍 / 👎.


DROP TRIGGER IF EXISTS trg_episode_catalog_entries_episodes ON public.episodes;
CREATE TRIGGER trg_episode_catalog_entries_episodes
AFTER INSERT OR UPDATE OF content_id, series_id, title, air_date, runtime, rating_imdb, rating_tmdb, still_path, still_thumbhash, created_at OR DELETE

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 Refresh entries when episode numbers change

The read model stores fallback titles/sort keys as Episode <episode_number> when an episode title is blank, but this trigger does not fire on episode_number updates. If scanner/metadata reconciliation corrects an untitled episode's number, episode_catalog_entries.sort_key and title remain stale, so the new fast path can browse/search it under the old number until some unrelated watched column changes; include episode_number in the trigger's UPDATE column list.

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit 583c16c into main May 27, 2026
1 of 2 checks passed
@Quick104
Quick104 deleted the codex/episode-catalog-performance branch May 27, 2026 16:52
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
…log-performance

perf(catalog): add episode browse index fast path
Quick104 added a commit that referenced this pull request Jun 11, 2026
…ance

perf(catalog): add episode browse index fast path
CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
Six defects on byte-serving paths, all of which made the PR's monitoring and
kill-switch claims narrower than documented.

#2/GAP-10 -- the ABS in-flight kill switch was a production no-op. accessLog
wraps every ABS route, and its statusRecorder implemented Write, WriteHeader,
Hijack and Flush but not Unwrap, so http.NewResponseController dead-ended and
SetWriteDeadline returned ErrNotSupported. A multi-GB audiobook pour survived a
RevokeUser. The existing test passed throughout because it called handlers
directly and never saw the middleware; the new test drives the mounted router
over a real socket, and both new assertions fail if Unwrap is removed again.

GAP-11 -- ebook, comic and PDF serving was invisible and un-killable: no meter,
no transfer record, no Refuse, no watcher, on a route that serves cbz/cbr/pdf
files routinely 100 MB-1 GB+. It now follows the ABS file-handler idiom. Note
guardRevocationCut is deliberately *not* reused here: it keys on a session_id
URL param and an ?st= token this route does not carry, so it would have
compiled and silently guarded nothing. Cap-exempt per decision A4 -- admission
is untouched and neither route consumes a stream slot.

#10 -- the no-proxy remote transcode hop forwarded segments through a bare
RollingDeadlineWriter, so bytes on the API hop went unaccounted for a supported
topology. Metering is scoped to media bodies; manifests are excluded so a
rewritten playlist is not counted as media, and a mid-copy failure is no longer
silently discarded.

#16 -- native, proxy and compat subtitle pours were entry-gated only. They now
carry a transport span, a meter and an in-flight watcher. Proxy subtitle bytes
are attributed only when a tracker record already exists: taking Track/Remove
lifecycle ownership per subtitle request would walk straight into the
overlapping-request defect (#1) that Batch 2 addresses. Compat subtitle
extraction is buffered and rejects bitmap formats, so a cut stops delivery but
not extraction already in progress.

M2 -- the proxy deferred tracker Remove with the request context, which is
already canceled on client disconnect, so the Redis DEL never happened and the
key lingered until TTL -- a false over-cap window that could get a legitimate
stream killed. Cleanup now uses a short bounded context.

GAP-13 -- mergeStreams took the freshest record wholesale and never merged
BytesServed, so a stream that poured 8 GiB at an edge could report 0. Merged as
a max, not a sum: the records are two observers of one pour. Fixed in
DedupeSessionInfos too, which had the same hole and feeds the admin view.

#11 needed no behaviour change -- that route was already metered, registered and
watched, and commit c24d839 plus this Unwrap fix are what make its cut work.
Its comment claimed download-class exemption while the comment above it said the
?token= form is for iOS streaming; both facts and decision A4 are now stated.

Part of #305.
@kody-ai kody-ai Bot mentioned this pull request Sep 27, 2026
2 tasks done
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