Skip to content

[codex] Fix Next Up anchor query - #41

Merged
Quick104 merged 1 commit into
mainfrom
codex/fix-next-up-anchor-query
Jun 2, 2026
Merged

Quick104 merged 1 commit into
mainfrom
codex/fix-next-up-anchor-query

Conversation

@Quick104

@Quick104 Quick104 commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Remove the 100-row completed-progress pre-cap from the Next Up anchor query.
  • Derive the latest completed episode anchor per series inside SQL, then apply the requested result limit after valid next-up candidates are found.
  • Preserve hidden-history suppression and existing in-progress newer-than-anchor suppression behavior.

Root Cause

Next Up previously loaded only the 100 most recent completed progress rows before grouping by series. Large imported histories could have those rows dominated by fully-watched series, causing the section to return no candidates even when older completed series had valid next episodes.

Validation

  • go test ./internal/catalog
  • go test ./internal/sections
  • Verified the rewritten SQL returns 9 Next Up candidates for dev user 182.
  • Deployed to the dev server with make dev-deploy; /api/v1/ready returned {"status":"ok"}.

AI Use

Implemented with Codex.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Fixed an issue where episodes marked as hidden in user profiles were not being properly excluded from "Next Up" recommendations. Hidden content is now correctly filtered based on individual viewing preferences, ensuring personalized suggestions accurately respect user-defined content restrictions.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The ListNextUp function is refactored to shift completed-episodes and hidden-items logic into SQL query generation. Instead of pre-fetching completed episode IDs in Go and passing them to the query builder, the function now computes a default limit and relies on buildListNextUpQuery to construct the completed-episodes selection inside the SQL, including a new hidden-items filter. Bind parameter indices are adjusted accordingly, and tests are updated to reflect the new query structure and invocation signature.

Changes

Next-up query refactoring with hidden-items filtering

Layer / File(s) Summary
Call site and function signature refactoring
internal/catalog/nextup_repo.go
ListNextUp now derives a default limit in Go and calls buildListNextUpQuery(q, limit) instead of pre-fetching and passing completed episode IDs. The helper function signature removes the completedIDs parameter and initializes argument bindings from the reduced input set.
SQL query generation with hidden-items filtering and limit binding
internal/catalog/nextup_repo.go
The completed-episodes CTE gains a NOT EXISTS filter against user_history_hidden_items to exclude episodes hidden for the user profile. The final LIMIT bind parameter is adjusted to use the updated index $3.
Test assertions and invocation updates
internal/catalog/nextup_repo_test.go
Tests are updated to verify new SQL fragments for hidden-item filtering, the expected argument count is reduced from 4 to 3, and invocations of buildListNextUpQuery are adjusted to remove the prior slice argument.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A catalog of shows, both seen and unseen,
Now hidden by time, no longer convene.
The query refactored, SQL takes the lead,
Filtering whispers of what scrolls we freed. 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 PR title '[codex] Fix Next Up anchor query' directly addresses the main change—refactoring the Next Up query to derive the completed-episode anchor per series inside SQL instead of pre-capping completed progress rows.
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-next-up-anchor-query

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

@Quick104
Quick104 marked this pull request as ready for review June 2, 2026 15:10

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

🧹 Nitpick comments (1)
internal/catalog/nextup_repo.go (1)

157-207: Validate the query plan and supporting indexes before wider rollout.

Dropping the pre-cap means this path now walks the user's full completed history and runs the hidden-items anti-join for each candidate anchor. I'd EXPLAIN this against prod-sized histories and make sure the access path is backed by composite indexes that match the new predicates, especially on user_watch_progress and user_history_hidden_items, so the correctness fix doesn't become a latency regression.

🤖 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/nextup_repo.go` around lines 157 - 207, The new query
removed the pre-cap and now scans the user's full completed history and
repeatedly anti-joins to user_history_hidden_items; run EXPLAIN (ANALYZE,
BUFFERS) on the completed_episodes CTE and full query against prod-like data to
verify plan and hotspots, and if needed add composite indexes that match the
predicates used by completed_episodes and the hidden-items anti-join —
specifically consider indexes on user_watch_progress covering (user_id,
profile_id, completed, updated_at, media_item_id) and on
user_history_hidden_items covering (user_id, profile_id, media_item_id,
hidden_before) (or same columns in an order matching the planner’s filter usage)
to support the EXISTS/NOT EXISTS checks and ordering so this correctness change
does not cause a latency regression.
🤖 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.

Nitpick comments:
In `@internal/catalog/nextup_repo.go`:
- Around line 157-207: The new query removed the pre-cap and now scans the
user's full completed history and repeatedly anti-joins to
user_history_hidden_items; run EXPLAIN (ANALYZE, BUFFERS) on the
completed_episodes CTE and full query against prod-like data to verify plan and
hotspots, and if needed add composite indexes that match the predicates used by
completed_episodes and the hidden-items anti-join — specifically consider
indexes on user_watch_progress covering (user_id, profile_id, completed,
updated_at, media_item_id) and on user_history_hidden_items covering (user_id,
profile_id, media_item_id, hidden_before) (or same columns in an order matching
the planner’s filter usage) to support the EXISTS/NOT EXISTS checks and ordering
so this correctness change does not cause a latency regression.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c253a4b0-f96d-49bb-aa2d-077775003c27

📥 Commits

Reviewing files that changed from the base of the PR and between 3beb375 and 3a0687b.

📒 Files selected for processing (2)
  • internal/catalog/nextup_repo.go
  • internal/catalog/nextup_repo_test.go

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

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

}

query, args := buildListNextUpQuery(q, completedIDs, limit)
query, args := buildListNextUpQuery(q, limit)

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 Keep Next Up anchored to the user store

When userdb.backend=sqlite is configured, watch progress is written through SQLiteProvider into the per-user SQLite store, but this path now skips store.ListProgress and derives completed anchors only from the Postgres user_watch_progress table. In those deployments /Shows/NextUp and the home Next Up section will miss completed anchors (often returning no next-up rows) even though the user's store has completed episodes; the previous code worked because it read completed IDs from the configured UserStore before joining against catalog episodes.

Useful? React with 👍 / 👎.

%s
%s
ORDER BY e.series_id, uwp.updated_at DESC
ORDER BY e.series_id, uwp.updated_at DESC, e.season_number DESC, e.episode_number DESC

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 Bound the completed-anchor scan for large histories

After removing the completedIDs prefilter, this CTE now has to read every completed progress row for the profile, join each row to episodes, and sort by series before the final LIMIT can apply; the checked progress indexes only cover (user_id, profile_id, updated_at DESC), so they do not support this distinct-by-series ordering. On the large imported histories this change targets, every home/Next Up request can become an unbounded scan/sort of the user's full completed history; add a purpose-built indexed/materialized anchor path or otherwise bound the work while still avoiding the old 100-row cap.

Useful? React with 👍 / 👎.

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