Repository navigation
feat(sections): persist trending_discover via background-refreshed snapshot - #23
Conversation
A library-agnostic home section that surfaces external global trending
(TMDB or Trakt, admin-selectable) mixing movies + series, matched to
titles in the viewer's enabled libraries. TMDB uses /trending/all/{window}
(natively mixed); Trakt merges trending movies + shows. Fetched live with
a 1h in-process cache, so no background job or stored collection — and no
per-library duplication.
Appears in the admin section gallery via its recipe presets (TMDB Trending
Today/This Week, Trakt Trending); featured -> hero via the existing flag.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds a persisted, background-refreshed "trending_discover" section: recipe/type registration, snapshot repository + migration, fetcher read-path using persisted snapshots, a TrendingRefresher that refreshes snapshots from TMDB/Trakt and resolves external IDs, task scheduling, and tests/docs. ChangesSection type & recipe
Fetcher read-path and ordering logic
Snapshot persistence & migration
Refresher, task, repo listing, and tests
Wiring, CLI/task registration, and docs
Sequence Diagram (high-level refresher flow) sequenceDiagram
participant Refresher as TrendingRefresher
participant SectionRepo as SectionRepo
participant Provider as TMDB/Trakt
participant Resolver as CatalogResolver
participant SnapRepo as TrendingSnapshotRepository
Refresher->>SectionRepo: ListTrendingDiscoverConfigs()
Refresher->>Provider: Fetch trending entries (per combo)
Provider-->>Refresher: entries
Refresher->>Resolver: Batch resolve external IDs -> content IDs
Resolver-->>Refresher: ordered contentIDs
Refresher->>SnapRepo: SaveSuccess / RecordAttempt (upsert snapshot)
SnapRepo-->>Refresher: ack
Estimated code review effort 🎯 4 (Complex) | ⏱️ ~45 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2e6f9f6b4f
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/sections/fetcher.go`:
- Around line 2424-2428: The code calls f.Clock.Now() directly when reading the
editorial cache (around ensureEditorialCandidateCache()/cache.get) which can
panic if Fetcher is zero-valued; replace that direct call with the nil-safe
helper f.now() used elsewhere in this file so the cache key/timestamp uses
f.now() instead of f.Clock.Now() before invoking cache.get(cacheKey, now).
- Around line 2507-2511: resolveTrendingDiscoverIDs currently treats any entry
with e.mediaType != "tv" as a movie, which incorrectly batches TMDB results with
media_type "person" into movieBatch; update the loop over entries to explicitly
handle only "tv" and "movie" values: if e.mediaType == "tv" use seriesBatch,
else if e.mediaType == "movie" use movieBatch, otherwise skip/continue so
unknown types are not batched; reference the entries iteration and the
movieBatch/seriesBatch assignment to locate the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 4550bad8-59a3-4062-82f0-edbbed33f0fb
📒 Files selected for processing (5)
internal/api/router.gointernal/sections/fetcher.gointernal/sections/recipes/trending_discover.gointernal/sections/trending_discover_test.gointernal/sections/types.go
Replace the in-process 1h trending cache with a background-refreshed, persisted snapshot for reliability under upstream failure and sync-run observability. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extract newTrendingEntry, reuse orderMediaItems, and collapse concurrent cache-miss loads with singleflight. Baseline for the persistent snapshot work. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The shared dev DB already recorded version 166 (166_trending_blend_collection_type from another branch), so the integer-version migration runner silently skipped our 166 and the table was never created — the trending section errored out empty. 167 is the next free version. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 644e5f2. Configure here.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/sections/trending_read_test.go (1)
43-52: ⚡ Quick winAdd an explicit error-path test for snapshot reads.
Please add a case where
fakeSnapshotGetter.err != niland assertloadTrendingDiscoverContentIDsreturns that error 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/sections/trending_read_test.go` around lines 43 - 52, Add a test that exercises the error path of the snapshot reader: create a Fetcher with TrendingSnapshots set to fakeSnapshotGetter{err: someErr} (e.g., errors.New("boom")), call loadTrendingDiscoverContentIDs(ctx, "tmdb", "week"), and assert the returned error is the same error and that ids is nil; implement this as a new test function (e.g., TestLoadTrendingDiscoverContentIDsError) alongside the existing TestLoadTrendingDiscoverContentIDsNotFound and use t.Fatalf or t.Error to fail if err does not equal the injected error or ids is not nil.
🤖 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 `@cmd/silo/main.go`:
- Around line 1304-1306: The trending refresh task is registered via
taskMgr.Register(tasks.NewRefreshTrendingDiscoverTask(trendingRefresher)) before
Trakt is wired in api.NewRouter, causing a startup race; fix by delaying
registration until after Trakt wiring or wiring Trakt earlier: either move the
taskMgr.Register call so it executes after api.NewRouter returns (where
trendingRefresher has Trakt injected) or ensure the Trakt client is initialized
and injected into trendingRefresher prior to calling taskMgr.Register; update
the startup sequence around trendingRefresher, taskMgr.Register, and
api.NewRouter accordingly.
In `@internal/sections/trending_refresher.go`:
- Around line 192-196: The current code calls
r.TraktTrending.GetCollectionPreset twice and only treats an error when both
movieErr and showErr are non-nil, which allows a partial snapshot to be saved;
change the post-fetch check to treat any single error as fatal: after calling
r.TraktTrending.GetCollectionPreset for "movie" and "tv" inspect movieErr and
showErr and if either is non-nil return an error (e.g. wrap both errors into a
single fmt.Errorf or use fmt.Errorf with details for movieErr/showErr) so the
function exits without saving movies or shows; ensure you reference the existing
symbols (r.TraktTrending.GetCollectionPreset, movieErr, showErr, movies, shows)
so no partial write occurs.
In `@internal/taskmanager/tasks/refresh_trending_discover.go`:
- Around line 3-7: Guard the t.refresher field before dereferencing: in the task
execution function (the method where t.refresher is accessed in
refresh_trending_discover.go) add a nil-check (if t.refresher == nil) and return
a controlled error (e.g., fmt.Errorf("missing refresher dependency") or the
task's standard error type) instead of proceeding; apply this check at the
locations where t.refresher is used (the block around the current dereference at
lines ~47-53) so the task fails gracefully when wiring is incomplete.
---
Nitpick comments:
In `@internal/sections/trending_read_test.go`:
- Around line 43-52: Add a test that exercises the error path of the snapshot
reader: create a Fetcher with TrendingSnapshots set to fakeSnapshotGetter{err:
someErr} (e.g., errors.New("boom")), call loadTrendingDiscoverContentIDs(ctx,
"tmdb", "week"), and assert the returned error is the same error and that ids is
nil; implement this as a new test function (e.g.,
TestLoadTrendingDiscoverContentIDsError) alongside the existing
TestLoadTrendingDiscoverContentIDsNotFound and use t.Fatalf or t.Error to fail
if err does not equal the injected error or ids is not nil.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 00f9a0dd-7f57-49bf-8495-61f2e2c6fccc
📒 Files selected for processing (14)
cmd/silo/main.godocs/superpowers/plans/2026-05-29-trending-discover-persistent-snapshot.mddocs/superpowers/specs/2026-05-29-trending-discover-persistent-snapshot-design.mdinternal/api/router.gointernal/sections/fetcher.gointernal/sections/repo.gointernal/sections/trending_read_test.gointernal/sections/trending_refresher.gointernal/sections/trending_refresher_test.gointernal/sections/trending_snapshot.gointernal/sections/trending_snapshot_test.gointernal/taskmanager/tasks/refresh_trending_discover.gomigrations/167_trending_discover_snapshots.down.sqlmigrations/167_trending_discover_snapshots.up.sql
✅ Files skipped from review due to trivial changes (1)
- migrations/167_trending_discover_snapshots.down.sql
- Interleave Trakt movies/shows by rank so the mixed row shows both types instead of burying all series past the display limit. - Treat any Trakt sub-fetch failure as fatal (errors.Join) so a partial result never overwrites the last-good snapshot with a media type missing. - Skip non-title entries (TMDB trending/all returns media_type "person") in both ID batching and ordering so they can't match an unrelated library title. - Guard the refresh task against a nil refresher. - Tests: person skip, Trakt interleave, Trakt partial-failure preserves last-good, snapshot read error propagation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
feat(sections): persist trending_discover via background-refreshed snapshot
feat(sections): persist trending_discover via background-refreshed snapshot

Summary
Replaces the in-process 1-hour cache behind the
trending_discoverhome section with a background-refreshed, persisted snapshot, so reads never call the upstream provider and refresh history is observable (the synced-record pattern used by collections).trending_discover_snapshots(migration167) — one row per canonical(source, time_window)holding the ordered, catalog-resolved content IDs, plusrefreshed_at/last_status/last_error/entry_count. A failed or empty refresh never clears the last-good list.TrendingRefresherowns the upstream fetch + external-ID resolution (moved out of the fetcher). It enumerates only the(source, window)combos used by enabled sections, so a dormant feature makes zero upstream calls.refresh_trending_discovertask — runs on startup + hourly; result summary surfaced in task history. Trigger on demand viaPOST /api/v1/admin/tasks/refresh_trending_discover/run.day/weekcollapse to oneweekrow.Why this approach
Reliability under upstream failure + observability were the goals. A lazy cache (even persisted/Redis) still blocks a request at TTL expiry and gives no sync history; a library-scoped collection would reintroduce per-library duplication (trending is library-agnostic). A dedicated background-refreshed snapshot satisfies both without that cost. Design:
docs/superpowers/specs/2026-05-29-trending-discover-persistent-snapshot-design.md.Notes
166 → 167after a collision with another branch's166_trending_blend_collection_typeon the shared dev DB (the runner dedupes by integer version and silently skipped the duplicate).Test Plan
RunOnce(ordered IDs, ok/empty/error transitions, failure preserves last-good, Trakt collapse), read path reads snapshot without touching upstream.go build ./...,go vet,golangci-lintclean on touched files.status=ok), section renders items.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests
Chores