Skip to content

feat(sections): persist trending_discover via background-refreshed snapshot - #23

Merged
Quick104 merged 14 commits into
mainfrom
feat/trending-section
May 29, 2026
Merged

Quick104 merged 14 commits into
mainfrom
feat/trending-section

Conversation

@Quick104

@Quick104 Quick104 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replaces the in-process 1-hour cache behind the trending_discover home 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).

  • New table trending_discover_snapshots (migration 167) — one row per canonical (source, time_window) holding the ordered, catalog-resolved content IDs, plus refreshed_at / last_status / last_error / entry_count. A failed or empty refresh never clears the last-good list.
  • TrendingRefresher owns 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_discover task — runs on startup + hourly; result summary surfaced in task history. Trigger on demand via POST /api/v1/admin/tasks/refresh_trending_discover/run.
  • Fetcher read path reduced to a single snapshot lookup; per-viewer access filtering unchanged. The fetcher no longer holds upstream fetcher deps.
  • Trakt day/week collapse to one week row.

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

  • Migration was renumbered 166 → 167 after a collision with another branch's 166_trending_blend_collection_type on the shared dev DB (the runner dedupes by integer version and silently skipped the duplicate).

Test Plan

  • Unit tests: canonicalization, refresher 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-lint clean on touched files.
  • Verified live on dev: migration 167 applied, startup task fetched 200 trending titles, matched 148 to the library (status=ok), section renders items.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Trending “discover” sections (TMDB/Trakt) with configurable time windows.
    • Persistent, background-refreshed trending snapshots used for reads (no upstream calls on view).
    • Scheduled refresher task (runs at startup and hourly) that updates and preserves last-good trending lists.
  • Documentation

    • Design and implementation plans for persistent trending snapshots and refresh behavior.
  • Tests

    • New unit tests covering snapshot reading, ID-resolution ordering, refresher behavior, and canonicalization.
  • Chores

    • Database migration adding the trending snapshot table.

Review Change Stack

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

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 91e7cedb-c6fa-4799-8b10-76b06bf744e4

📥 Commits

Reviewing files that changed from the base of the PR and between 644e5f2 and c944c6c.

📒 Files selected for processing (5)
  • internal/sections/fetcher.go
  • internal/sections/trending_read_test.go
  • internal/sections/trending_refresher.go
  • internal/sections/trending_refresher_test.go
  • internal/taskmanager/tasks/refresh_trending_discover.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/taskmanager/tasks/refresh_trending_discover.go
  • internal/sections/trending_refresher.go

📝 Walkthrough

Walkthrough

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

Changes

Section type & recipe

Layer / File(s) Summary
Recipe and SectionType definition
internal/sections/recipes/trending_discover.go, internal/sections/types.go
Adds TrendingDiscoverParams, recipe implementation with validation and presets, and registers SectionTrendingDiscover as valid.

Fetcher read-path and ordering logic

Layer / File(s) Summary
Fetcher implementation and tests
internal/sections/fetcher.go, internal/sections/trending_discover_test.go, internal/sections/trending_read_test.go
Adds TrendingSnapshots getter, routes SectionTrendingDiscover to fetchTrendingDiscover, implements snapshot-based load, orderedTrendingContentIDs resolution/ordering, and tests for ordering and snapshot read behavior.

Snapshot persistence & migration

Layer / File(s) Summary
Snapshot model, repo, migrations, tests
internal/sections/trending_snapshot.go, migrations/167_trending_discover_snapshots.*.sql, internal/sections/trending_snapshot_test.go
Introduces TrendingSnapshot model, TrendingSnapshotRepository with Get/SaveSuccess/RecordAttempt/ListAll, canonical keying, migrations, and canonicalization unit test.

Refresher, task, repo listing, and tests

Layer / File(s) Summary
TrendingRefresher core logic
internal/sections/trending_refresher.go
Implements TrendingRefresher with distinct combo discovery, per-combo fetch (TMDB/Trakt), external-ID resolution, snapshot persistence, and RunOnce result aggregation.
Refresher tests, task, and listing
internal/sections/trending_refresher_test.go, internal/taskmanager/tasks/refresh_trending_discover.go, internal/sections/repo.go
Adds unit tests covering success, failure, empty provider behavior, task that runs RunOnce at startup/hourly, and Repository.ListTrendingDiscoverConfigs to enumerate enabled configs.

Wiring, CLI/task registration, and docs

Layer / File(s) Summary
Router/CMD wiring and documentation
internal/api/router.go, cmd/silo/main.go, docs/superpowers/*
Adds deps.TrendingRefresher, wires snapshot repo into section fetcher, constructs and assigns the refresher in startup, registers the refresh task, and includes design/plan docs and verification steps.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

"🐰 I hopped through configs, snapshots, and queues,
I fetched upstream trends and resolved foreign cues,
I saved the last-good list so the home won't forget,
Now discover stays steady — no more volatile threat! 🥕"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main architectural change: replacing an in-process cache with a persisted, background-refreshed snapshot for the trending_discover feature.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/trending-section

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

Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/sections/fetcher.go Resolved

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

Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/api/router.go 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8ae273 and 2e6f9f6.

📒 Files selected for processing (5)
  • internal/api/router.go
  • internal/sections/fetcher.go
  • internal/sections/recipes/trending_discover.go
  • internal/sections/trending_discover_test.go
  • internal/sections/types.go

Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/sections/fetcher.go Resolved
Quick104 and others added 12 commits May 29, 2026 10:25
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]>
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]>
@Quick104 Quick104 changed the title feat(sections): add Trending Discover home section (TMDB/Trakt, movies + series) feat(sections): persist trending_discover via background-refreshed snapshot May 29, 2026

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

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

Comment thread internal/sections/trending_refresher.go 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
internal/sections/trending_read_test.go (1)

43-52: ⚡ Quick win

Add an explicit error-path test for snapshot reads.

Please add a case where fakeSnapshotGetter.err != nil and assert loadTrendingDiscoverContentIDs returns 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e6f9f6 and 644e5f2.

📒 Files selected for processing (14)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-05-29-trending-discover-persistent-snapshot.md
  • docs/superpowers/specs/2026-05-29-trending-discover-persistent-snapshot-design.md
  • internal/api/router.go
  • internal/sections/fetcher.go
  • internal/sections/repo.go
  • internal/sections/trending_read_test.go
  • internal/sections/trending_refresher.go
  • internal/sections/trending_refresher_test.go
  • internal/sections/trending_snapshot.go
  • internal/sections/trending_snapshot_test.go
  • internal/taskmanager/tasks/refresh_trending_discover.go
  • migrations/167_trending_discover_snapshots.down.sql
  • migrations/167_trending_discover_snapshots.up.sql
✅ Files skipped from review due to trivial changes (1)
  • migrations/167_trending_discover_snapshots.down.sql

Comment thread cmd/silo/main.go Resolved
Comment thread internal/sections/trending_refresher.go Resolved
- 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]>
@Quick104
Quick104 merged commit 97eb83d into main May 29, 2026
37 checks passed
@Quick104
Quick104 deleted the feat/trending-section branch May 29, 2026 15:35
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
feat(sections): persist trending_discover via background-refreshed snapshot
Quick104 added a commit that referenced this pull request Jun 11, 2026
feat(sections): persist trending_discover via background-refreshed snapshot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant