Repository navigation
perf(catalog): add episode browse index fast path - #16
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (8)
📝 WalkthroughWalkthroughThis 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. ChangesEpisode Catalog Performance Optimization
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ 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.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
docs/superpowers/plans/2026-05-27-episode-catalog-performance.md (2)
506-521: ⚡ Quick winConsider 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_entriesrefresh 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 winConsider 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
📒 Files selected for processing (18)
docs/superpowers/plans/2026-05-27-episode-catalog-performance.mdinternal/catalog/episode_catalog_entries_executor.gointernal/catalog/episode_catalog_entries_executor_test.gointernal/catalog/episode_catalog_source.gointernal/catalog/episode_library_repo.gointernal/catalog/name_prefix_sql_test.gointernal/catalog/query_builder.gointernal/catalog/query_builder_test.gointernal/catalog/query_executor.gointernal/catalog/query_executor_test.gointernal/catalog/window_count_test.gomigrations/141_episode_title_sort_index.down.sqlmigrations/141_episode_title_sort_index.up.sqlmigrations/142_episode_catalog_entries.down.sqlmigrations/142_episode_catalog_entries.up.sqlscripts/benchmark_episode_catalog.pyweb/src/pages/LibraryBrowse.test.tsxweb/src/pages/LibraryBrowse.tsx
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
…log-performance perf(catalog): add episode browse index fast path
…ance perf(catalog): add episode browse index fast path
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.

Summary
episode_catalog_entriesread model with backfill, maintenance triggers, and indexes for episode library browse.Verification
go test ./internal/catalog ./internal/scanner ./internal/userstore -count=1cd web && pnpm vitest run src/pages/LibraryBrowse.test.tsxcd web && pnpm run lint(passes with existing warnings)git diff --checkmake verify-local-pathssilo-silo-1is healthy.Performance Notes
767,464episode catalog entries, matchingepisode_libraries.include_total=falsewere roughly 180-245 ms foradded_at,title,resolution, andbitratefirst-page requests.AI Use
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_entriesread model (migration 142) with backfill, refresh triggers, and btree/GIN indexes, plus anidx_episodes_sort_key_contentindex 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.PreviewPagedropsCOUNT(*) 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 projectedsort_keyand tighter single-libraryepisode_librariesjoins.Library browse UI requests
includeTotal: falseby default and no longer shows an exact filtered item count.ReconcileFolderMembershiprestores missing memberships before pruning stale rows. Ascripts/benchmark_episode_catalog.pyharness 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
Chores
Documentation
Tests