Repository navigation
fix(catalog): bound Next Up anchors by distinct series, not rows - #593
Conversation
The global Next Up query capped its anchor scan at the 500 most recently completed rows (nextUpAnchorMaxRows, #350). Bulk mark-watched writes hundreds of completed rows with the newest timestamps, so one series could flood the whole window and evict every other series from the rail - observed in production wiping a user's Next Up row entirely. Replace the row-capped CTE with a recursive skip-scan over idx_uwp_profile_completed that emits the newest completed row of each not-yet-seen series and stops after nextUpAnchorMaxSeries (96) distinct series. A compound (updated_at, media_item_id) cursor keeps the walk total when bulk writes share one timestamp across series. The series-scoped branch (show-detail tile) keeps its unbounded shape. DB-backed regression tests cover the flood shape (600 same-timestamp rows of one series must not evict others) and same-timestamp anchors across series; the flood test fails against the previous query. Fixes #592 Co-Authored-By: Claude Fable 5 <[email protected]>
📝 WalkthroughWalkthroughThe Next Up repository selects distinct global series through recursive PostgreSQL scans in resumable batches. Compound cursors preserve ordering across batches. Hidden and cutoff-filtered rows are excluded during each scan. PostgreSQL integration tests cover continuation and exhausted-history cases. ChangesNext Up anchor selection
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant NextUpRepository
participant PostgreSQL
participant CompletedWatchProgress
NextUpRepository->>PostgreSQL: Execute global query with cursor
PostgreSQL->>CompletedWatchProgress: Recursively find eligible unseen series
CompletedWatchProgress-->>PostgreSQL: Return anchors and frontier metadata
PostgreSQL-->>NextUpRepository: Return next-up rows
NextUpRepository->>PostgreSQL: Request the next batch from the frontier
Possibly related issues
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/catalog/nextup_repo_test.go (1)
327-344: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueGuard the parallel slice lengths.
unnestpads shorter arrays with NULL. If a future caller passes slices of different lengths, this helper inserts rows with a NULLcontent_idorseries_id, or fails with an opaque constraint error. A length check turns that into a clear test failure.♻️ Proposed guard
t.Helper() + if len(episodeIDs) != len(seriesIDs) || len(episodeIDs) != len(episodeNumbers) { + t.Fatalf("seedNextUpEpisodes: mismatched fixture lengths %d/%d/%d", + len(episodeIDs), len(seriesIDs), len(episodeNumbers)) + } + if _, err := pool.Exec(ctx, `🤖 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_test.go` around lines 327 - 344, Update seedNextUpEpisodes to validate that episodeIDs, seriesIDs, and episodeNumbers have identical lengths before executing the INSERT, and fail the test with a clear length-mismatch message when they differ.
🤖 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/nextup_repo_test.go`:
- Line 297: Update the profileID generation in the test to avoid the truncated
timestamp, deriving it from the existing per-run entropy used for prefix or
generating a random UUID. Preserve the required UUID format and ensure each test
run produces a collision-free user_profiles.id.
---
Nitpick comments:
In `@internal/catalog/nextup_repo_test.go`:
- Around line 327-344: Update seedNextUpEpisodes to validate that episodeIDs,
seriesIDs, and episodeNumbers have identical lengths before executing the
INSERT, and fail the test with a clear length-mismatch message when they differ.
🪄 Autofix
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: 565ec4f1-9e76-4cab-aeed-a74323e40e6d
📒 Files selected for processing (2)
internal/catalog/nextup_repo.gointernal/catalog/nextup_repo_test.go
| t.Fatalf("seed user: %v", err) | ||
| } | ||
|
|
||
| profileID := fmt.Sprintf("00000000-0000-4000-8000-%012d", time.Now().UnixNano()%1_000_000_000_000) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Make the profile ID collision-free.
time.Now().UnixNano()%1_000_000_000_000 wraps about every 16.7 minutes. Two runs separated by that interval can generate the same profileID. If user_profiles.id is a primary key, the insert then fails and the test aborts. Derive the profile ID from the same per-run entropy that already produces prefix, or use a random UUID.
🐛 Proposed fix using full-width entropy
- profileID := fmt.Sprintf("00000000-0000-4000-8000-%012d", time.Now().UnixNano()%1_000_000_000_000)
+ profileID := fmt.Sprintf("%08x-0000-4000-8000-%012x", rand.Uint32(), rand.Uint64()&0xFFFFFFFFFFFF)Add "math/rand/v2" to the imports.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| profileID := fmt.Sprintf("00000000-0000-4000-8000-%012d", time.Now().UnixNano()%1_000_000_000_000) | |
| profileID := fmt.Sprintf("%08x-0000-4000-8000-%012x", rand.Uint32(), rand.Uint64()&0xFFFFFFFFFFFF) |
🤖 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_test.go` at line 297, Update the profileID
generation in the test to avoid the truncated timestamp, deriving it from the
existing per-run entropy used for prefix or generating a random UUID. Preserve
the required UUID format and ensure each test run produces a collision-free
user_profiles.id.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: da84cbe3e9
ℹ️ 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".
| ORDER BY uwp.updated_at DESC, uwp.media_item_id DESC | ||
| LIMIT 1 | ||
| ) pick ON true | ||
| WHERE w.n < %d |
There was a problem hiding this comment.
Continue walking until enough eligible series are found
The fixed 96-series stop is applied before the lateral next-episode and in-progress exclusions, so those anchors do not guarantee any returned rows. If a profile's 96 most recently completed series are finished, unavailable, or blocked by newer partial progress, an older series with a valid next episode is never examined and the rail can still become empty; this also caps /Shows/NextUp pagination even though the handler requests Limit + StartIndex. Bound the walk based on the requested number of eligible results, or otherwise continue past rejected anchors.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
…es found The 96-series walk budget counted visited series, but eligibility (next episode exists with a present file, no newer partial progress) is only decided downstream, so 96 consecutive ineligible anchors - all caught up, unavailable, or blocked - still emptied the rail and silently capped /Shows/NextUp pagination at whatever survived one walk. Run the walk in batches: each batch keeps the 96-series budget, reports its frontier (compound cursor position, seen-series array, rows walked), and ListNextUp resumes the next batch below that frontier until the requested limit is filled, history is exhausted (frontier short of the budget), or a 10-batch runaway guard trips (logged, never silent). Batches emit anchors in strictly descending (updated_at, media_item_id) order, so appending preserves rail order. Series-scoped queries keep their single-shot shape. DB-backed regressions: 100 fully-watched series must not hide older series with eligible next episodes (fails on the single-batch code), and an all-caught-up profile returns empty without spinning to the batch cap. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Addressed the P1 in ef7a21b — the walk now continues until enough eligible series are found, not just visited. Approach: batched continuation in Go, not eligibility-in-SQL. I first prototyped pushing the eligibility test (next-episode LATERAL + newer-partial-progress exclusion) into every walk step so the recursion could stop on eligible-count directly. Measured on the worst production profile it costs ~1.2s (the eligibility probe runs per visited series, including all the ineligible ones) — worse than the disease. Instead, each batch keeps the cheap 96-visited-series walk but now reports its frontier (compound cursor position + seen-series array + rows walked), and Loop invariants:
Verification (same sandbox DB + read-only prod methodology as the PR body):
One honest caveat: a profile whose recent history is a long run of caught-up series pays one extra ~200ms batch per 96 ineligible anchors until it finds enough eligible ones (bounded at 10). That's the cost of correctness here; the warning log is the tripwire if real profiles ever hit the cap. (AI disclosure as in the PR body: claude-fable-5 orchestrating/reviewing, gpt-5.6-sol implementing; the timestamptz cast fix in the exhaustion test's seed SQL was mine.) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ef7a21b1ad
ℹ️ 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".
| AND (uwp.updated_at, uwp.media_item_id) < (w.updated_at, w.media_item_id) | ||
| AND NOT (e.series_id = ANY(w.seen)) |
There was a problem hiding this comment.
Keep the anchor walk bounded by progress rows
When a profile has a dominant completed series—especially the documented bulk-import case—the recursive step must scan and join every newer row from already-seen series before it can find another anchor. The only supporting index is (user_id, profile_id, updated_at DESC) (migrations/sql/102_catalog_perf_indexes.sql:38-40), so it cannot skip by series or satisfy the new media_item_id tie-break; equal-timestamp imports additionally require sorting that entire timestamp group. Removing the former 500-row limit therefore reintroduces the unbounded 233k-row/44.7s path this query was designed to prevent, potentially across multiple batches; bound the row work or add an access path that can actually jump between series.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
| ORDER BY uwp.updated_at DESC, uwp.media_item_id DESC, | ||
| e.season_number DESC, e.episode_number DESC |
There was a problem hiding this comment.
Preserve episode order for tied completion timestamps
When a bulk import gives multiple completed episodes in one series the same updated_at, placing the unique media_item_id before season and episode number makes the selected anchor depend on an arbitrary content ID rather than the furthest completed episode. For example, with E1 and E3 completed simultaneously and E2 unwatched, choosing E1's ID causes the lateral lookup to return E2, whereas the previous season_number DESC, episode_number DESC tie-break anchored at E3 and returned E4. Put episode order ahead of the unique cursor tie-break, or derive the per-series anchor separately, so same-timestamp imports retain the established progression behavior.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/catalog/nextup_repo.go (1)
391-479: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winExtract the duplicated result SELECT into one string.
Lines 392-421 and lines 425-452 contain the same next-episode lookup, media-file check, watch-progress exclusion, ordering, and
LIMIT $3. Only theAS completed_atalias differs, and that alias is inert for the series-scoped branch. Keep one definition so a change to the next-episode rules cannot apply to only one branch.As per coding guidelines: "Put new code in the package that owns the behavior, extract shared logic instead of duplicating it, and prefer changing existing code over local workarounds."
♻️ Proposed restructuring
- if q.SeriesID != "" { - query := fmt.Sprintf(` - WITH %s - %s - SELECT - next_ep.content_id, - next_ep.series_id, - si.title, - next_ep.season_number, - next_ep.episode_number, - es.updated_at - FROM %s es - ... - ORDER BY es.updated_at DESC - LIMIT $3`, completedEpisodesCTE, inProgressExclusion, sourceTable) - return query, args - } - - resultQuery := fmt.Sprintf(` + resultQuery := fmt.Sprintf(` SELECT next_ep.content_id, next_ep.series_id, si.title, next_ep.season_number, next_ep.episode_number, es.updated_at AS completed_at FROM %s es ... ORDER BY es.updated_at DESC LIMIT $3`, sourceTable) + + if q.SeriesID != "" { + return fmt.Sprintf(` + WITH %s + %s + %s`, completedEpisodesCTE, inProgressExclusion, resultQuery), args + }Keep the global assembly at lines 454-479 unchanged.
🤖 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 391 - 479, In the query-building function, extract the duplicated next-episode result SELECT used by the q.SeriesID branch and the global result query into one shared string definition. Preserve the existing columns, joins, filters, ordering, and LIMIT $3; use the completed_at alias only where the global query requires it, while keeping the series-scoped branch behavior unchanged. Leave the global assembly involving frontier unchanged.Source: Coding guidelines
🧹 Nitpick comments (1)
internal/catalog/nextup_repo_test.go (1)
335-335: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive
ineligibleCountfromnextUpAnchorMaxSeries.The literal 100 exceeds the current batch size of 96, so the test forces a second batch. If
nextUpAnchorMaxSeriesis raised above 100, the test still passes but no longer covers continuation. Tie the fixture size to the constant.♻️ Proposed change
- const ineligibleCount = 100 + const ineligibleCount = nextUpAnchorMaxSeries + 4🤖 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_test.go` at line 335, Update the ineligibleCount fixture in the relevant test to derive its value from nextUpAnchorMaxSeries, ensuring it remains large enough to force continuation into a second batch when the anchor limit changes.
🤖 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.
Outside diff comments:
In `@internal/catalog/nextup_repo.go`:
- Around line 391-479: In the query-building function, extract the duplicated
next-episode result SELECT used by the q.SeriesID branch and the global result
query into one shared string definition. Preserve the existing columns, joins,
filters, ordering, and LIMIT $3; use the completed_at alias only where the
global query requires it, while keeping the series-scoped branch behavior
unchanged. Leave the global assembly involving frontier unchanged.
---
Nitpick comments:
In `@internal/catalog/nextup_repo_test.go`:
- Line 335: Update the ineligibleCount fixture in the relevant test to derive
its value from nextUpAnchorMaxSeries, ensuring it remains large enough to force
continuation into a second batch when the anchor limit changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b8051512-38d5-41ae-a731-353139954824
📒 Files selected for processing (2)
internal/catalog/nextup_repo.gointernal/catalog/nextup_repo_test.go
Review follow-up to the anchor walk. Two issues remained after the batching fix. The walk ordered anchors by (updated_at, media_item_id) and then by (season, episode). media_item_id is unique, so no two rows ever tie on that pair and the season/episode clause was unreachable. For a bulk mark-watched series — every row written with one timestamp — the anchor was therefore whichever content_id sorted highest. With production-shape 18-digit IDs where season 2 was scanned before a season-1 backfill, season 1 sorts higher, so the rail surfaced s01e04: an episode following one the user had already watched. Choosing the series and choosing its anchor episode are now separate steps. The walk still advances on the compound cursor, which is the total order it needs; a lateral then picks the highest (season, episode) among that series' rows sharing pick.updated_at, matching what the series-scoped branch already did. Pinning updated_at instead of re-sorting keeps it an index probe, and both rows carry the same updated_at, so cursor order and the reported CompletedAt are unchanged. Also adds the index the compound cursor needs. idx_uwp_profile_completed stops at updated_at, so the media_item_id half of the seek was a filter and every step re-read the rows tied on one timestamp — the exact shape a bulk mark-watched profile has. Measured by dropping and recreating the index around the shipped query on a synthetic 40k-row profile: 341ms -> 224ms, same plan shape otherwise. Verified against Postgres 18.3. The new DB regression seeds the scanned-out-of-order ID shape and fails on the previous ordering (returns s01e04, wants s02e04); the SQL-shape test pins that media_item_id can no longer gate the episode choice. Part of #592 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Pushed 8d5f3a2 addressing the remaining review findings. Note ef7a21b landed while I was working, which already covers the empty-rail and pagination findings via batching — this commit is scoped to what that didn't reach. Anchor ordering (blocking finding). The walk ordered by Fixed by separating the two orderings: the walk still advances on the compound cursor (the total order it needs), and a lateral picks the highest Cursor index. Added Test coverage. New DB regression seeds the scanned-out-of-order ID shape and fails on the previous ordering (returns s01e04, wants s02e04); a SQL-shape test pins that All verified against a live Postgres 18.3 sandbox, not inferred. Full One finding I did not act on: the per-anchor in-progress suppression scan. In the batched structure it runs once over the ≤96-row CTE rather than per walk step, so the cost I originally measured doesn't apply here. I'd rather leave it than restructure working code on a stale premise — happy to revisit if you'd like it hoisted anyway. 🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/sql/20260811145848_add_nextup_anchor_walk_cursor_index.sql`:
- Around line 20-22: Before the CREATE INDEX CONCURRENTLY statement for
idx_uwp_profile_completed_cursor, conditionally drop the existing index when
pg_index.indisvalid is false, using the catalog to identify the invalid index.
Preserve IF NOT EXISTS so valid existing indexes remain untouched, then recreate
the index with the current definition.
🪄 Autofix
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: 2f115bb3-ce68-448a-863c-c7b7f747abeb
📒 Files selected for processing (3)
internal/catalog/nextup_repo.gointernal/catalog/nextup_repo_test.gomigrations/sql/20260811145848_add_nextup_anchor_walk_cursor_index.sql
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/catalog/nextup_repo.go
| CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_uwp_profile_completed_cursor | ||
| ON public.user_watch_progress USING btree (user_id, profile_id, updated_at DESC, media_item_id DESC) | ||
| WHERE completed = TRUE; |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
: "${DATABASE_URL:?Set DATABASE_URL to a staging PostgreSQL database}"
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "
SELECT c.relname, i.indisvalid, i.indisready
FROM pg_class c
JOIN pg_index i ON i.indexrelid = c.oid
WHERE c.relname = 'idx_uwp_profile_completed_cursor';
"Repository: Silo-Server/silo-server
Length of output: 239
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(git ls-files 'migrations/sql/20260811145848_add_nextup_anchor_walk_cursor_index.sql')"
test -n "$file"
printf '%s\n' "$file"
wc -l "$file"
cat -n "$file"
printf '\nRelated index references:\n'
rg -n -C 3 'idx_uwp_profile_completed_cursor|CREATE INDEX CONCURRENTLY|DROP INDEX CONCURRENTLY' migrations/sqlRepository: Silo-Server/silo-server
Length of output: 20098
🏁 Script executed:
#!/bin/bash
set -euo pipefail
for file in \
migrations/sql/20260719173000_ebook_enrichment_reconcile_cursor.sql \
migrations/sql/20260626023809_media_item_embeddings_model_index.sql \
migrations/sql/20260719090000_ebook_enrichment_jobs.sql
do
printf '\n--- %s ---\n' "$file"
sed -n '1,42p' "$file"
if [ "$file" = migrations/sql/20260719090000_ebook_enrichment_jobs.sql ]; then
sed -n '130,210p' "$file"
fi
doneRepository: Silo-Server/silo-server
Length of output: 7838
🌐 Web query:
PostgreSQL official documentation CREATE INDEX CONCURRENTLY invalid index IF NOT EXISTS behavior
💡 Result:
In PostgreSQL, combining CREATE INDEX CONCURRENTLY with the IF NOT EXISTS clause carries a significant risk: if the index creation process is interrupted or fails, it can leave behind an "invalid" index, which IF NOT EXISTS will then silently ignore in future attempts [1][2]. Official Behavior: The IF NOT EXISTS clause instructs PostgreSQL to skip the creation of an index if a relation (index) with the specified name already exists in the database [1]. If it exists, PostgreSQL issues a notice and does not throw an error [1]. Crucially, the official documentation warns that there is no guarantee the existing index matches the definition of the index you intended to create [1]. Risk with CONCURRENTLY: When you run CREATE INDEX CONCURRENTLY, PostgreSQL first creates an entry for the index in the system catalogs and marks it as "invalid" before beginning the index build [2]. If the operation fails (e.g., due to a lock timeout, deadlock, or interruption), this invalid entry persists in the system [2]. If you subsequently run the same command again with IF NOT EXISTS, PostgreSQL will detect the existing (invalid) index name and skip the command entirely [2]. Because the command finishes successfully (or "successfully" ignores the task), the index remains in its broken, invalid state rather than being fixed or rebuilt [2]. Recommendation: To ensure an index is correctly created, it is safer to avoid relying on IF NOT EXISTS for concurrent builds [2]. Instead, best practices typically involve: 1. Attempting to drop the index (if it exists) by name before creating it [2]. 2. Checking the status of the index (e.g., in pg_index) to confirm it is valid [2]. 3. Manually dropping and recreating the index if it is found to be invalid [2].
Citations:
- 1: https://www.postgresql.org/docs/current/sql-createindex.html
- 2: https://www.shayon.dev/post/2024/225/stop-relying-on-if-not-exists-for-concurrent-index-creation-in-postgresql/
Handle invalid concurrent index retries.
If CREATE INDEX CONCURRENTLY fails, PostgreSQL can leave an invalid index. IF NOT EXISTS then skips the rebuild, and Goose can record the migration as applied without a usable cursor index.
Conditionally drop public.idx_uwp_profile_completed_cursor when pg_index.indisvalid is false before creating the index. Keep IF NOT EXISTS so an existing valid index is preserved.
🧰 Tools
🪛 Squawk (2.61.0)
[warning] 20-20: While regular index creation can happen inside a transaction, this is not allowed when the CONCURRENTLY option is used. Build the index outside any transactions.
(ban-concurrent-index-creation-in-transaction)
🤖 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 `@migrations/sql/20260811145848_add_nextup_anchor_walk_cursor_index.sql` around
lines 20 - 22, Before the CREATE INDEX CONCURRENTLY statement for
idx_uwp_profile_completed_cursor, conditionally drop the existing index when
pg_index.indisvalid is false, using the catalog to identify the invalid index.
Preserve IF NOT EXISTS so valid existing indexes remain untouched, then recreate
the index with the current definition.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8d5f3a2699
ℹ️ 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".
| CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_uwp_profile_completed_cursor | ||
| ON public.user_watch_progress USING btree (user_id, profile_id, updated_at DESC, media_item_id DESC) | ||
| WHERE completed = TRUE; |
There was a problem hiding this comment.
Remove invalid concurrent indexes before retrying
If PostgreSQL is interrupted during CREATE INDEX CONCURRENTLY, it can leave an invalid index with this name; on the next migration attempt, IF NOT EXISTS skips that unusable relation and Goose records the migration as successful, permanently leaving the anchor walk without its intended cursor index. Drop a same-named index when pg_index.indisvalid is false before rebuilding it, as the repository's other concurrent-index migrations do.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
Fixes #592 · Part of the Next Up / sections reliability work (follow-up to #350's perf fixes)
Problem
Marking one long series watched wiped a user's entire Next Up rail (prod incident 2026-08-10, user report + server-side corroboration in #592).
buildListNextUpQuerybounds the global anchor scan atnextUpAnchorMaxRows = 500raw completed rows; a bulk mark-watched wrote 572 completed rows in <2s, all newer than everything else, so the 500-row window contained one series and the rail collapsed to 0 rows. No data was lost — the rail was just unreachable behind the cap.The cap also silently truncates rails organically: a prod profile with 11k completed rows gets 2 Next Up rows from the capped query vs the full 24 without it.
Approach
Bound by distinct series instead of rows. The anchor CTE becomes a recursive skip-scan (loose index scan) walking
idx_uwp_profile_completednewest→oldest, emitting the first row of each not-yet-seen series, stopping atnextUpAnchorMaxSeries = 96(4× the ~24-item rail). One series can then never evict others, regardless of how many of its rows are newest.Load-bearing details:
(updated_at, media_item_id)cursor in seed + step. Bulk marks and history imports stamp many rows across different series with one timestamp; a bareupdated_at <cursor would skip those series. Pinned by a DB-backed test.DateCutoffapply inside both seed and recursive step, so excluded rows neither anchor nor advance the cursor.completed_episodesCTE name.Performance (measured on prod data, PG 18.4, read-only)
The worst-profile regression is the cost of actually finding 96 distinct series instead of giving up after 500 rows; both are far under the 44.7s that motivated #350. Worst case with fewer than 96 completed series is one ordered walk of the profile's completed partial index.
Verification
go build ./...,go vet,gofmt/goimportsclean;golangci-lint run --new-from-merge-base=origin/main ./internal/catalog/...→ 0 issues.WITH RECURSIVE, compound cursor,ANY(w.seen)skip, series bound; series-scoped test asserts its SQL didn't change shape.SILO_TEST_DATABASE_URL), run against a freshly-migrated Postgres 18 sandbox:TestNextUpRepository_GlobalAnchorWalkSurvivesFloodedSeries— 600 same-timestamp completed rows of one series must not evict two older series. Fails against the old query (returns 0 rows), passes with the walk.TestNextUpRepository_GlobalAnchorWalkKeepsSameTimestampSeries— two series completed at an identical timestamp both anchor (pins the compound cursor).TestEpisodeSearchPostgresAndDocumentSource(_vectorsopt-out) fails identically on cleanorigin/mainagainst the same DB — unrelated.Risks / follow-ups
slow querylog is the tripwire.media_item_id, not episode order — the surfaced episode is still always unwatched (downstream LATERAL skips completed/in-progress), only which unwatched episode of that series wins can differ. Noted in a code comment.internal/sections/fetcher.go's Continue Watching scan caps (continueProgressMaxScanned) share the raw-row-bound shape but have no bulk-write path to flood them; left alone.AI Disclosure
WITH %sformat string (series-scoped branch stays plainWITH); the same$4placeholder is legally referenced twice for DateCutoff; confirmed the flood regression test fails against the old query by stashing the fix and re-running. The worst-profile perf regression was measured and judged acceptable versus the correctness bug; documented above rather than hidden.Summary by CodeRabbit