Skip to content

[codex] fix season page loading - #178

Merged
Quick104 merged 2 commits into
mainfrom
codex/fix-season-page-loading
Jun 18, 2026
Merged

Quick104 merged 2 commits into
mainfrom
codex/fix-season-page-loading

Conversation

@Quick104

@Quick104 Quick104 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the season page loading regression around series season selection by addressing both the frontend refetch behavior and the backend season episode lookup path.

Root Cause

Season navigation was paying for two separate problems:

  • The frontend kept previous identity-specific catalog query data while switching between series and seasons, which made the route feel stalled and stale until all dependent queries settled.
  • High-frequency realtime user_state events invalidated and actively refetched visible catalog queries.
  • The backend season episode lookup filtered episodes by season_id without a matching index, forcing scans across a large episodes table.

Changes

  • Removed keepPreviousData from identity-specific catalog detail, season, version, and episode queries.
  • Added a non-refetching media surface invalidation path for realtime user-state events.
  • Added a concurrent Goose migration for episodes(season_id, episode_number).
  • Reworked season response construction to reuse loaded episode groups and batch progress aggregation instead of issuing per-episode progress lookups.

Impact

Season clicks no longer appear to hang while unrelated refetches finish. The backend now serves the affected season detail and episode-list paths through indexed lookups and batched progress reads.

Validation

  • cd web && pnpm run lint passed with existing warnings, no errors.
  • cd web && pnpm run format:check passed.
  • cd web && pnpm run build passed.
  • make migrate-validate passed.
  • make dev-deploy succeeded and compiled the server in Docker.
  • Browser validation on https://silo.arkyncdn.net/item/series-tvdb-81797: Loguetown click updated route in about 135 ms, content settled in about 1.2 s, console stayed clean.
  • Live DB EXPLAIN ANALYZE after migration used idx_episodes_season_id_episode_number, with the season episode lookup around 0.760 ms.

Local bare-host Go tests were not run successfully because /opt/dev/github/SiloServer/go.work lists Go 1.26.3 while this module requires >=1.26.4; the deployed Docker build path compiled successfully.

Risk And Follow-Up

  • Direct-link 404 behavior appears profile/access related and should be fixed separately by clearing catalog/item query caches on profile switch and preserving the intended return URL through profile selection.
  • Unrelated logs still show stale playback session 404 loops and occasional context-canceled home-section requests.

Scope: bug fix only; no new v1 capability.

AI-use disclosure: Implemented with AI assistance in Codex; changes were inspected, deployed to dev, and validated with browser and server timings.

Summary by CodeRabbit

Release Notes

  • Performance

    • Optimized episode and progress data loading through batch processing and improved database indexing.
  • Bug Fixes

    • Enhanced error handling when loading episodes for seasons.
  • Updates

    • Modified loading behavior for catalog items and seasons to remove stale data placeholders.

@coderabbitai

coderabbitai Bot commented Jun 18, 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: 7f4b8f00-92fb-4743-bd7f-3545294ae65c

📥 Commits

Reviewing files that changed from the base of the PR and between be27715 and 3cc02c0.

📒 Files selected for processing (4)
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • internal/api/handlers/items_user_data_test.go
  • migrations/sql/20260618164519_add_episodes_season_id_index.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go

📝 Walkthrough

Walkthrough

Backend season response construction is refactored to batch-fetch watch progress via chunked ListProgressByMediaItems calls instead of per-episode lookups, with new episodeContentIDs and flattenEpisodeGroups helpers. Handlers are updated to use grouped episode fetching and the new response builder. A concurrent DB index on episodes(season_id, episode_number) is added. Frontend catalog query hooks drop placeholderData: keepPreviousData.

Changes

Season Batch Fetching and Frontend Query Changes

Layer / File(s) Summary
DB index on episodes(season_id, episode_number)
migrations/sql/20260618164519_add_episodes_season_id_index.sql
Non-transactional Goose migration conditionally drops an invalid existing index and creates idx_episodes_season_id_episode_number concurrently on public.episodes(season_id, episode_number); Down migration drops it concurrently.
Batch progress aggregation helpers and toSeasonResponseFromEpisodes
internal/api/handlers/items.go, internal/api/handlers/items_user_data_test.go
Adds episodeContentIDs and flattenEpisodeGroups utilities. Rewrites getAggregateUserData to batch-load progress via ListProgressByMediaItems in deduped 500-ID chunks and produce SeasonUserData from the resulting map. Updates toSeasonResponse to fetch episodes and delegate to toSeasonResponseFromEpisodes, which now accepts and assigns aggregate UserData. Adds a unit test verifying getAggregateUserData returns nil when a batch call fails.
Handler updates to grouped episode fetching
internal/api/handlers/catalog_resources.go
HandleGetSeasons fetches episodes grouped by season via ListBySeriesGroupedBySeason and builds responses with toSeasonResponseFromEpisodes; fallback path computes aggregate userData once. HandleGetSeason adds error handling for ListBySeasonID and falls back to ListBySeason when empty. syntheticSeasonDetail switches from toSeasonResponse to toSeasonResponseFromEpisodes.
Remove keepPreviousData from catalog query hooks
web/src/hooks/queries/catalogRead.ts
Drops the keepPreviousData import and removes placeholderData: keepPreviousData from six catalog query hooks: useCatalogItemDetail, useCatalogItemVersions, useCatalogItemEpisodes, useCatalogSeriesSeasons, useCatalogSeasonDetail, and useCatalogSeasonEpisodes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% 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 '[codex] fix season page loading' directly addresses the main objective of the PR, which is to fix a season page loading regression. It accurately reflects the primary change.
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/fix-season-page-loading

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

@Quick104
Quick104 marked this pull request as ready for review June 18, 2026 17:37

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

ℹ️ 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 +424 to +426
payload.content_id
? { itemId: payload.content_id, refetchActive: false }
: { refetchActive: false },

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 active refetches for realtime user-state changes

When a user-state change originates from another tab or device, refetchType: "none" leaves every mounted catalog, progress, history, favorite, and watchlist query showing its cached data indefinitely. The direct update above only patches user_state on the changed item's detail; it does not update user_data, season aggregates, episode progress, or list membership. Consequently, an open season or Favorites page no longer reflects remote watched/progress/favorite changes until a later focus, remount, or manual refresh, whereas these active queries were refetched before this change.

Useful? React with 👍 / 👎.

switch {
case err == nil:
episodes, _ := h.items.episodeRepo.ListBySeasonID(r.Context(), season.ContentID)
episodes, err := h.items.episodeRepo.ListBySeasonID(r.Context(), season.ContentID)

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 Fall back to the season number when episode links are absent

For catalogs containing episodes whose nullable season_id has not been populated (including imported legacy bundles, whose importer preserves a missing season ID), this lookup returns no episodes even though the same rows are available by series_id and season_number. Before this change, toSeasonResponse performed that latter lookup, so the season detail still reported the correct episode count and aggregate user data; it now returns a zero-count season with no user data. Use the series/number lookup as a fallback, or ensure all existing rows are backfilled before relying exclusively on season_id.

Useful? React with 👍 / 👎.

Comment on lines +8 to +9
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_episodes_season_id_episode_number
ON public.episodes USING btree (season_id, episode_number);

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 Recover invalid concurrent indexes before retrying

If this non-transactional CREATE INDEX CONCURRENTLY is interrupted or fails after creating its catalog entry, PostgreSQL leaves an invalid index with this name. On the next Goose retry, IF NOT EXISTS treats that invalid relation as existing, skips rebuilding it, and allows the migration to be recorded as applied even though the optimizer cannot use the index, leaving the season lookup regression unfixed. Drop an invalid same-named index before creation or otherwise validate and rebuild it during retry.

Useful? React with 👍 / 👎.

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

🤖 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/api/handlers/items.go`:
- Around line 1466-1475: The progressMapForEpisodes method currently returns
partial progress data when batch retrieval fails, which causes incorrect
aggregation results. Instead of returning the incomplete progressMap, implement
error handling similar to listLeafUserData: check for errors during the
listProgressForEpisodeIDs call within progressMapForEpisodes and return nil,
false when a batch error occurs, ensuring that partial progress maps are never
used for aggregation and preventing incorrect episode watch status from being
displayed.

In `@migrations/sql/20260618164519_add_episodes_season_id_index.sql`:
- Around line 8-9: The issue is that using IF NOT EXISTS with CREATE INDEX
CONCURRENTLY can mask invalid index states in PostgreSQL's system catalog. When
a concurrent index creation fails, the IF NOT EXISTS clause will skip recreation
on rerun even though the index is invalid, causing the migration to appear
successful while the index remains unusable. Remove the IF NOT EXISTS clause
from the CREATE INDEX CONCURRENTLY statement in the
idx_episodes_season_id_episode_number index creation so that the migration will
fail explicitly if the index already exists, forcing immediate attention to any
invalid index state rather than silently skipping the operation.
🪄 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: ec703134-d28c-4d90-8ed0-e4ce07877e67

📥 Commits

Reviewing files that changed from the base of the PR and between a24f5bb and be27715.

📒 Files selected for processing (6)
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • migrations/sql/20260618164519_add_episodes_season_id_index.sql
  • web/src/components/RealtimeEventsProvider.tsx
  • web/src/hooks/queries/catalogRead.ts
  • web/src/hooks/queries/mediaSurfaceRefresh.ts

Comment thread internal/api/handlers/items.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit 9c7e2bf into main Jun 18, 2026
1 check passed
@Quick104
Quick104 deleted the codex/fix-season-page-loading branch June 18, 2026 18:18
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
* fix(catalog): speed up season page loads

* fix: address season loading review feedback
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