Skip to content

feat(catalog): rework TV recents and poster playback - #561

Merged
Quick104 merged 10 commits into
Silo-Server:mainfrom
Rhainland:feature/home-categories-rework
Aug 27, 2026
Merged

Quick104 merged 10 commits into
Silo-Server:mainfrom
Rhainland:feature/home-categories-rework

Conversation

@Rhainland

@Rhainland Rhainland commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  • Group TV Recently Added entries by exact scan run: a single newly added episode renders as an episode, while multi-episode and legacy additions render as the series.
  • Preserve separate events for repeated scan runs and provide event-specific direct-play targets.
  • Add immutable scan-run provenance to first-seen files and episode-library memberships, including synchronous admin refresh ingestion.
  • Add profile-aware play targets for playable movie, series, season, and episode cards across Home, catalog, search, recommendations, Continue Watching, and season views.
  • Add independent parent-series title navigation for episode cards and a centered accessible play overlay.
  • Preserve Jellyfin /Items/Latest compatibility through an explicit TV-grouping opt-out.
  • Invalidate Recently Added caches across catalog scan-complete events with leading/trailing burst coalescing.

Why

Recently Added previously linked every TV update to the series or season, making a newly arrived episode slower to reach. It also lacked a consistent direct-play interaction across media-card surfaces. This aligns TV additions with Plex-style behavior while preserving existing detail navigation and compatibility clients.

Reliability and architecture

  • Scan provenance is recorded only on first discovery and is never overwritten by rescans or delayed matching.
  • Queue workers cannot claim synchronous admin-refresh scan runs.
  • Direct admin runs heartbeat while active; abandoned direct runs fail instead of being requeued and executed twice.
  • Personalized playback targets are resolved after shared-cache lookup and are never stored in the process-global list cache.
  • Play-target resolution is batched and applies library/profile availability before selecting an episode.
  • Cache generations apply only to Recently Added, protect against stale in-flight refreshes, and retain a trailing invalidation when scan events are debounced.

Validation

Passed:

  • make build
  • database-backed Recently Added grouping, provenance, playable-target, scanqueue, and admin-refresh tests
  • affected Go package suites: internal/scanqueue, internal/adminjob, internal/sections, internal/catalog, internal/scanner, and API handlers
  • focused Go race-detector tests for cache invalidation and direct-scan heartbeats
  • 45 focused frontend card/play-overlay tests
  • make migrate-validate
  • make verify-local-paths
  • golangci-lint run --new-from-rev=main (0 issues)
  • pnpm run lint (0 errors; existing warnings only)
  • pnpm run format:check
  • git diff --check

Repository-wide baseline notes:

  • make test-web: 1,784 tests passed; 36 existing failures remain in appearance/localStorage and settings-realtime tests.
  • make test-go: affected packages pass; existing Jellyfin compatibility process-lock/shared-database and playback-environment failures remain.
  • make lint: the repository-wide baseline currently reports 303 pre-existing findings; changed-line lint reports none.

Manual QA

Verified against an isolated PostgreSQL/Redis stack using real Home and catalog pages:

  • single-episode, multi-episode, repeated-run, and legacy TV events
  • independent poster, parent-series title, and direct-play navigation
  • movie, episode, series, and season play targets
  • unavailable media omitting the play control
  • clean browser console and expected API payloads

Risks

  • The migration adds nullable foreign keys and partial FK indexes without backfilling historical rows.
  • Historical rows intentionally remain series cards because trustworthy scan provenance cannot be reconstructed.
  • Mobile clients are unchanged; all API additions are optional /api/v1 fields.

Review follow-up (Quick104)

Addressed all six functional findings from Quick104's review in 7c26f9ee:

  • enforce effective playback-quality and source-library constraints during play-target resolution;
  • rank series/season targets with one batched read through the configured PostgreSQL or SQLite user store;
  • expose keyboard search selection through real focus in a semantic result list while keeping Play as an independent control;
  • recover stale direct scans from both accepted and running;
  • use top-level concurrent index cleanup on migration retries.

Follow-up validation: make build; affected Go package suites; 13 focused GlobalSearch tests; make migrate-validate; make verify-local-paths; frontend lint/format checks; and changed-line golangci-lint (0 issues).

CodeRabbit follow-up

Addressed CodeRabbit's follow-up review in 4a5fc686:

  • normalize result focus indices and explicitly wrap ArrowUp from an unselected search box to the final result;
  • make the concurrent-index regression assertions whitespace- and statement-boundary-aware, rejecting both blocking ordinary-drop forms;
  • exercise stale accepted direct-run recovery through requested_at while leaving started_at and heartbeat_at unset.

Follow-up review found no material issues. Validation passed: affected Go suites, 13 focused GlobalSearch tests, TypeScript build, migration validation, frontend format checks, local-path checks, and changed-line Go lint (0 issues). ESLint reports 0 errors and one pre-existing warning.

AI Disclosure

  • Tool(s): Codex desktop
  • Model(s): gpt-5.6-sol
  • Involvement: fully AI-generated under human direction and review
  • Adversarial review: Reviewed the full branch for concurrency, cache consistency, access boundaries, scan lifecycle, API contracts, and frontend navigation. The review found dropped trailing cache invalidations, missing library-refresh scan-complete publication, and live direct scans being treated as abandoned; all three were corrected and covered by focused and race/database-backed tests.

Summary by CodeRabbit

  • New Features

    • Added one-click playback overlays to movie, episode, season, recommendation, search, and continue-watching cards.
    • Playback selects accessible content, supports resume behavior, and preserves return navigation.
    • Episode cards link to their series pages while retaining episode details.
    • Added playback identifiers to item, season, section, and browse responses.
    • Improved Recently Added TV sections with episode/series grouping and pagination.
    • Added scan provenance tracking for newly discovered media.
  • Bug Fixes

    • Refreshed catalog results now update more reliably after scans.
    • Improved scan tracking, heartbeat monitoring, and failure handling for direct library and item refreshes.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 99b7ebcc-82d1-4dc5-a796-d327e49da822

📥 Commits

Reviewing files that changed from the base of the PR and between d9ec5e8 and 3c82a48.

📒 Files selected for processing (2)
  • internal/catalog/playable_targets.go
  • internal/catalog/recent_tv.go

📝 Walkthrough

Walkthrough

This PR adds tracked direct scan lifecycles and provenance, resolves accessible playback targets, adds scan-aware recently added TV sections with cache invalidation, and exposes direct-play overlays across web cards and search results.

Changes

Scan lifecycle and provenance

Layer / File(s) Summary
Direct scan execution and provenance
internal/adminjob/..., internal/scanbatch/..., internal/scanner/..., migrations/sql/...
Admin refreshes create and finalize direct scan runs, maintain heartbeats, and persist first-seen scan-run IDs on media files and episode memberships.
Queue and startup integration
internal/scanqueue/..., cmd/silo/main.go
Direct runs bypass worker claims and concurrency counts. Stale direct runs fail as abandoned. Startup wires repositories and catalog cache invalidation.

Playable targets and TV sections

Layer / File(s) Summary
Playable-target resolution
internal/catalog/..., internal/api/handlers/...
The server resolves accessible playback targets for movies, episodes, series, and seasons, then adds play_content_id and episode-series metadata to API responses.
Recently added TV flow and cache invalidation
internal/catalog/recent_tv.go, internal/catalog/catalog_resolver.go, internal/sections/..., internal/jellycompat/...
Recently added TV results use scan-run grouping, snapshots, access filters, pagination, and playable episode selection. Compatibility requests can disable TV event grouping. Scan completion invalidates resolved section caches.

Web playback controls

Layer / File(s) Summary
Shared playback overlay and card integration
web/src/api/types.ts, web/src/components/..., web/src/pages/ItemDetail/...
The web client consumes playable-target fields and renders independent detail and playback links across item, section, recommendation, season, continue-watching, and search cards. Episode headings can link to series pages.

Estimated code review effort: 5 (Critical) | ~120 minutes

Merge Risk: 🔵 Low · up to d9ec5

Search results add an independent Play control, but the current structure may not provide a valid accessible interaction pattern for keyboard and assistive-technology users. The risk is localized and mergeable with explicit owner awareness or a follow-up fix.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 117 functions across 50 files. (8 skipped… 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 clearly and concisely summarizes the PR's primary changes: reworking TV Recently Added behavior and adding poster playback.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 117 functions across 50 files. (8 skipped: 1 unsupported, 7 over the file limit.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@Rhainland
Rhainland marked this pull request as ready for review August 7, 2026 17:42
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Aug 7, 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: 6

🧹 Nitpick comments (9)
internal/catalog/recent_tv.go (2)

347-355: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use slices.Sort instead of a hand-written insertion sort.

Lines 349-353 implement insertion sort. The standard library covers this case and removes the nested loop.

♻️ Proposed change
 func sortedUniqueInts(values []int) []int {
 	values = uniquePositiveInts(values)
-	for i := 1; i < len(values); i++ {
-		for j := i; j > 0 && values[j] < values[j-1]; j-- {
-			values[j], values[j-1] = values[j-1], values[j]
-		}
-	}
+	slices.Sort(values)
 	return values
 }

Add "slices" to the import block.

🤖 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/recent_tv.go` around lines 347 - 355, Replace the
hand-written insertion sort in sortedUniqueInts with the standard library
slices.Sort call after uniquePositiveInts returns. Add the slices import and
preserve the existing returned values and uniqueness behavior.

189-260: 🚀 Performance & Scalability | 🔵 Trivial

Confirm index coverage for the scan-run grouping and the availability EXISTS checks.

The CTE groups episode_libraries by (series_id, first_seen_scan_run_id) and runs a correlated EXISTS against media_files on (episode_id, media_folder_id, missing_since) for every candidate row. filtered is then scanned twice, once for totals and once for page. Without indexes on episode_libraries(media_folder_id, first_seen_at), episode_libraries(first_seen_scan_run_id), and media_files(episode_id, media_folder_id), this becomes a full grouping over the library on every uncached request.

Capture EXPLAIN (ANALYZE, BUFFERS) output for a large TV library before release.

#!/bin/bash
# Description: List indexes declared for episode_libraries and media_files in the migrations.
set -euo pipefail

fd -e sql . migrations/sql --exec rg -n -i 'CREATE (UNIQUE )?INDEX.*(episode_libraries|media_files)' {} +
fd -e sql . migrations/sql --exec rg -n -i 'first_seen_scan_run_id' {} +
🤖 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/recent_tv.go` around lines 189 - 260, Verify index coverage
for the query in the recent TV catalog flow, ensuring indexes support
episode_libraries filtering by media_folder_id and first_seen_at, grouping by
first_seen_scan_run_id, and media_files availability checks on episode_id and
media_folder_id. Add or update migration indexes where coverage is missing, then
capture EXPLAIN (ANALYZE, BUFFERS) for a large TV library to validate the
grouping and repeated filtered scans.
internal/api/handlers/catalog_resources.go (1)

340-350: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract a single-season enrichment helper.

Both sites wrap one seasonResponse in a slice, call enrichSeasonPlayTargets, then read index 0 back. A single-value helper removes the duplicated wrap and unwrap.

♻️ Proposed helper

Add to internal/api/handlers/items.go:

func (h *ItemsHandler) enrichSeasonPlayTarget(r *http.Request, seriesID string, season *seasonResponse) {
	if season == nil {
		return
	}
	wrapped := []seasonResponse{*season}
	h.enrichSeasonPlayTargets(r, seriesID, wrapped)
	*season = wrapped[0]
}

Then simplify both call sites:

-			seasonResponses := []seasonResponse{resp}
-			h.items.enrichSeasonPlayTargets(r, id, seasonResponses)
-			resp = seasonResponses[0]
+			h.items.enrichSeasonPlayTarget(r, id, &resp)
 			writeJSON(w, http.StatusOK, seasonDetailResponse{Season: resp})

Also applies to: 381-383

🤖 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/api/handlers/catalog_resources.go` around lines 340 - 350, Add the
single-value helper enrichSeasonPlayTarget on ItemsHandler, guarding nil seasons
and internally wrapping, enriching, and copying back the seasonResponse. Update
both affected call sites to use this helper directly instead of manually
creating a one-element slice and reading index 0.
internal/api/handlers/items.go (2)

938-947: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Skip non-playable item types before calling the resolver.

listPlayableTargets sends every item to the resolver. PlayableTargetResolver.Resolve discards types other than movie, episode, series, and season, so book, audiobook, and manga items add rows to the unnest arrays without ever producing a target. Filtering in Go keeps the SQL payload proportional to the playable subset on mixed-library browse pages.

🤖 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/api/handlers/items.go` around lines 938 - 947, Update
listPlayableTargets to filter inputs to playable item types—movie, episode,
series, and season—before calling resolvePlayableTargetInputs; continue skipping
nil items and empty ContentID values, and exclude book, audiobook, manga, and
other unsupported types from the SQL payload.

967-982: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm that enrichSeasonPlayTargets must clear unresolved targets.

Line 980 assigns the map lookup unconditionally. If the resolver returns no entry for a season, PlayContentID becomes "". The browse path at Lines 923-925 uses the opposite rule and preserves an existing value. No current caller pre-populates seasonResponse.PlayContentID, so behavior is correct today. Consider matching the browse guard to keep the two paths consistent if a future caller sets the field earlier.

♻️ Optional consistency change
 	for i := range seasons {
-		seasons[i].PlayContentID = targets[seasons[i].ContentID]
+		if seasons[i].PlayContentID == "" {
+			seasons[i].PlayContentID = targets[seasons[i].ContentID]
+		}
 	}
🤖 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/api/handlers/items.go` around lines 967 - 982, Update
enrichSeasonPlayTargets to assign PlayContentID only when
resolvePlayableTargetInputs returns a non-empty target for the season,
preserving any existing value when the lookup is unresolved. Match the guarded
assignment behavior used by the browse path while leaving resolved target
handling unchanged.
internal/catalog/catalog_resolver.go (1)

462-472: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

req.SkipTotal is ignored on the recent-TV path.

RecentTVQuery carries no skip-total flag, and Line 515 always reports TotalExact: true. RecentTVRepository.List therefore always evaluates COUNT(*) over the full filtered CTE, even when the caller set SkipTotal. Every other section path honors the flag. Rail requests that only need the first few items pay for a complete grouping over the library.

Thread SkipTotal into RecentTVQuery and set TotalExact from it.

Also applies to: 511-517

🤖 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/catalog_resolver.go` around lines 462 - 472, Propagate
req.SkipTotal through the recent-TV flow by adding it to RecentTVQuery and
assigning it when constructing the query in the resolver. Update
RecentTVRepository.List to skip the full COUNT(*) work when requested, and set
the response’s TotalExact value from the query flag rather than always returning
true.
internal/api/handlers/sections.go (1)

1241-1262: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Reuse the existing dedup set for the play-target batch.

Lines 1211-1224 already build a deduplicated contentIDs list with the seen map. The new loop iterates allItems again and can pass the same ContentID several times when one item appears in more than one section. Building inputs from the deduplicated set removes the redundant rows in the batch query input.

♻️ Proposed refactor
 	playTargets := map[string]string{}
 	if h.fetcher != nil {
-		inputs := make([]catalog.PlayableTargetInput, 0, len(allItems))
-		for _, item := range allItems {
-			if item == nil || item.ContentID == "" {
-				continue
-			}
-			inputs = append(inputs, catalog.PlayableTargetInput{ContentID: item.ContentID, Type: item.Type})
-		}
+		typeByContentID := make(map[string]string, len(contentIDs))
+		for _, item := range allItems {
+			if item == nil || item.ContentID == "" {
+				continue
+			}
+			if _, ok := typeByContentID[item.ContentID]; !ok {
+				typeByContentID[item.ContentID] = item.Type
+			}
+		}
+		inputs := make([]catalog.PlayableTargetInput, 0, len(contentIDs))
+		for _, id := range contentIDs {
+			inputs = append(inputs, catalog.PlayableTargetInput{ContentID: id, Type: typeByContentID[id]})
+		}
🤖 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/api/handlers/sections.go` around lines 1241 - 1262, Build the
playable-target inputs from the existing deduplicated contentIDs/seen result
created earlier in the handler instead of iterating allItems. Preserve each
target’s required type information using the established item data, and continue
passing the resulting inputs to ResolvePlayableTargets without duplicate
ContentID entries.
internal/sections/resolvedlistcache_test.go (1)

251-254: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer t.Errorf plus a sentinel error inside loader closures.

Both closures call t.Fatal from inside a resolvedListLoader. t.Fatal calls runtime.Goexit, which is only defined behavior on the goroutine that runs the test. Today these loaders run synchronously on the test goroutine, because the entry is a warm hit at the supplied timestamp, so the call never happens. If the cache timing assumptions change and the loader runs on a background refresh goroutine, t.Fatal produces a confusing hang or a misattributed failure rather than a clean assertion.

Returning an error and asserting on it afterwards keeps the failure attributable regardless of which goroutine invokes the loader.

♻️ Proposed refactor for line 251
+	errUnexpectedLoad := errors.New("late old-generation refresh repopulated the active key")
 	active, _, err := getOrRefresh(context.Background(), newKey, base.Add(6*time.Minute), func(context.Context) ([]*models.MediaItem, int, error) {
-		t.Fatal("late old-generation refresh repopulated the active key")
-		return nil, 0, nil
+		return nil, 0, errUnexpectedLoad
 	})

Also applies to: 337-340

🤖 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/sections/resolvedlistcache_test.go` around lines 251 - 254, Replace
t.Fatal calls inside the resolvedListLoader closures around getOrRefresh with
t.Errorf and a sentinel error return, then assert the returned error after
getOrRefresh completes. Apply the same pattern to both affected closures so
failures remain attributable if refresh execution moves to a background
goroutine.
internal/sections/resolvedlistcache.go (1)

445-449: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the default scheduler to remove the duplicated closure.

Lines 446-449 repeat the closure defined at lines 93-96. A named function keeps the two definitions in sync if the scheduling behavior changes.

♻️ Proposed refactor
+func defaultResolvedListScheduleInvalidation(delay time.Duration, callback func()) func() {
+	timer := time.AfterFunc(delay, callback)
+	return func() { timer.Stop() }
+}

Then use it in both places:

-	resolvedListScheduleInvalidation = func(delay time.Duration, callback func()) func() {
-		timer := time.AfterFunc(delay, callback)
-		return func() { timer.Stop() }
-	}
+	resolvedListScheduleInvalidation = defaultResolvedListScheduleInvalidation
🤖 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/sections/resolvedlistcache.go` around lines 445 - 449, Extract the
duplicated scheduling closure into a named default scheduler function,
preserving the time.AfterFunc and timer.Stop behavior. Update both the existing
definition near the earlier scheduler setup and the resolved-list setup around
resolvedListScheduleInvalidation to reference the shared function.
🤖 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/adminjob/direct_scan_run.go`:
- Around line 82-84: Update the Start error path in the direct scan run flow to
transition the accepted run to failed or cancelled before returning the startup
error. Execute that cleanup using a short timeout context derived with
context.WithoutCancel(ctx), so it still runs when the original context has
expired; preserve the existing wrapped error return and handle cleanup failure
according to the repository’s established reliability conventions.

In `@internal/adminjob/item_refresh.go`:
- Around line 500-512: Update the direct-scan flow after completeDirectScan
succeeds to publish EventScanComplete immediately, before folder checks, target
resolution, or metadata refresh. Remove the later duplicate EventScanComplete
publication so the event is emitted exactly once per completed scan.

In `@internal/catalog/catalog_resolver.go`:
- Around line 442-456: Extend recent-TV grouping to recognize media_scope
"video" alongside the existing series condition. Update the logic around
ResolveRecentTVLibraryIDs and RecentTVTarget so video-scoped queries pass
through the TV-resolution path with the same series semantics, while preserving
existing behavior for other media scopes.

In `@internal/catalog/recent_tv_db_test.go`:
- Around line 43-46: Update the t.Cleanup callbacks for the seeded runs,
including runCross and runMissing, to delete their corresponding scan_runs rows
before deleting media_folders. Use each seeded run’s identifiers and preserve
the existing media_items and media_folders cleanup so all related test data is
removed from the shared database.

In
`@migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql`:
- Around line 3-17: Make the migration non-transactional with the Goose NO
TRANSACTION directive, add both nullable columns before constraints, and create
each foreign key as NOT VALID to avoid blocking active ingestion. Build both
partial indexes with CREATE INDEX CONCURRENTLY, then validate each foreign key
after index creation. Update any Down migration to drop these indexes with DROP
INDEX CONCURRENTLY.

In `@web/src/components/GlobalSearch.tsx`:
- Around line 64-116: Update the search result row around the role="option"
container so it does not contain the nested button or CardPlayOverlay
interactive control. Either replace the listbox option pattern with a
non-listbox result container that preserves selection and playback actions, or
keep role="option" while moving the play action outside the listbox and ensuring
the row itself is not an interactive descendant container.

---

Nitpick comments:
In `@internal/api/handlers/catalog_resources.go`:
- Around line 340-350: Add the single-value helper enrichSeasonPlayTarget on
ItemsHandler, guarding nil seasons and internally wrapping, enriching, and
copying back the seasonResponse. Update both affected call sites to use this
helper directly instead of manually creating a one-element slice and reading
index 0.

In `@internal/api/handlers/items.go`:
- Around line 938-947: Update listPlayableTargets to filter inputs to playable
item types—movie, episode, series, and season—before calling
resolvePlayableTargetInputs; continue skipping nil items and empty ContentID
values, and exclude book, audiobook, manga, and other unsupported types from the
SQL payload.
- Around line 967-982: Update enrichSeasonPlayTargets to assign PlayContentID
only when resolvePlayableTargetInputs returns a non-empty target for the season,
preserving any existing value when the lookup is unresolved. Match the guarded
assignment behavior used by the browse path while leaving resolved target
handling unchanged.

In `@internal/api/handlers/sections.go`:
- Around line 1241-1262: Build the playable-target inputs from the existing
deduplicated contentIDs/seen result created earlier in the handler instead of
iterating allItems. Preserve each target’s required type information using the
established item data, and continue passing the resulting inputs to
ResolvePlayableTargets without duplicate ContentID entries.

In `@internal/catalog/catalog_resolver.go`:
- Around line 462-472: Propagate req.SkipTotal through the recent-TV flow by
adding it to RecentTVQuery and assigning it when constructing the query in the
resolver. Update RecentTVRepository.List to skip the full COUNT(*) work when
requested, and set the response’s TotalExact value from the query flag rather
than always returning true.

In `@internal/catalog/recent_tv.go`:
- Around line 347-355: Replace the hand-written insertion sort in
sortedUniqueInts with the standard library slices.Sort call after
uniquePositiveInts returns. Add the slices import and preserve the existing
returned values and uniqueness behavior.
- Around line 189-260: Verify index coverage for the query in the recent TV
catalog flow, ensuring indexes support episode_libraries filtering by
media_folder_id and first_seen_at, grouping by first_seen_scan_run_id, and
media_files availability checks on episode_id and media_folder_id. Add or update
migration indexes where coverage is missing, then capture EXPLAIN (ANALYZE,
BUFFERS) for a large TV library to validate the grouping and repeated filtered
scans.

In `@internal/sections/resolvedlistcache_test.go`:
- Around line 251-254: Replace t.Fatal calls inside the resolvedListLoader
closures around getOrRefresh with t.Errorf and a sentinel error return, then
assert the returned error after getOrRefresh completes. Apply the same pattern
to both affected closures so failures remain attributable if refresh execution
moves to a background goroutine.

In `@internal/sections/resolvedlistcache.go`:
- Around line 445-449: Extract the duplicated scheduling closure into a named
default scheduler function, preserving the time.AfterFunc and timer.Stop
behavior. Update both the existing definition near the earlier scheduler setup
and the resolved-list setup around resolvedListScheduleInvalidation to reference
the shared function.
🪄 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: ba726c78-1907-4274-8203-deddf938457c

📥 Commits

Reviewing files that changed from the base of the PR and between 39efe30 and d3e71fe.

📒 Files selected for processing (54)
  • cmd/silo/main.go
  • internal/adminjob/direct_scan_run.go
  • internal/adminjob/item_refresh.go
  • internal/adminjob/item_refresh_test.go
  • internal/adminjob/library_refresh.go
  • internal/adminjob/library_refresh_scan_run_test.go
  • internal/api/handlers/catalog.go
  • internal/api/handlers/catalog_recent_tv_test.go
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • internal/api/handlers/sections.go
  • internal/api/handlers/sections_test.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/detail.go
  • internal/catalog/episode_library_repo.go
  • internal/catalog/filesplit/filesplit.go
  • internal/catalog/playable_targets.go
  • internal/catalog/playable_targets_db_test.go
  • internal/catalog/recent_tv.go
  • internal/catalog/recent_tv_db_test.go
  • internal/jellycompat/handlers_items.go
  • internal/models/media.go
  • internal/scanbatch/context.go
  • internal/scanbatch/context_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/file_repo_scan_provenance_test.go
  • internal/scanner/scanner.go
  • internal/scanqueue/repository.go
  • internal/scanqueue/repository_direct_runs_db_test.go
  • internal/scanqueue/service.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_recently_added_compat_test.go
  • internal/sections/resolvedlistcache.go
  • internal/sections/resolvedlistcache_test.go
  • internal/sections/types.go
  • migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql
  • web/src/api/types.ts
  • web/src/components/CardPlayOverlay.test.tsx
  • web/src/components/CardPlayOverlay.tsx
  • web/src/components/ContinueWatchingCard.tsx
  • web/src/components/GlobalSearch.test.tsx
  • web/src/components/GlobalSearch.tsx
  • web/src/components/ItemCard.test.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/ItemGrid.tsx
  • web/src/components/RecommendationGrid.test.tsx
  • web/src/components/RecommendationGrid.tsx
  • web/src/components/SeasonAccordion.test.tsx
  • web/src/components/SeasonAccordion.tsx
  • web/src/components/SectionItemCard.test.tsx
  • web/src/components/SectionItemCard.tsx
  • web/src/components/SectionRow.tsx
  • web/src/pages/ItemDetail/SeasonCarousel.test.tsx
  • web/src/pages/ItemDetail/SeasonCarousel.tsx

Comment thread internal/adminjob/direct_scan_run.go Resolved
Comment thread internal/adminjob/item_refresh.go Resolved
Comment thread internal/catalog/catalog_resolver.go Resolved
Comment thread internal/catalog/recent_tv_db_test.go Resolved
Comment thread web/src/components/GlobalSearch.tsx Resolved

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

♻️ Duplicate comments (1)
migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql (1)

48-66: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Drop invalid indexes without blocking active ingestion.

Lines 62 and 84 run regular DROP INDEX inside DO blocks. PostgreSQL takes an ACCESS EXCLUSIVE lock for a normal index drop. A retry after a failed concurrent build can stall scans and file ingestion. (postgresql.org)

Run DROP INDEX CONCURRENTLY IF EXISTS as a top-level Goose statement, then recreate the index concurrently. Do not wrap either statement in StatementBegin.

Proposed fix
-DO $$
-BEGIN
-    ...
-        DROP INDEX public.idx_media_files_first_seen_scan_run_id;
-    ...
-END;
-$$;
+DROP INDEX CONCURRENTLY IF EXISTS public.idx_media_files_first_seen_scan_run_id;

-CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_media_files_first_seen_scan_run_id
+CREATE INDEX CONCURRENTLY idx_media_files_first_seen_scan_run_id

Apply the same change to idx_episode_libraries_first_seen_scan_run_id.

#!/bin/bash
set -euo pipefail

migration='migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql'

# Expect only concurrent index drops for these retry-cleanup indexes.
if rg -n '^\s*DROP INDEX public\.(idx_media_files_first_seen_scan_run_id|idx_episode_libraries_first_seen_scan_run_id);' "$migration"; then
  echo "Found blocking index drop(s)." >&2
  exit 1
fi
rg -n 'DROP INDEX CONCURRENTLY IF EXISTS public\.(idx_media_files_first_seen_scan_run_id|idx_episode_libraries_first_seen_scan_run_id)' "$migration"

Also applies to: 72-88

🤖 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/20260807094340_add_scan_run_provenance_to_media_availability.sql`
around lines 48 - 66, Replace the DO blocks that conditionally drop invalid
indexes for idx_media_files_first_seen_scan_run_id and
idx_episode_libraries_first_seen_scan_run_id with top-level DROP INDEX
CONCURRENTLY IF EXISTS statements. Keep each drop outside Goose
StatementBegin/StatementEnd blocks, and ensure the indexes are recreated
concurrently afterward.
🤖 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.

Duplicate comments:
In
`@migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql`:
- Around line 48-66: Replace the DO blocks that conditionally drop invalid
indexes for idx_media_files_first_seen_scan_run_id and
idx_episode_libraries_first_seen_scan_run_id with top-level DROP INDEX
CONCURRENTLY IF EXISTS statements. Keep each drop outside Goose
StatementBegin/StatementEnd blocks, and ensure the indexes are recreated
concurrently afterward.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f23bc089-183a-4e08-8732-02d97fdc3e40

📥 Commits

Reviewing files that changed from the base of the PR and between d3e71fe and 0b330d7.

📒 Files selected for processing (9)
  • internal/adminjob/direct_scan_run.go
  • internal/adminjob/item_refresh.go
  • internal/adminjob/item_refresh_test.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/recent_tv.go
  • internal/catalog/recent_tv_db_test.go
  • migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql
  • web/src/components/GlobalSearch.test.tsx
  • web/src/components/GlobalSearch.tsx
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/catalog/catalog_resolver.go
  • web/src/components/GlobalSearch.test.tsx
  • internal/adminjob/item_refresh.go
  • web/src/components/GlobalSearch.tsx
  • internal/catalog/recent_tv_db_test.go
  • internal/adminjob/direct_scan_run.go
  • internal/catalog/recent_tv.go

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

I reviewed the current head (0b330d7). Setting aside process and standards concerns, these functional issues should be addressed:

P1

  1. Playable-target resolution ignores the profile's maximum playback quality (internal/catalog/playable_targets.go:105-128). The resolver filters missing files, disabled folders, and library access, but never applies Access.MaxPlaybackQuality. Detail and playback enforce that limit later, so a profile capped at 1080p can receive a Play control and play_content_id for media whose only file is 4K, then reach a watch route with no allowed version. Please apply the same quality predicate used by catalog.FileAllowedByAccess and add a resolver test for a quality-capped profile.

  2. Library-scoped section catalogs lose their library constraint during play-target enrichment (internal/api/handlers/catalog.go:147). For source=section&scope=library, the parser stores the scope in CatalogRequest.LibraryID, while this call passes only req.Query.LibraryIDs, which is empty for section sources. A series card can therefore select an episode from another accessible library. Please pass the effective source-library scope (including req.LibraryID) and cover a series present in multiple libraries.

  3. Keyboard search selection is no longer exposed to assistive technology (web/src/components/GlobalSearch.tsx:273-301). The input's aria-activedescendant and the results' listbox/option semantics were removed, but ArrowUp/ArrowDown still update a visual selectedIndex on generic elements. Screen-reader users consequently receive no announcement of the selected result. Please restore a valid accessible composite/focus pattern while keeping the nested Play action valid, and add coverage for the resulting ARIA/focus behavior.

P2

  1. Series/season resume selection bypasses SQLite-backed user progress (internal/catalog/playable_targets.go:201-204). The resolver joins the PostgreSQL user_watch_progress table directly, so a supported userdb.backend=sqlite deployment cannot use its progress when selecting an episode; an in-progress episode may be ignored. Please resolve progress through the configured user-store abstraction (ideally as a batched overlay) and add backend-conformance coverage.

  2. A crash before a direct scan starts can permanently block that scope (internal/scanqueue/repository.go:315-334,517-533). Direct triggers are excluded from queue workers, and stale cleanup only fails direct runs in running. If the process dies after Create but before Start, the run remains accepted indefinitely and the unique active-scope constraint rejects future refreshes. Please include stale accepted direct runs in recovery or make creation/start atomic, with a crash-window test.

  3. The migration's failed-build recovery can block catalog traffic (migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql:48-88). Although the indexes are built concurrently, the recovery blocks use ordinary DROP INDEX; retrying after an interrupted concurrent build can therefore wait for an ACCESS EXCLUSIVE lock on actively queried/ingested tables. Please move recovery to top-level DROP INDEX CONCURRENTLY IF EXISTS statements before the concurrent creates and validate the retry path.

Copy link
Copy Markdown
Contributor Author

@Quick104 Thanks for the careful review — all six findings are addressed in 7c26f9ee.

Highlights:

  • quality ceilings and library-section scope now constrain play-target selection;
  • resume ranking uses a single batched read through the configured user store, including SQLite coverage;
  • search ArrowUp/ArrowDown now moves real focus through a semantic result list while Play remains an independent control;
  • stale direct runs are recovered from both accepted and running;
  • migration retry cleanup uses top-level DROP INDEX CONCURRENTLY.

Validation passed: build, affected Go suites, 13 focused search tests, migration validation, frontend lint/format, local-path checks, and changed-line Go lint (0 issues). The new PostgreSQL-backed cases are committed for CI; this checkout did not have SILO_TEST_DATABASE_URL configured.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/scanqueue/repository_direct_runs_db_test.go (1)

85-99: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use requested_at to make acceptedDirectID stale.

FailStaleDirect evaluates COALESCE(heartbeat_at, started_at, requested_at) for accepted rows. Keep started_at and heartbeat_at unset for acceptedDirectID, backdate requested_at for it, and backdate started_at and heartbeat_at only for directID and queuedID.

🤖 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/scanqueue/repository_direct_runs_db_test.go` around lines 85 - 99,
The stale-run test setup must distinguish acceptedDirectID from started runs:
update the SQL setup so started_at and heartbeat_at are backdated only for
directID and queuedID, while acceptedDirectID keeps both unset and has
requested_at backdated separately. Preserve the existing stale timestamp and
FailStaleDirect coverage.
🤖 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/scan_run_provenance_test.go`:
- Around line 19-32: Update the regression checks around indexName in the
migration test to normalize SQL whitespace and match complete CREATE INDEX
CONCURRENTLY statements through their statement terminator, preventing similarly
named indexes from satisfying the assertion. Expand the ordinary-drop validation
to reject both DROP INDEX public.<indexName> and DROP INDEX IF EXISTS
public.<indexName> forms, while preserving the requirement that concurrent
cleanup precedes each create.

In `@web/src/components/GlobalSearch.tsx`:
- Around line 263-270: Update moveResultFocus so the modulo result is normalized
to a non-negative index before setSelectedIndex; preserve the empty-items
behavior and ensure ArrowUp with negative nextIndex wraps to the final result
for any non-empty items list.

---

Outside diff comments:
In `@internal/scanqueue/repository_direct_runs_db_test.go`:
- Around line 85-99: The stale-run test setup must distinguish acceptedDirectID
from started runs: update the SQL setup so started_at and heartbeat_at are
backdated only for directID and queuedID, while acceptedDirectID keeps both
unset and has requested_at backdated separately. Preserve the existing stale
timestamp and FailStaleDirect coverage.
🪄 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: 383cdafe-1034-401f-9f8f-4c7aaeb561e2

📥 Commits

Reviewing files that changed from the base of the PR and between 0b330d7 and 7c26f9e.

📒 Files selected for processing (12)
  • internal/api/handlers/catalog.go
  • internal/api/handlers/catalog_playable_targets_test.go
  • internal/api/handlers/items.go
  • internal/catalog/playable_targets.go
  • internal/catalog/playable_targets_db_test.go
  • internal/scanqueue/repository.go
  • internal/scanqueue/repository_direct_runs_db_test.go
  • internal/scanqueue/service.go
  • migrations/scan_run_provenance_test.go
  • migrations/sql/20260807094340_add_scan_run_provenance_to_media_availability.sql
  • web/src/components/GlobalSearch.test.tsx
  • web/src/components/GlobalSearch.tsx
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/api/handlers/catalog.go
  • internal/scanqueue/service.go
  • internal/scanqueue/repository.go
  • web/src/components/GlobalSearch.test.tsx
  • internal/api/handlers/items.go

Comment thread migrations/scan_run_provenance_test.go Resolved
Comment thread web/src/components/GlobalSearch.tsx Resolved

Copy link
Copy Markdown
Contributor Author

@coderabbitai Addressed the outside-diff stale accepted-run test feedback in 4a5fc686. The setup now backdates started_at/heartbeat_at only for started runs; the accepted direct run keeps both null and is made stale through requested_at, so the test exercises the production COALESCE(heartbeat_at, started_at, requested_at) branch. The scanqueue suite passes; the PostgreSQL-backed case remains committed for CI because this checkout has no SILO_TEST_DATABASE_URL configured.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@Rhainland Confirmed. The revised setup exercises the requested_at fallback in COALESCE(heartbeat_at, started_at, requested_at) for an accepted direct run.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

FROM episodes e_play
WHERE page.target_type = 'series'
AND e_play.series_id = page.series_id
AND e_play.season_number = page.anchor_season_number

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.

Recently-added TV play_content_id bypasses the profile playback-quality ceiling

The play_target LATERAL only checks el_play.media_folder_id = ANY($1) and mf_play.missing_since IS NULL. It never applies MaxPlaybackQuality, which PlayableTargetResolver deliberately does enforce (playable_targets.go, the CASE UPPER(BTRIM(mf.resolution)) rank clause).

Worse, this value then wins: catalog.go:222, items.go:923 and sections.go:1444 all only fall back to the resolver when item.PlayContentID is empty, so the enforced target is never used for TV recents.

Concretely: a profile capped at 1080p sees a series card whose Play button targets an episode that only exists as a 2160p file, and playback hard-fails at stream-token time.

Note the cache angle too — PlayContentID set here rides the process-global resolved-list cache, whose key (resolvedListCacheKey -> WriteAccessScopeCacheKey) excludes MaxPlaybackQuality. So making this value quality-dependent in the cached path would leak one profile's ceiling to another. The safe shape is to keep this as a profile-independent anchor hint and let the post-cache PlayableTargetResolver validate/resolve it per profile.

Comment thread internal/scanqueue/service.go Outdated

requeued, err := s.repo.RequeueStaleRunning(ctx, time.Now().UTC().Add(-s.staleAfter))
staleBefore := time.Now().UTC().Add(-s.staleAfter)
failed, err := s.repo.FailStaleDirect(ctx, staleBefore)

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.

requeueStale() aborts the pre-existing stale-run requeue when the new FailStaleDirect errors

The new FailStaleDirect call returns on error, so a transient failure here disables RequeueStaleRunning entirely — behavior that worked before this PR.

A statement timeout or lock contention on scan_runs during a large scan is enough: requeueStale logs a warning and returns, and queue scan runs abandoned by a crashed worker are never requeued for as long as the error persists. The scan queue silently stalls.

Log and continue to RequeueStaleRunning rather than returning.

Comment thread internal/adminjob/direct_scan_run.go Outdated
return nil, nil, fmt.Errorf("create scan run: %w", err)
}
if !created {
return nil, nil, fmt.Errorf("scan scope already has active run %s", run.ID)

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.

Admin item/library refresh now hard-fails whenever any active scan run covers the same scope

When scanqueue.Repository.Create reports created == false (the partial unique index idx_scan_runs_active_scope already has an accepted/running row for the same (media_folder_id, mode, path)), this returns a hard error. Before this PR the same call path just ran IngestSubtree.

Failure case: autoscan enqueues a subtree scan for /media/tv/Show (status accepted, not yet claimed). An admin clicks "Refresh item" on that show and gets scan scope: scan scope already has active run 01J…. Same for two concurrent refreshes of one item, or a retry while an earlier direct run is still inside the 2-minute stale window.

A reasonable fix keeps the old behavior: when the scope is already claimed, proceed with ingestion without owning a scan run (empty scanbatch run ID) and log it. Those files just get NULL provenance, i.e. the documented legacy/series-card path.

Comment thread internal/catalog/playable_targets.go Outdated
}
progress := map[string]userstore.WatchProgress{}
if q.ProgressStore != nil && len(allCandidateIDs) > 0 {
progress, err = q.ProgressStore.ListProgressByMediaItems(ctx, q.ProfileID, allCandidateIDs)

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.

Unbounded candidate fan-out becomes one bind parameter per episode

Resolve returns one row per (card, candidate episode) with no per-card cap, then hands the entire flattened list to ListProgressByMediaItems. The Postgres implementation (internal/userstore/pgstore/progress.go:650-656) emits one placeholder per ID.

Some callers reach BrowseFilters.MaxLimit of 1000. For 100 long-running series averaging 700 episodes, allCandidateIDs holds 70,000 IDs and the generated IN (...) exceeds Postgres' 65535 extended-protocol parameter limit — the request fails outright. Below that ceiling it still ships tens of thousands of rows and params on every list response.

At minimum: dedupe allCandidateIDs and chunk the progress lookup. Better: bound candidates per card in SQL (ROW_NUMBER() OVER (PARTITION BY ord …)) or push the ranking into SQL.

Comment thread web/src/components/GlobalSearch.tsx Outdated
.getElementById(`search-result-${selectedIndex}`)
?.scrollIntoView({ block: "nearest" });
const selectedResult = document.getElementById(`search-result-${selectedIndex}`);
selectedResult?.focus();

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.

Arrow-key selection steals DOM focus, so the user can no longer type to refine the query

The selection effect now calls selectedResult?.focus(), moving DOM focus off the search input onto a result <button>. A button accepts no text, and its onKeyDown handles only ArrowUp/ArrowDown.

Repro: type bre, press ArrowDown once. selectedIndex becomes 0, focus moves to #search-result-0, the input blurs. Now type aking — nothing happens; the keystrokes go to the button and are discarded. The useEffect at line 236 that resets selectedIndex on query change can never fire, because query can no longer change.

The previous aria-activedescendant virtual-focus combobox pattern is the standard here and keeps the Play control independently reachable via Tab.

Comment thread internal/api/handlers/sections.go Outdated
}
inputs = append(inputs, catalog.PlayableTargetInput{ContentID: item.ContentID, Type: item.Type})
}
resolvedTargets, err := h.fetcher.ResolvePlayableTargets(r.Context(), catalog.PlayableTargetQuery{

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.

Section play targets ignore watch progress (no ProgressStore passed)

This PlayableTargetQuery omits ProgressStore, even though SectionHandler.StoreProvider is right there. preferredPlayableTarget then sees an empty progress map, ranks every candidate 1, and returns the lowest-numbered available episode.

So a profile watched through S03E05 gets "resume S03E05" from the series card on /api/v1/catalog (which does pass the store via resolvePlayableTargetInputs) and "play S01E01" from the identical card in a Home rail. Two surfaces, two answers.

Comment thread internal/adminjob/item_refresh.go Outdated
if err := completeDirectScan(ctx, e.scanRuns, scanRun, ingestResult); err != nil {
return nil, fmt.Errorf("scan scope: %w", err)
}
e.publish(cache.EventScanComplete, strconv.Itoa(req.ScanFolderID))

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.

EventScanComplete now published before the metadata refresh

This publish moved from after refreshMetadata to immediately after the scan completes. With the new sections.InvalidateResolvedListCache subscriber wired to this event (cmd/silo/main.go:659), the generation can advance and a rail can rebuild from pre-refresh data.

That freshly-cached entry then holds stale title/poster/type for the full 15-minute resolvedListTTL, because EventMetadataUpdated (published one line later) is not wired to the invalidator.

Same ordering question applies to the new publish in library_refresh.go:435. Either restore the post-refresh ordering, or also invalidate on EventMetadataUpdated.

return nil, false, fmt.Errorf("iterating TV recent libraries: %w", err)
}

if !explicitSeries {

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.

A non-series filter_type is hijacked by TV event grouping

When explicitSeries is false the decision is made purely from library types, ignoring a configured filter_type of movie/episode/season.

A rail configured {"filter_type":"episode"} scoped to library 7 (type series) satisfies "every requested library is type series", so tvScoped is true and RecentTVRepository.List takes over — returning a mix of series cards (multi-episode and legacy events) and episode cards, ignoring the episode-only request. The old buildRecentlyAddedQuery path ran applyConfigTypeFilter and honored it.

Pass the actual FilterType through and bail out to the generic path for any non-empty, non-series value.

Comment thread internal/api/handlers/items.go Outdated

overlaySummaries := h.listOverlaySummaries(r.Context(), result.Items, h.accessFilter(r))
userStates := h.listItemUserStates(r, result.Items)
playTargets := h.listPlayableTargets(r, result.Items, req.Query.LibraryIDs, h.accessFilter(r))

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.

/browse never populates series_id, so the new episode heading link is dead there

writeCatalogBrowseResponse resolves play targets but builds responses through toItemListResponseWithOverlay -> itemListResponseShell, which never sets SeriesID. Only CatalogHandler.catalogItemResponses calls listEpisodeBrowseMetadata/applyEpisodeBrowseMetadata.

So an episode card rendered from a /browse response has item.series_id === undefined, and ItemCard.tsx:232 collapses headingHref to itemHref. Clicking the series title opens the episode's own detail page — silently diverging from the identical card fed by /api/v1/catalog.

// cached entry never leaks one profile's state to another.
func resolvedListCacheKey(resolved ResolvedSection, libraryID *int, libraryIDs []int, filter catalog.AccessFilter) string {
var b strings.Builder
if resolved.SectionType == SectionRecentlyAdded {

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.

Superseded cache generations are retained for the full 15-minute TTL

Advancing resolvedListGeneration only changes future keys. The entries it obsoletes stay in resolvedListCache until expiresAt (15 min) and are only swept opportunistically inside resolvedListSet, at most once per minute.

During a large multi-library rescan the generation advances every 30 s, so up to resolvedListTTL / resolvedListInvalidationInterval = 30 generations of every (library × access-scope) entry are alive at once. With 20 access scopes that is 600 live entries instead of 20 — a 30× memory multiplier that only decays once scanning stops.

InvalidateResolvedListCache should drop the keys it supersedes.

Comment thread internal/catalog/recent_tv.go Outdated
SELECT series_id, 'series'::text, added_at, ''::text, series_id, NULL::integer, NULL::text
FROM series_without_episode_events
),
deduplicated AS (

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.

The deduplicated CTE can never remove a row

episode_events is already GROUP BY e.series_id, el.first_seen_scan_run_id, so (target_id, target_type, event_id) is unique within it; and series_without_episode_events is disjoint from it by construction (its NOT EXISTS requires no present file, which episode_events requires).

Every row therefore has target_rank = 1. The window function adds a partition+sort over the whole event set on every Recently Added page load for no behavioral benefit, and a future reader has to re-derive the disjointness proof to know it is safe to touch. filtered can select straight from all_events.

Comment thread internal/api/handlers/sections.go Outdated
return resp
}

func sectionRequestLibraryIDs(r *http.Request) []int {

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.

Library scope re-derived by sniffing r.URL.Path for "/library/"

Every caller of buildSectionsResponse already parsed a validated libraryID a few lines earlier (HandleLibrarySections at 643, HandleLibrarySectionItems at 665). Recovering it here by substring-matching the URL and re-parsing chi.URLParam(r, "id") is a second, weaker source of truth.

If the route is ever remounted (/libraries/{id}/sections) or the param renamed, play targets silently stop being library-scoped — no error, no failing test, no compile break. Pass libraryID down instead.

return result
}

func sortedUniqueInts(values []int) []int {

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.

Hand-rolled insertion sort and duplicate int-set helpers

sortedUniqueInts implements an insertion sort by hand where slices.Sort does the job, and intersectOptionalInts duplicates the package's existing intersectInts (internal/catalog/query_executor.go:510).

Four new int-set helpers land in a package that already has one, so the intersection semantics now live in two places and can drift.

episodes,
h.items.getAggregateUserData(r, episodes),
)
seasonResponses := []seasonResponse{resp}

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.

Single season wrapped in a slice just to enrich it

Both single-season branches wrap one seasonResponse into a slice, call enrichSeasonPlayTargets, then unwrap seasonResponses[0] — the same three lines at 347-349 and 381-383.

A third single-season path means copying it again, and a reader has to verify seasonResponses[0] is still the same value. A resolveSeasonPlayTarget(r, seriesID, *seasonResponse) helper (or having the enricher take []*seasonResponse) removes both copies.

items.length === 0 ? -1 : prev <= 0 ? items.length - 1 : prev - 1,
);
moveResultFocus(selectedIndex < 0 ? items.length - 1 : selectedIndex - 1);
} else if (e.key === "Enter" && selectedIndex >= 0 && items[selectedIndex]) {

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.

Unreachable Enter branch on the search input

This branch is guarded by selectedIndex >= 0, but selectedIndex only becomes non-negative through moveResultFocus, which immediately moves DOM focus to the result button. The input can therefore never receive an Enter event while the guard holds.

handlePickItem(items[selectedIndex].content_id) at line 312 is dead: Enter on a selected result is handled by the button's native click, and Enter with no selection falls through to form submission. It reads as a second implementation of result activation that no test can exercise.

(If finding #5 is fixed by restoring aria-activedescendant virtual focus, this branch becomes live again and should stay.)

Quick104 and others added 2 commits August 27, 2026 15:52
Fifteen findings from review of this branch, plus follow-ups.

Correctness:

- Recently-added TV play targets bypassed the profile's playback-quality
  ceiling and outranked the profile-aware resolver. The SQL value is now a
  profile-independent anchor hint (PlayableTargetInput.PreferredContentID)
  that PlayableTargetResolver honors only when it clears the same file
  conditions as any other candidate. It cannot be filtered in place: the
  value rides the shared resolved-list cache, whose key excludes
  MaxPlaybackQuality.
- Resolve is keyed by PlayableTargetInput.Key (type + content ID + hint), so
  two recently-added scan-run event cards for one series resolve separately.
- Progress lookups are deduped and batched; candidates stay uncapped so a
  profile deep inside a long-running series still resumes correctly.
- requeueStale no longer aborts RequeueStaleRunning when FailStaleDirect
  errors.
- Admin item/library refresh no longer hard-fails when another scan run
  already covers the scope; it ingests without scan-run provenance instead.
- EventScanComplete is published after the metadata refresh again, so cache
  invalidation cannot repopulate rails from pre-refresh data.
- Section play targets pass a ProgressStore, matching the catalog endpoints.
- A non-series filter_type no longer gets TV event grouping.
- /browse populates series_id, so episode cards link to their series.
- InvalidateResolvedListCache releases the entries it supersedes.
- GlobalSearch keeps keyboard focus in the input via aria-activedescendant,
  so typing still refines the query after ArrowDown. The Play link is a
  sibling of the option, not a child: role="option" is children-presentational
  and would hide it from assistive technology.

Cleanup:

- Drop the dead deduplicated CTE from the recent-TV query.
- Pass the library scope into buildSectionsResponse instead of re-deriving it
  from the URL path.
- Reuse intersectInts and slices.Sort in recent_tv.go.
- Add a single-season play-target helper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts:
#	internal/adminjob/item_refresh_test.go
#	internal/api/handlers/catalog.go
#	internal/api/handlers/catalog_resources.go
#	internal/api/handlers/items.go
#	internal/api/handlers/sections.go
#	internal/models/media.go
#	internal/scanner/file_repo.go
#	internal/scanner/scanner.go
#	web/src/components/ContinueWatchingCard.tsx
#	web/src/components/ItemCard.tsx
#	web/src/components/SectionItemCard.tsx
#	web/src/pages/ItemDetail/SeasonCarousel.tsx
@coderabbitai

coderabbitai Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot removed the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Aug 27, 2026
Quick104 and others added 4 commits August 27, 2026 17:33
The leaf_targets CTE matched movie and episode files through a single
CASE expression, which PostgreSQL cannot drive through either
media_files index; every movie/episode card scanned the whole table
(~10s per section request on a 1.8M-row dev catalog). Splitting the
predicate into type-specific EXISTS branches restores index probes
(10.1s -> 2.2ms for a 16-card page on the shared dev data).

Co-Authored-By: Claude Fable 5 <[email protected]>
The recently-added TV query walked every episode-availability row for
the requested libraries twice: once to aggregate (series, scan run)
events and again inside the series-without-episodes anti-join. On the
shared dev catalog (794K rows in the TV library) that cost ~4.7s per
uncached request. Materialize the qualifying availability rows once and
derive both the event aggregate and the anti-join from that CTE
(4.7s -> 3.1s measured; result-identical on a 500-row page).

Access and name-prefix conditions move from the availability scan to
the event aggregate so the anti-join keeps seeing every series with any
present episode file, preserving the original per-branch semantics.

Co-Authored-By: Claude Fable 5 <[email protected]>
…lumns

The single-pass shape still sorted every availability row (794K in the
shared dev TV library) to aggregate 25.7K historical events per uncached
request. Split the no-prefix path in two: a narrow MAX-only aggregate
that PostgreSQL fuses into a parallel hash aggregate finds and ranks
every event, then the expensive columns (episode counts, anchor
episodes) are computed only for the requested page, driven from the
page keys. rank() keeps added_at ties together so the fully tiebroken
page ordering is unaffected. Measured 3.31s -> 1.99s on shared dev;
result-identical on a 500-row page under a fixed snapshot.

The name-prefix path keeps the single-pass shape: its per-episode title
filter changes which rows belong to each event and cannot move past the
aggregation.

Co-Authored-By: Claude Fable 5 <[email protected]>
PostgreSQL rejects $limit + $offset when both bind parameters reach the
expression untyped (operator is not unique: unknown + unknown); cast
both to bigint.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor

Pushed four performance commits after testing this PR on the shared dev deployment (1.16M episode_libraries rows, 794K in the TV library; 1.77M media_files; 2.1M episodes). Home/section items requests were taking 13–50s and /api/v1/catalog 5–6s.

956d797b0 — playable-target leaf lookups
The leaf_targets CTE matched movie and episode files through one CASE expression, which PostgreSQL cannot drive through either media_files index — every movie/episode card scanned the table. EXPLAIN (ANALYZE, BUFFERS) on dev showed a nested-loop semi join discarding 6.87M rows for an 8-card page, 10.1s. Splitting into type-specific EXISTS branches restores index probes: 10,103ms → 2.2ms, identical results.

c820a8ffa + 39c587fc7 — recently-added TV events
RecentTVRepository.List walked every availability row twice (event aggregate + series_without_episode_events anti-join), ~4.7s per uncached request. First commit shares one materialized pass between both branches (4.7s → 3.3s). Second commit splits the no-prefix path in two phases: a narrow MAX-only aggregate (fuses into a parallel hash aggregate — no 794K-row sort) finds and ranks every event, then the expensive columns (episode counts, anchor picks) are computed only for the requested page. rank() keeps added_at ties together so the fully tiebroken page ordering is unchanged. 3.3s → 2.0s; result-identical on a 500-row page under a pinned snapshot. The name-prefix path keeps the single-pass shape because its per-episode-title filter changes which rows belong to each event.

3c82a4820 — parameter typing
added_rank <= $n + $m fails with untyped bind parameters (operator is not unique: unknown + unknown, SQLSTATE 42725); both casts to bigint. Found live on dev — SQL prototypes with literals can't catch this, which is a good argument for running the SILO_TEST_DATABASE_URL-gated tests on this PR before merge.

Live results on shared dev (server-side duration_ms): section items cache-miss 13–50s → 2.0–2.2s, warm 170–594ms; /api/v1/catalog 5–6s → ~0.6s.

Remaining discussion for this PR: the recent-TV query still makes one full pass over the library's availability rows per cache miss (irreducible for exact results in the current schema). Options if that matters at scale: a covering index (episodes(content_id) INCLUDE (series_id)), denormalizing series_id into episode_libraries, or scanner-maintained incremental event rows. Also observed two concurrent cache misses both recomputing — single-flight on the resolved-list cache would hide scan-time invalidation.

Commands run: go build, go vet, go test ./internal/catalog/ (DB-gated tests skip without SILO_TEST_DATABASE_URL — not run), golangci-lint run --new-from-merge-base=origin/main ./internal/catalog/... (0 issues), live deployment verification above. Not run: full make test-go, DB-backed catalog tests.

AI Disclosure

  • Tool(s): Claude Code
  • Model(s): claude-fable-5
  • Involvement: Fully AI-generated, human-directed (maintainer line-by-line review pending)
  • Adversarial review: result-identity diffs of old vs. new SQL on live dev data (500-row pages, snapshot-pinned against concurrent scan writes), EXPLAIN (ANALYZE, BUFFERS) verification of every plan claim, live deployment measurement of each commit, and a parameterized-path failure (3c82a4820) found and fixed during that live verification.

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit 3242f76 into Silo-Server:main Aug 27, 2026
3 of 4 checks passed
@Rhainland Rhainland mentioned this pull request Oct 13, 2026
13 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants