Skip to content

fix(catalog): bound Next Up anchors by distinct series, not rows - #593

Merged
Quick104 merged 3 commits into
mainfrom
fix/nextup-anchor-series-skip-scan
Aug 11, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/nextup-anchor-series-skip-scan

Conversation

@Quick104

@Quick104 Quick104 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

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). buildListNextUpQuery bounds the global anchor scan at nextUpAnchorMaxRows = 500 raw 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_completed newest→oldest, emitting the first row of each not-yet-seen series, stopping at nextUpAnchorMaxSeries = 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:

  • Compound (updated_at, media_item_id) cursor in seed + step. Bulk marks and history imports stamp many rows across different series with one timestamp; a bare updated_at < cursor would skip those series. Pinned by a DB-backed test.
  • Hidden-items filter and DateCutoff apply inside both seed and recursive step, so excluded rows neither anchor nor advance the cursor.
  • The series-scoped branch (show-detail tile) is untouched — intentionally unbounded, anchors on the series' last completed episode regardless of age.
  • Downstream SQL (eligible_series exclusion, next-episode LATERAL) unchanged; the walk feeds the same completed_episodes CTE name.

Performance (measured on prod data, PG 18.4, read-only)

Profile Old (row cap) New (series walk)
Flooded incident profile ~15ms, 0 rows (the bug) 0.5ms, correct rail
Heavy organic profile (11k rows, 293 series) 181ms, 2 rows (truncated) 102ms, full 24 rows
Worst bulk-import profile (23k rows, 271 series) 84ms 210ms

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/goimports clean; golangci-lint run --new-from-merge-base=origin/main ./internal/catalog/... → 0 issues.
  • Unit tests updated: global query asserts WITH RECURSIVE, compound cursor, ANY(w.seen) skip, series bound; series-scoped test asserts its SQL didn't change shape.
  • New DB-backed regression tests (skip without 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).
  • Pre-existing failure TestEpisodeSearchPostgresAndDocumentSource (_vectors opt-out) fails identically on clean origin/main against the same DB — unrelated.
  • Generated SQL (not hand-transcribed) EXPLAIN ANALYZEd read-only against the production profiles in the table above.

Risks / follow-ups

  • Worst-profile latency regressed 84→210ms. If the tail grows, the escape hatch is a scan-depth cutoff, not a row cap. The slow query log is the tripwire.
  • Within a bulk-marked series where all timestamps are equal, the anchor's tie-break is 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

  • Tool(s): Claude Code (orchestration, diagnosis, review, verification), Codex CLI (implementation)
  • Model(s): claude-fable-5, gpt-5.6-sol
  • Involvement: fully AI-generated, human-operated
  • Adversarial review: Claude reviewed the Codex diff line-by-line against the brief. Found and verified acceptable: the WITH RECURSIVE prefix is emitted via the shared WITH %s format string (series-scoped branch stays plain WITH); the same $4 placeholder 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

  • Bug Fixes
    • Improved the global “Next Up” list so series with many recent completions no longer crowd out other series.
    • Hidden and outdated items are now consistently excluded while building recommendations.
    • Results with matching timestamps are ordered consistently for more reliable display.
    • Global results continue scanning eligible history when needed, up to a safe limit.
    • Series-specific “Next Up” views continue to return complete results without the global limit.

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]>
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Next Up anchor selection

Layer / File(s) Summary
Global recursive anchor walk
internal/catalog/nextup_repo.go, migrations/sql/20260811145848_add_nextup_anchor_walk_cursor_index.sql
Global queries walk eligible completion rows by compound timestamp and media-item cursors. Each batch selects up to 96 distinct series and returns frontier metadata. Series-scoped queries remain unbounded and non-recursive. A partial cursor index supports completed-row traversal.
Query shape validation
internal/catalog/nextup_repo_test.go
Query tests validate deterministic ordering, recursive pagination, shared cutoff filters, hidden-item filtering, episode ordering, continuation arguments, and series-scoped behavior.
Integration fixtures and regression coverage
internal/catalog/nextup_repo_test.go
PostgreSQL fixtures and tests cover bulk-completed ordering, flooded series, equal timestamps, ineligible series, exhausted history, cleanup, and returned content IDs.

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
Loading

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: limiting Next Up anchor scanning by distinct series instead of completed rows.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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 fix/nextup-anchor-series-skip-scan

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Aug 11, 2026

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

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

327-344: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Guard the parallel slice lengths.

unnest pads shorter arrays with NULL. If a future caller passes slices of different lengths, this helper inserts rows with a NULL content_id or series_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

📥 Commits

Reviewing files that changed from the base of the PR and between 881c968 and da84cbe.

📒 Files selected for processing (2)
  • internal/catalog/nextup_repo.go
  • internal/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)

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.

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

Suggested change
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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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]>
@Quick104

Copy link
Copy Markdown
Contributor Author

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 ListNextUp loops: run a batch, keep eligible results, resume below the frontier until the requested Limit is filled or history is exhausted.

Loop invariants:

  • Pagination works: jellycompat's Limit + StartIndex is filled across batches, not capped at one walk.
  • Termination: frontier n < 96 ⇒ the walk ran out of history before its budget ⇒ terminal. No frontier row at all ⇒ empty history ⇒ terminal.
  • Runaway guard: 10 batches max (960 visited series per call), and hitting the cap with results still short logs a warning with profile/batches/results — no silent truncation.
  • Order preserved: every batch resumes strictly below the previous compound (updated_at, media_item_id) frontier, so appended batches keep the rail's recency order.
  • Series-scoped queries (show-detail tile) keep their single-shot shape, byte-identical SQL — pinned by test.

Verification (same sandbox DB + read-only prod methodology as the PR body):

  • New DB-backed regression: 100 fully-watched (ineligible) series newest in history must not hide 2 older series with eligible next episodes — fails on the previous commit (returns 0 rows), passes now; verified by running the new test against da84cbe in a scratch worktree.
  • Exhaustion test: an all-caught-up profile returns empty without spinning to the batch cap.
  • Generated batch-1 SQL EXPLAINed on the worst prod profile: 234ms, frontier row correctly reports n=96 + 96-series seen array; subsequent batches only run when a page is short.
  • go build, go vet, gofmt clean; golangci-lint --new-from-merge-base → 0 issues; full catalog suite green except the pre-existing TestEpisodeSearchPostgresAndDocumentSource failure that reproduces on clean main.

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

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

Comment on lines +369 to +370
AND (uwp.updated_at, uwp.media_item_id) < (w.updated_at, w.media_item_id)
AND NOT (e.series_id = ANY(w.seen))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread internal/catalog/nextup_repo.go Outdated
Comment on lines +343 to +344
ORDER BY uwp.updated_at DESC, uwp.media_item_id 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 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 👍 / 👎.

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

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 win

Extract 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 the AS completed_at alias 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 win

Derive ineligibleCount from nextUpAnchorMaxSeries.

The literal 100 exceeds the current batch size of 96, so the test forces a second batch. If nextUpAnchorMaxSeries is 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

📥 Commits

Reviewing files that changed from the base of the PR and between da84cbe and ef7a21b.

📒 Files selected for processing (2)
  • internal/catalog/nextup_repo.go
  • internal/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]>
@Quick104

Copy link
Copy Markdown
Contributor Author

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 (updated_at, media_item_id) then (season, episode). Since media_item_id is unique, nothing ever ties on that pair, so the season/episode clause was unreachable — for a bulk mark-watched series (all rows one timestamp) the anchor was just the highest content_id. With production-shape 18-digit IDs where season 2 was scanned before a season-1 backfill, that surfaced s01e04 instead of s02e04 — an episode following one already watched.

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 (season, episode) among rows sharing pick.updated_at. Pinning updated_at rather than re-sorting keeps it an index probe; both rows carry the same updated_at, so cursor order and CompletedAt are unchanged.

Cursor index. Added idx_uwp_profile_completed_cursor. The existing index stops at updated_at, so the media_item_id half of the seek was a filter and each step re-read every row tied on one timestamp — exactly the bulk mark-watched shape. Dropping/recreating it around the shipped query on a synthetic 40k-row profile: 341ms → 224ms, same plan shape.

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 media_item_id can't gate the episode choice again.

All verified against a live Postgres 18.3 sandbox, not inferred. Full NextUp suite passes. Two unrelated failures exist on this branch and on da84cbe3e alike — TestEpisodeSearchPostgresAndDocumentSource and the jellycompat TestBeginWebOperation* pair.

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef7a21b and 8d5f3a2.

📒 Files selected for processing (3)
  • internal/catalog/nextup_repo.go
  • internal/catalog/nextup_repo_test.go
  • migrations/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

Comment on lines +20 to +22
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;

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.

🚀 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/sql

Repository: 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
done

Repository: 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:


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.

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

Comment on lines +20 to +22
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;

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 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 👍 / 👎.

@Quick104
Quick104 merged commit e77d9e9 into main Aug 11, 2026
7 of 8 checks passed
@Quick104
Quick104 deleted the fix/nextup-anchor-series-skip-scan branch August 11, 2026 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Next Up rail wiped out after bulk mark-watched (row-capped anchor scan evicts all other series)

1 participant