Skip to content

Add poster-aware collection templates and async sync queueing - #1

Merged
Quick104 merged 10 commits into
mainfrom
codex/collections-template-port
May 24, 2026
Merged

Quick104 merged 10 commits into
mainfrom
codex/collections-template-port

Conversation

@Quick104

@Quick104 Quick104 commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Ported built-in collection templates to include TMDB discover and franchise coverage, plus poster assets and template metadata.
  • Propagated template defaults into created collections, including sort order, poster URL, and collection management behavior.
  • Added poster-aware apply/import flows so existing collections can be reused, posters are preserved or applied deterministically, and large template bundle syncs can be queued asynchronously.
  • Tightened collection sync behavior for MDBList, TMDB, and Trakt sources by using shared limit helpers and more accurate sync accounting.
  • Documented the collection template poster generation workflow in the admin wiki.

Testing

  • Not run (not requested).
  • Added/updated unit coverage for collection template definitions and poster asset expectations in internal/collections/templates/templates_test.go.
  • No frontend or integration verification run.

Summary by CodeRabbit

  • New Features

    • Choose collection poster (server default or custom URL) when applying templates or importing; apply flow can queue template-bundle apply jobs and shows "sync queued" info.
  • Improvements

    • Bundled template posters can be persisted to public asset storage; admin-uploaded posters are preserved while template-origin posters are tracked and refreshable. Increased item limits (UI and backend) and clearer sync/timeout reporting; live job status banner for template applies.
  • Tests

    • Added template asset and poster-upload unit tests.
  • Documentation

    • Added poster generation workflow and expanded multi-repo guidance.

Review Change Stack

Quick104 and others added 4 commits May 22, 2026 23:53
Append the Phase-2 catalog from the collection-templates expansion plan:

- 18 Popular by Genre (sort_order 5001..5018, daily 0 4 * * *,
  popularity.desc with vote_count_gte=300)
- 18 Top Rated by Genre (sort_order 6001..6018, weekly 0 5 * * 0,
  vote_average.desc with vote_count_gte=1000)
- 1 Kids Movies (sort_order 9050, weekly, Family genre with
  certification_lte=PG)

Adds TestPhase2DiscoverTemplatesUseExpectedBands to pin the band ranges
and the TMDB query parameters that define each section.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase-3 of the collection-templates expansion. Adds ten curated movie
franchises plus a generic placeholder template, all backed by Agent B's
tmdb_collection source. Templates land in the 7000s sort-order band.

Verified TMDB collection IDs (via api.themoviedb.org/3/collection/{id}):
  - 10        Star Wars Collection (9 films)
  - 645       James Bond Collection (25 films)
  - 1241      Harry Potter Collection (8 films) — used for "Wizarding World"
  - 9485      The Fast and the Furious Collection (12 films)
  - 119       The Lord of the Rings Collection (3 films)
  - 121938    The Hobbit Collection (3 films)
  - 328       Jurassic Park Collection (7 films)
  - 295       Pirates of the Caribbean Collection (5 films)
  - 87359     Mission: Impossible Collection (8 films)
  - 535313    Godzilla Collection (3 films) — used for "MonsterVerse"

Plan corrections / skips:
  - MCU (plan ID 86311) resolves to "The Avengers Collection" (6 films),
    not the full Marvel Cinematic Universe. TMDB has no umbrella MCU
    collection. Skipped per the no-invent-IDs rule. Sort slot 7001 left
    open.
  - DC Extended Universe (plan ID 573436) resolves to "Spider-Man:
    Spider-Verse Collection" — unrelated. No DCEU umbrella exists on
    TMDB. Skipped. Sort slot 7005 left open.
  - Wizarding World (plan ID 1241) is TMDB's Harry Potter octalogy;
    Fantastic Beasts lives in a separate collection (435259). Used as-is
    with description noting the scope.
  - MonsterVerse (plan ID 535313) is labelled "Godzilla Collection" but
    contains the three Legendary MonsterVerse Godzilla films, which is
    the closest TMDB representation. Used as-is.

The placeholder template ships with CollectionID=0 and an empty sync
schedule so it can be applied without a valid franchise ID; admins edit
the resulting collection's source_config before the first sync.
…ection

Agent F's code review surfaced a critical gap: every Phase 1-3 template
ships a non-zero `DefaultSortOrder` in the documented PMM-style bands
(1000s charts, 2000s best-of-year, 3000s awards, 4000s streaming,
5000s popular by genre, 6000s top rated by genre, 7000s franchises,
8000s seasonal, 9000s misc/kids) and the test suite pins those values,
but none of the four `createCollectionFromTemplate` dispatch paths
forwarded the rank into `catalog.CreateLibraryCollectionInput.SortOrder`.
Applying any template — bundled or one-off — landed the new collection at
SortOrder 0, defeating the band scheme entirely.

Fix: add `SortOrder int` to each request struct
(`importMDBListRequest`, `importTMDBRequest`, `importTMDBFranchiseRequest`,
`importTMDBDiscoverRequest`) and forward `tmpl.DefaultSortOrder` →
`req.SortOrder` → `CreateLibraryCollectionInput.SortOrder` end-to-end.

The pre-existing `SourceTrakt` path is unchanged — no Trakt template
currently sets a non-zero `DefaultSortOrder` so the gap is dormant
there; revisit if/when a Trakt template needs ordering.

No new unit test: the fix is a per-struct field forward whose
end-to-end exercise requires the live repository. Adding a fake repo
to test the propagation would be a refactor beyond this fix's scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Add poster URLs through collection import and template apply flows
- Queue large template bundle syncs and preserve existing collection posters
- Update template bundle assets, docs, and limit handling
@Quick104

Copy link
Copy Markdown
Contributor Author

@codex

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

ℹ️ 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/usercollections/sync.go Resolved
- add poster_from_template to collection records and update flows
- preserve template-applied posters while keeping admin uploads sticky
- improve template bundle sync/status reporting and MDBList limit handling
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds poster-origin tracking and propagation, centralizes source-fetch limits and scan-depth reporting for syncs, expands template catalog and tests, refactors template-bundle apply with async queueing and panic recovery, persists user collection PosterURL, and adds frontend poster selection UI and related API/type wiring.

Changes

Template Poster Management and Sync Refinement

Layer / File(s) Summary
Database schema and core model
migrations/134_*, internal/models/library_collection.go, internal/catalog/library_collection_repo.go
Adds poster_from_template column; model and repo inputs/scan updated to persist and conditionally update poster origin marker.
Fetch limit helpers & metadata caps
internal/collectionutil/collectionutil.go, internal/metadata/tmdb/client.go, internal/metadata/trakt/client.go
Adds SourceFetchLimit and ItemLimitReached; increases TMDB/Trakt preset max results from 100→500.
Template catalog & tests
internal/collections/templates/builtin.go, internal/collections/templates/templates_test.go
Adds genre-based Discover templates (5000s/6000s), Kids and Franchise templates (7000s); reorganizes bundles; tests validate poster path prefixes, on-disk poster assets, bundle reachability, and Phase-2/Phase-3 band invariants.
Library collection sync refactor
internal/catalog/library_collection_service.go
MDBList/TMDB/Trakt syncs use unified fetch limits, track scanned entries, detect limit-reached early, and include scan-depth in completion messages/metrics.
Usercollections sync refactor
internal/usercollections/sync.go
Refactors resolution to resolveMatchedWithLimit, reports sourceTotal/scanned, and appends “item limit reached after N scanned” when applicable.
LibraryCollection handler: poster orchestration
internal/api/handlers/library_collections.go
Adds PosterFromTemplate marker, storeBundledTemplatePoster, preloads existing collections, slug-adoption fallback, sync_queued labeling, per-worker panic recovery, and preserves sticky admin posters via rewritten ensureTemplatePoster.
Collection artwork storage & tests
internal/api/handlers/collection_artwork.go, internal/api/handlers/collection_artwork_test.go
Adds helper to store bundled template posters from FrontendFS into S3 and tests verifying PUTs and thumbhash behavior.
User collection import & userstore
internal/api/handlers/user_collection_imports.go, internal/userstore/*
Accepts poster_url in imports, persists PosterURL in CreateCollection, attempts to store bundled template posters, and presigns poster URLs in responses.
API response & presigning
internal/api/handlers/collections.go
Collection responses now include PosterURL; presign logic treats absolute paths (/…) and HTTP(S) as already-servable and presigns other local paths when S3 is configured.
Router, adminjob & runner wiring
internal/api/router.go, internal/adminjob/*, cmd/silo/main.go
Adds FrontendFS dependency, new template_bundle_apply admin job type, runner executor wiring, route for queuing apply-job, and cmd-level executor provisioning.
Frontend types, UI & admin pages
web/src/api/types.ts, web/src/lib/collectionTemplates.ts, web/src/components/CollectionTemplateGallery/*, web/src/pages/AdminCollections.tsx
Adds optional poster_url to import types; adds TemplatePosterField component and integrates poster selection into config forms and user import; changes gallery apply flow to queue apply-job and surface sync_queued; admin page shows apply-job banner and triggers query invalidation on completion.
Hooks and form limits
web/src/hooks/queries/admin/collections.ts, web/src/pages/adminCollectionsShared.tsx
Hook adds timeout-aware error messages, includes sync_queued in success toasts and special-cases 409 for already-running; increases Max Items numeric input max from 100→200.
Docs
AGENTS.md, docs/wiki/admin/collection-templates.md
AGENTS.md expands multi-repo ownership/coordination guidance; collection-templates docs describe poster generation pipeline and asset expectations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I hopped through templates, posters in my paw,
From server defaults to URLs I saw.
Five hundred scans across each genre bin,
Queue them, sync them, watch the dashboards spin.
A rabbit’s nod: choose default or craft your own.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.33% 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 'Add poster-aware collection templates and async sync queueing' directly and clearly summarizes the main changes: it identifies the two primary features added (poster-aware templates and async sync queueing), which are consistently emphasized across the changeset.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/collections-template-port

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
web/src/hooks/queries/admin/collections.ts (1)

146-155: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Include failure-only outcomes in the success summary toast.

Line 146 currently suppresses any toast when only failures are returned (failureCount > 0 with zero created/deleted/queued). That can leave admins with no visible result for a completed apply call.

Suggested fix
-        if (created > 0 || deleted > 0 || syncQueued > 0) {
+        if (created > 0 || deleted > 0 || syncQueued > 0 || failureCount > 0) {
           const message = [
             deleted > 0 ? `Deleted ${deleted}` : "",
             created > 0 ? `created ${created}` : "",
             syncQueued > 0 ? `queued ${syncQueued} syncs` : "",
             failureCount > 0 ? `${failureCount} failed` : "",
           ]
             .filter(Boolean)
             .join("; ");
           toast.success(message);
         }

Based on learnings: Reliability is a core priority; keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).

🤖 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 `@web/src/hooks/queries/admin/collections.ts` around lines 146 - 155, The code
currently only shows the summary toast when created, deleted, or syncQueued are
>0, which hides outcomes when only failureCount > 0; update the condition that
gates the toast (the if surrounding created/deleted/syncQueued and
toast.success) to also include failureCount > 0 so the constructed message
(which already references failureCount) is shown even when there are only
failures; locate the block referencing created, deleted, syncQueued,
failureCount, message, and toast.success and change the if to (created > 0 ||
deleted > 0 || syncQueued > 0 || failureCount > 0).
internal/usercollections/sync.go (1)

153-176: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cap MDBList lookup batches before resolve-phase limiting.

On Line 153, limit enforcement starts during resolve, but the expensive external-ID batches are already
constructed from the full source list earlier in this function. For large MDBList feeds with small
cfg.Limit, this can still produce oversized GetByExternalIDs calls and unnecessary DB load.

Suggested fix
 func (s *Service) syncMDBList(ctx context.Context, store userstore.UserStore, collection *userstore.Collection, cfg SourceConfig, startedAt time.Time) (*SyncResult, *userstore.Collection, error) {
 	url := strings.TrimSpace(cfg.URL)
 	if url == "" {
 		return nil, nil, fmt.Errorf("mdblist sync: url is required")
 	}
 
 	entries, err := s.fetchMDBListEntries(ctx, url)
 	if err != nil {
 		return nil, nil, err
 	}
+	if fetchLimit := collectionutil.SourceFetchLimit(cfg.Limit); fetchLimit > 0 && len(entries) > fetchLimit {
+		entries = entries[:fetchLimit]
+	}
 
 	var movieBatch, seriesBatch catalog.ExternalIDBatch
 	for _, entry := range entries {
 		batch := &movieBatch

Based on learnings: "Performance is a core priority; if a tradeoff is required, choose correctness and robustness over short-term convenience."

🤖 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/usercollections/sync.go` around lines 153 - 176, The resolve-phase
currently constructs expensive external-ID batches from the entire entries slice
before applying the resolveLimit, causing oversized GetByExternalIDs calls; to
fix, ensure you cap the work that builds those lookup batches to
collectionResolveLimit(cfg) by only passing the first N entries (N =
resolveLimit) into resolveMatchedWithLimit or by limiting the loop that
generates external-ID keys (the code that calls resolveCandidate for entries) so
it never includes items beyond resolveLimit; keep using
collectionResolveLimit(cfg), resolveMatchedWithLimit, resolveCandidate and
ensure subsequent filtering/limit logic (filterByLibraries,
limitCollectionItems, applyResult) still operates on the original totals for
counts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/usercollections/sync.go`:
- Around line 153-176: The resolve-phase currently constructs expensive
external-ID batches from the entire entries slice before applying the
resolveLimit, causing oversized GetByExternalIDs calls; to fix, ensure you cap
the work that builds those lookup batches to collectionResolveLimit(cfg) by only
passing the first N entries (N = resolveLimit) into resolveMatchedWithLimit or
by limiting the loop that generates external-ID keys (the code that calls
resolveCandidate for entries) so it never includes items beyond resolveLimit;
keep using collectionResolveLimit(cfg), resolveMatchedWithLimit,
resolveCandidate and ensure subsequent filtering/limit logic (filterByLibraries,
limitCollectionItems, applyResult) still operates on the original totals for
counts.

In `@web/src/hooks/queries/admin/collections.ts`:
- Around line 146-155: The code currently only shows the summary toast when
created, deleted, or syncQueued are >0, which hides outcomes when only
failureCount > 0; update the condition that gates the toast (the if surrounding
created/deleted/syncQueued and toast.success) to also include failureCount > 0
so the constructed message (which already references failureCount) is shown even
when there are only failures; locate the block referencing created, deleted,
syncQueued, failureCount, message, and toast.success and change the if to
(created > 0 || deleted > 0 || syncQueued > 0 || failureCount > 0).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7efd5093-dcdb-4d36-826c-93b0dd9e4198

📥 Commits

Reviewing files that changed from the base of the PR and between c085b12 and 841e63e.

⛔ Files ignored due to path filters (150)
  • web/public/images/collection-templates/mdblist_awards_golden_globes_winners.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_awards_oscar_winners.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_best_of_2023.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_best_of_2024.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_best_of_2025.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_charts_popular_movies.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_misc_a24.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_misc_criterion_collection.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_misc_ifc_films.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_misc_studio_ghibli.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_aapi_heritage_month.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_christmas.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_easter.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_halloween.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_latinx_heritage_month.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_new_year.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_pride_month.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_thanksgiving.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_seasonal_valentines_day.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_apple_tv_plus.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_disney_plus_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_hbo_max_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_hulu_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_netflix_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_peacock_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_prime_video_originals.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/mdblist_streaming_shudder.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/raw/mdblist_awards_golden_globes_winners.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_awards_oscar_winners.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_best_of_2023.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_best_of_2024.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_best_of_2025.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_charts_popular_movies.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_misc_a24.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_misc_criterion_collection.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_misc_ifc_films.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_misc_studio_ghibli.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_aapi_heritage_month.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_christmas.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_easter.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_halloween.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_latinx_heritage_month.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_new_year.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_pride_month.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_thanksgiving.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_seasonal_valentines_day.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_apple_tv_plus.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_disney_plus_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_hbo_max_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_hulu_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_netflix_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_peacock_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_prime_video_originals.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/mdblist_streaming_shudder.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_kids_movies.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_action.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_adventure.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_animation.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_comedy.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_crime.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_documentary.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_drama.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_family.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_fantasy.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_history.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_horror.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_music.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_mystery.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_romance.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_science_fiction.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_thriller.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_war.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_popular_western.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_action.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_adventure.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_animation.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_comedy.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_crime.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_documentary.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_drama.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_family.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_fantasy.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_history.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_horror.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_music.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_mystery.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_romance.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_science_fiction.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_thriller.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_war.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_discover_top_rated_western.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_fast_furious.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_hobbit.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_james_bond.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_jurassic_park.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_lord_of_the_rings.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_mission_impossible.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_monsterverse.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_pirates_of_the_caribbean.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_placeholder.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_star_wars.png is excluded by !**/*.png
  • web/public/images/collection-templates/raw/tmdb_franchise_wizarding_world.png is excluded by !**/*.png
  • web/public/images/collection-templates/tmdb_discover_kids_movies.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_action.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_adventure.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_animation.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_comedy.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_crime.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_documentary.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_drama.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_family.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_fantasy.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_history.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_horror.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_music.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_mystery.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_romance.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_science_fiction.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_thriller.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_war.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_popular_western.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_action.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_adventure.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_animation.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_comedy.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_crime.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_documentary.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_drama.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_family.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_fantasy.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_history.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_horror.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_music.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_mystery.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_romance.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_science_fiction.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_thriller.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_war.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_discover_top_rated_western.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_fast_furious.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_hobbit.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_james_bond.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_jurassic_park.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_lord_of_the_rings.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_mission_impossible.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_monsterverse.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_pirates_of_the_caribbean.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_placeholder.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_star_wars.jpg is excluded by !**/*.jpg
  • web/public/images/collection-templates/tmdb_franchise_wizarding_world.jpg is excluded by !**/*.jpg
📒 Files selected for processing (29)
  • AGENTS.md
  • docs/wiki/admin/collection-templates.md
  • internal/api/handlers/collections.go
  • internal/api/handlers/library_collections.go
  • internal/api/handlers/user_collection_imports.go
  • internal/catalog/library_collection_repo.go
  • internal/catalog/library_collection_service.go
  • internal/collections/templates/builtin.go
  • internal/collections/templates/templates_test.go
  • internal/collectionutil/collectionutil.go
  • internal/metadata/tmdb/client.go
  • internal/metadata/trakt/client.go
  • internal/models/library_collection.go
  • internal/sections/repo.go
  • internal/usercollections/sync.go
  • internal/userstore/pgstore/collections.go
  • internal/userstore/types.go
  • migrations/134_library_collection_poster_template_origin.down.sql
  • migrations/134_library_collection_poster_template_origin.up.sql
  • web/src/api/types.ts
  • web/src/components/CollectionTemplateGallery/CollectionTemplateCard.test.tsx
  • web/src/components/CollectionTemplateGallery/CollectionTemplateCard.tsx
  • web/src/components/CollectionTemplateGallery/CollectionTemplateConfigForm.tsx
  • web/src/components/CollectionTemplateGallery/CollectionTemplateGallery.tsx
  • web/src/components/CollectionTemplateGallery/TemplatePosterField.tsx
  • web/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsx
  • web/src/hooks/queries/admin/collections.ts
  • web/src/lib/collectionTemplates.ts
  • web/src/pages/adminCollectionsShared.tsx

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

🧹 Nitpick comments (1)
internal/usercollections/sync.go (1)

245-270: 💤 Low value

Consider right-sizing capacity allocation when limit is smaller than total.

The pre-allocation uses total for both matched and seen capacities. When limit is significantly smaller than total (e.g., limit=50, total=500), this over-allocates. A minor optimization would be to use min(total, *limit) when limit is non-nil.

♻️ Optional: right-size capacity
 func resolveMatchedWithLimit(total int, limit *int, resolve func(i int) string) ([]userstore.CollectionItemReplacement, int, int) {
-	matched := make([]userstore.CollectionItemReplacement, 0, total)
-	seen := make(map[string]struct{}, total)
+	capacity := total
+	if limit != nil && *limit > 0 && *limit < total {
+		capacity = *limit
+	}
+	matched := make([]userstore.CollectionItemReplacement, 0, capacity)
+	seen := make(map[string]struct{}, capacity)
 	unmatched := 0
🤖 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/usercollections/sync.go` around lines 245 - 270, In
resolveMatchedWithLimit change the pre-allocation strategy so matched and seen
are sized to the expected upper bound instead of always using total: compute cap
:= total (or if limit != nil then cap = min(total, *limit)) and use that cap
when creating matched (make(..., 0, cap)) and seen (make(map[string]struct{},
cap)); everything else (resolve, unmatched/scanned logic and the
ItemLimitReached check) stays the same.
🤖 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.

Nitpick comments:
In `@internal/usercollections/sync.go`:
- Around line 245-270: In resolveMatchedWithLimit change the pre-allocation
strategy so matched and seen are sized to the expected upper bound instead of
always using total: compute cap := total (or if limit != nil then cap =
min(total, *limit)) and use that cap when creating matched (make(..., 0, cap))
and seen (make(map[string]struct{}, cap)); everything else (resolve,
unmatched/scanned logic and the ItemLimitReached check) stays the same.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 407d2e74-968a-474f-97ba-c2adb56472a2

📥 Commits

Reviewing files that changed from the base of the PR and between 841e63e and 70b8f6c.

📒 Files selected for processing (2)
  • internal/api/handlers/library_collections.go
  • internal/usercollections/sync.go

- Store bundled template posters in public S3 when available
- Presign imported user collection posters in API responses
- Thread frontend assets into router and collection handlers

@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/api/handlers/library_collections.go`:
- Around line 115-146: The current storeBundledTemplatePoster makes S3/upload or
update failures fatal after the collection row already exists; change it so
failures do not cause the create/import to fail: either (A) perform cleanup by
deleting the newly-created collection row before returning an error (call the
repository deletion method, e.g., h.repo.Delete(ctx, collectionID) or
h.repo.DeleteCollection/Remove equivalent and log any deletion error), or (B,
preferred for robustness) downgrade persistence failures to a non-fatal
warning—log the error from storeBundledCollectionPosterIfS3Configured and from
h.repo.Update (use processLogger or h.logger), return true/false poster flags as
appropriate but do not return a non-nil error to callers so create/import
succeeds; update callers that treat this helper’s error as fatal to rely on the
success path instead.

In `@internal/api/handlers/user_collection_imports.go`:
- Around line 228-231: The current handler returns a 500 when
storeBundledTemplatePoster fails even though the collection was already created;
change this to avoid reporting a failed import after CreateCollection succeeded
by making poster persistence best-effort (preferred) or performing a proper
rollback: on error from storeBundledTemplatePoster do not call writeError;
instead log the failure with context (include collection.ID, shared.PosterURL
and the error) and continue returning success, or if you opt for rollback call
the store deletion API (e.g., store.DeleteCollection or equivalent using
collection.ID) and handle its error before returning writeError; locate the code
around storeBundledTemplatePoster, collection, writeError and the store
interface to implement one of these two behaviors.
🪄 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: d8b3d5ba-72d6-4ded-b7d2-d911547053a9

📥 Commits

Reviewing files that changed from the base of the PR and between 70b8f6c and 01b9709.

📒 Files selected for processing (6)
  • cmd/silo/main.go
  • internal/api/handlers/collection_artwork.go
  • internal/api/handlers/collection_artwork_test.go
  • internal/api/handlers/library_collections.go
  • internal/api/handlers/user_collection_imports.go
  • internal/api/router.go

- Add admin job support for collection defaults applies
- Keep preview synchronous while real applies run via the job queue
- Show collection apply job status in the admin UI

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
web/src/hooks/queries/admin/collections.ts (1)

203-212: ⚡ Quick win

Add a polling fallback for template apply job status.

useTemplateBundleApplyJobs has no refetchInterval, so dropped/reconnected realtime streams can leave apply status stale and delay downstream refresh behavior. A lightweight poll (e.g. 5–10s) makes this flow predictable.

Suggested change
 export function useTemplateBundleApplyJobs() {
   return useQuery({
     queryKey: adminKeys.jobs("template_bundle_apply"),
     queryFn: () =>
       api<AdminJobsResponse>("/admin/jobs?job_type=template_bundle_apply&limit=10").then(
         (data) => data.jobs ?? [],
       ),
     staleTime: 0,
+    refetchInterval: 5000,
+    refetchIntervalInBackground: true,
   });
 }

Based on learnings: "Reliability first: keep behavior predictable under load and during failures (session restarts, reconnects, partial streams)".

🤖 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 `@web/src/hooks/queries/admin/collections.ts` around lines 203 - 212, The hook
useTemplateBundleApplyJobs lacks a polling fallback so job status can become
stale when realtime streams drop; add a short refetch interval (e.g. 5000–10000
ms) to the useQuery options and enable background refetching so it continues
polling when the tab is inactive if desired. Update the
useTemplateBundleApplyJobs query options (the useQuery call that uses
adminKeys.jobs("template_bundle_apply") and
api<AdminJobsResponse>("/admin/jobs?job_type=template_bundle_apply&limit=10"))
to include refetchInterval: 5000 (or 10000) and optionally
refetchIntervalInBackground: true to ensure predictable refreshes after
reconnects.
🤖 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/runner.go`:
- Around line 406-433: The code zeroes out progress when finishing/failing the
template bundle apply, which overwrites real progress; capture and preserve the
last reported progress by adding local vars (e.g., lastCurrent, lastTotal)
initialized from job.ProgressCurrent and job.ProgressTotal, update them inside
the ExecuteTemplateBundleApply progress callback (where UpdateProgress is
called), and then pass lastCurrent/lastTotal to r.failJob and to r.repo.Complete
(instead of 0,0); keep using the same symbols:
r.templateBundleApply.ExecuteTemplateBundleApply callback,
r.repo.UpdateProgress, r.failJob(job.ID,...), and r.repo.Complete(...) so prior
progress is retained.

---

Nitpick comments:
In `@web/src/hooks/queries/admin/collections.ts`:
- Around line 203-212: The hook useTemplateBundleApplyJobs lacks a polling
fallback so job status can become stale when realtime streams drop; add a short
refetch interval (e.g. 5000–10000 ms) to the useQuery options and enable
background refetching so it continues polling when the tab is inactive if
desired. Update the useTemplateBundleApplyJobs query options (the useQuery call
that uses adminKeys.jobs("template_bundle_apply") and
api<AdminJobsResponse>("/admin/jobs?job_type=template_bundle_apply&limit=10"))
to include refetchInterval: 5000 (or 10000) and optionally
refetchIntervalInBackground: true to ensure predictable refreshes after
reconnects.
🪄 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: 311656c4-65a4-4e68-85cc-b9433a653567

📥 Commits

Reviewing files that changed from the base of the PR and between 01b9709 and bad0a3d.

📒 Files selected for processing (9)
  • cmd/silo/main.go
  • internal/adminjob/runner.go
  • internal/adminjob/template_bundle_apply.go
  • internal/api/handlers/library_collections.go
  • internal/api/router.go
  • web/src/components/CollectionTemplateGallery/CollectionTemplateGallery.tsx
  • web/src/hooks/queries/admin/collections.ts
  • web/src/lib/collectionTemplates.ts
  • web/src/pages/AdminCollections.tsx

Comment thread internal/adminjob/runner.go Resolved
Silo Server Migration added 2 commits May 23, 2026 21:32
- Log poster store/update failures instead of aborting collection sync
- Preallocate matched collection replacements using the active limit
- Keep the last reported template bundle apply progress on success and failure
- Poll admin collection apply jobs every 5 seconds in the UI

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
internal/api/handlers/library_collections.go (1)

1785-1803: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don’t keep applying a library after the existing-collections preload fails.

When ListByLibrary fails here, the code still continues into create/adopt handling for that same library with an empty collectionsByLibraryID / remainingByLibrarySlug view. That can create duplicate collections or misreport delete/adoption results because the apply run no longer knows what already exists.

Suggested direction
+	skippedLibraries := make(map[int]struct{}, len(libraryIDs))
 	for _, libraryID := range libraryIDs {
 		collections, err := h.repo.ListByLibrary(ctx, libraryID, catalog.ListLibraryCollectionsOptions{IncludeHidden: true})
 		if err != nil {
 			library := librariesByID[libraryID]
+			skippedLibraries[libraryID] = struct{}{}
 			if req.DeleteExisting {
 				resp.DeleteFailed = append(resp.DeleteFailed, templateBundleCollectionEntry{
 					LibraryID:   library.ID,
 					LibraryName: library.Name,
 					Reason:      err.Error(),
 				})
 			} else {
 				slog.Warn("listing existing collections before template bundle apply",
 					"bundle_id", bundle.ID,
 					"library_id", library.ID,
 					"error", err,
 				)
 			}
 			continue
 		}
 	for _, libraryID := range libraryIDs {
+		if _, skip := skippedLibraries[libraryID]; skip {
+			continue
+		}
 		library := librariesByID[libraryID]
 		for _, templateID := range bundle.TemplateIDs {
Based on learnings: Reliability is the first priority; keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).

Also applies to: 1861-1948

🤖 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/library_collections.go` around lines 1785 - 1803, When
h.repo.ListByLibrary(ctx, libraryID, ...) fails, stop any further apply work for
that library instead of letting later create/adopt code run against empty
collections maps; record the failure (use resp.DeleteFailed or add a new
resp.ApplyFailed entry using templateBundleCollectionEntry with
LibraryID/LibraryName/Reason) and add the libraryID to a skip set (e.g.,
skipLibraryIDs or failedLibraryIDs) so downstream logic that uses
collectionsByLibraryID and remainingByLibrarySlug checks that set and skips
processing for that library; update the later create/adopt loops to consult
skipLibraryIDs before acting so no duplicate collections or misreported results
occur.
🤖 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/api/handlers/library_collections.go`:
- Around line 153-160: The handler currently returns stored=false when
h.repo.Update(ctx, input) fails, which conflates "upload to S3 succeeded" with
"DB update failed" and causes ensureTemplatePoster() to treat the asset as not
stored; change the return-path for the h.repo.Update error so that when the S3
upload succeeded you return stored=true (and include the storedPath and
storedThumbhash values) even if the DB update failed, so the
caller/ensureTemplatePoster() preserves the uploaded poster/thumbhash and can
retry the DB persist separately; update the error return value/propagation
accordingly so failures are distinguishable from a successful upload
(referencing h.repo.Update, ensureTemplatePoster, storedPath, storedThumbhash
and the stored boolean).

---

Outside diff comments:
In `@internal/api/handlers/library_collections.go`:
- Around line 1785-1803: When h.repo.ListByLibrary(ctx, libraryID, ...) fails,
stop any further apply work for that library instead of letting later
create/adopt code run against empty collections maps; record the failure (use
resp.DeleteFailed or add a new resp.ApplyFailed entry using
templateBundleCollectionEntry with LibraryID/LibraryName/Reason) and add the
libraryID to a skip set (e.g., skipLibraryIDs or failedLibraryIDs) so downstream
logic that uses collectionsByLibraryID and remainingByLibrarySlug checks that
set and skips processing for that library; update the later create/adopt loops
to consult skipLibraryIDs before acting so no duplicate collections or
misreported results occur.
🪄 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: 5f774767-3cf5-4009-aaf3-e80a53b953b4

📥 Commits

Reviewing files that changed from the base of the PR and between bad0a3d and 08fff4d.

📒 Files selected for processing (3)
  • internal/api/handlers/library_collections.go
  • internal/api/handlers/user_collection_imports.go
  • internal/usercollections/sync.go

Comment on lines +153 to +160
if err := h.repo.Update(ctx, input); err != nil {
slog.Warn("failed to persist bundled template poster",
"collection_id", collectionID,
"poster_path", posterPath,
"stored_path", storedPath,
"error", err,
)
return false, "", "", nil

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep “upload succeeded” distinct from “not stored.”

These branches currently return stored=false even when the S3 upload already succeeded and only the DB update failed. ensureTemplatePoster() treats that the same as “nothing was stored” and falls back to the raw template path, which can discard the uploaded poster/thumbhash and rewrite the row to a different poster source on the retry path.

Suggested direction
-		return false, "", "", nil
+		return false, storedPath, thumbhash, nil
-	if stored, _, _, err := h.storeBundledTemplatePoster(ctx, collection.ID, posterPath, true); err != nil {
+	if stored, storedPath, _, err := h.storeBundledTemplatePoster(ctx, collection.ID, posterPath, true); err != nil {
 		slog.Warn("failed to store template poster",
 			"collection_id", collection.ID,
 			"template_id", tmpl.ID,
 			"poster_path", posterPath,
 			"error", err,
 		)
 		return
-	} else if stored {
+	} else if stored || storedPath != "" {
 		return
 	}
Based on learnings: Reliability is the first priority; keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).

Also applies to: 2038-2048

🤖 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/library_collections.go` around lines 153 - 160, The
handler currently returns stored=false when h.repo.Update(ctx, input) fails,
which conflates "upload to S3 succeeded" with "DB update failed" and causes
ensureTemplatePoster() to treat the asset as not stored; change the return-path
for the h.repo.Update error so that when the S3 upload succeeded you return
stored=true (and include the storedPath and storedThumbhash values) even if the
DB update failed, so the caller/ensureTemplatePoster() preserves the uploaded
poster/thumbhash and can retry the DB persist separately; update the error
return value/propagation accordingly so failures are distinguishable from a
successful upload (referencing h.repo.Update, ensureTemplatePoster, storedPath,
storedThumbhash and the stored boolean).

@Quick104
Quick104 merged commit 46b07b8 into main May 24, 2026
3 checks passed
@Quick104
Quick104 deleted the codex/collections-template-port branch May 24, 2026 01:41
fluxis added a commit to fluxis/silo-server that referenced this pull request Jun 17, 2026
…ups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- Silo-Server#1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- Silo-Server#3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- Silo-Server#4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- Silo-Server#6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- Silo-Server#10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- Silo-Server#8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
* perf(catalog): fix audiobook detail N+1 + slow people facets

Audiobook detail pages were slow in proportion to track count (up to 433
files/book). Root causes, found by EXPLAIN ANALYZE on the live DB:

- effectiveAudioSelection ran 3-4 user-store queries (profile, audio pref,
  library pref) per file inside buildPlaybackInfo's loop, though the results
  are invariant across a request. Introduce a request-scoped audioPrefResolver
  that memoizes the store lookups (library prefs keyed by folder); a 400-file
  audiobook now issues each query once instead of per file. Selection logic is
  unchanged (audioPreference returns a copy so the original-language sentinel
  is still resolved per file).
- buildAudiobookExtension ran its four independent related-content queries
  serially; run them concurrently so latency is the slowest, not the sum.
- author/narrator browse facets did a full people-table scan; add a
  (kind, content_id, person_id) index so the facet resolves from an index-only
  scan of just that kind's credits (~112ms -> ~49ms on the live library).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(catalog): cache audiobook author/narrator group browse

The Authors/Narrators audiobook pages were slow on cold load and slow again
after a hard refresh (fast only while the React Query client cache was warm).

Root cause (EXPLAIN ANALYZE on live, 31K-audiobook library): the grouped
browse query is ~234ms/page, there are ~13K distinct authors, and the client
pages through the entire list on every load (sequential 500-row requests). With
no server-side cache each of the ~20 pages re-ran the full aggregation
(COUNT(*) OVER() forces it), so a cold load was ~20x234ms. The client's 60s
staleTime was the only thing making a warm revisit fast; a refresh wiped it.

Fix: AudiobookGroupsCache caches the full sorted group list per (library,
group_by, sort, viewer) for 60s (matching the client staleTime, so no extra
staleness) and serves every page as an in-memory slice — one aggregation per
window instead of one per page, and a refresh is a cache hit. Also raise the
client page size 500->2000 so fewer sequential round-trips are needed now that
a larger page is a cheap slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(settings): throttle per-request device last_seen upserts

Device-setting reads (HandleGetDeviceSetting, HandleGetEffectiveSettings,
HandleGetEffectiveSubtitleAppearance) each registered the request's device — an
INSERT ... ON CONFLICT upsert of last_seen_at on a single per-device row. A page
that fetches many settings fired hundreds of these concurrently; they serialized
on that row's lock (observed 100-237ms each, ~250 per page load in the slow
query log), taxing every settings fetch.

Throttle device registration to one upsert per (profile, device) per 5 minutes
via an in-process TTL cache, marking the device seen before the upsert so a
concurrent burst collapses to a single write. last_seen_at stays fresh to within
the window. Reads no longer issue a contended write on the hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf+fix(audiobooks): probe-repair, resume position, cache storm, groups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- #1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- #3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- #4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- #6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- #10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- #8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(audiobooks): batch-fetch abs list/shelf handlers (kill N+1)

handleSimilarItems, handleItemsInProgress, and handleGetMyProgress called
MediaStore.GetAudiobookByID once per row — up to ~500 single fetches (each a
few queries) on app open. Add GetAudiobooksByIDs (one access-scoped fetch +
people/series hydrated once for the whole set) and look results up from the
returned map, preserving order. Underlying primitives (GetByIDsWithAccess,
hydratePeople/Series) were already batch-capable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): reconcile deleted files on scan + prune session history

#5: ScanAudiobookFolder only ever upserted — deleted/renamed books leaked
media_items/media_files/memberships forever. Mirror the ebook reconcile: collect
seenPaths during the walk, MarkMissing files no longer on disk, then
reconcileLibraryMemberships. Safety mirrors ebooks/video: an inaccessible root
(unmounted source) is skipped entirely, and a walk that saw zero files while the
DB has rows only reconciles after operator cleanup confirmation
(ebookEmptyCleanupAllowed) — so a flapping mount can't wipe the catalog. Soft
mark only; the existing grace-period purge hard-deletes later. Reconcile runs
only on a fully-completed (non-cancelled) scan. (#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

#8-retention: abs_playback_sessions grew unbounded (one row per play-start, never
deleted) and fed every listening-stats scan. Add an hourly sweep in
SessionCleaner: close abandoned open sessions (no /close, stopped syncing >24h)
and delete closed sessions older than 90 days. Mirrors the recommendation_cache /
missing-files prune pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address max-effort code-review findings

From /code-review max on the pre-PR diff:
- DATA RACE (P0): SessionCleaner.lastABSSessionPrune is read+written by both the
  15s ticker goroutine and the shutdown-path CleanStale call (main.go defers
  Stop() to after that call). Guard the prune-due gate with a mutex. (CleanStale
  was stateless before this branch, so concurrent calls were previously safe.)
- ScanAudiobookFolder hardcoded fullScan=true into the empty-walk cleanup guard,
  but it's also called from ScanSubtree (incremental scans). An empty subtree
  scan would wrongly consume the operator's one-shot empty-cleanup allowance and
  warn. Thread a real fullScan flag (true from ScanFolder, false from the two
  subtree call sites), mirroring the ebook path.
- Revert UpdateProgressPosition to UPDATE-only (drop the INSERT-on-missing):
  keep the monotonic GREATEST + finish guard that fixes the resume rewind, but
  restore the no-op-on-missing contract so a stray sync tick can't resurrect
  just-cleared progress or create a zero-duration continue-listening row.
- Clamp the audiobook-groups handler limit (paging moved into the cache, leaving
  the old 500/page bound stranded); also gofmt the Scanner struct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address review feedback for scanner and stats

* fix(audiobooks): address review feedback

* fix(audiobooks): retry failed session prune

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Quick <[email protected]>
CoffeeKnyte added a commit that referenced this pull request Jul 29, 2026
Both matrices are the stated review checklist for this area, so a stale claim
in them is a real defect.

- stream-abuse-matrix: "correction #1", row A8 and follow-up #1 claimed the
  async enforcer reads the raw users.max_streams column and is "dormant on a
  default install". That was fixed earlier on this branch by resolving
  SessionManager.EffectiveLimits (the same group-merged policy synchronous
  admission uses); all three now describe the shipped behaviour. Added rows for
  the ABS authenticated file route, the ABS public track and the public RSS
  feed file route.
- playback-paths matrix: added ABS to the serving/monitoring/kill tables, marked
  VERIFY-4 resolved with the served-at-driven transcode grace, recorded
  integrated BytesServed and the deliberately distinct server-observed
  LastServedAt, and documented the kill-list endpoints, Unrevoke, the tombstone
  and the publish-failure fail-safe.
- Restated as explicitly deferred rather than implied: multi-replica
  enforcement (VERIFY-3) and the transcode-node ghost-record sweep. Both need
  the monitoring write side restructured and deserve their own change.

Part of the stream monitoring & kill-switch epic.
CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
Six defects on byte-serving paths, all of which made the PR's monitoring and
kill-switch claims narrower than documented.

#2/GAP-10 -- the ABS in-flight kill switch was a production no-op. accessLog
wraps every ABS route, and its statusRecorder implemented Write, WriteHeader,
Hijack and Flush but not Unwrap, so http.NewResponseController dead-ended and
SetWriteDeadline returned ErrNotSupported. A multi-GB audiobook pour survived a
RevokeUser. The existing test passed throughout because it called handlers
directly and never saw the middleware; the new test drives the mounted router
over a real socket, and both new assertions fail if Unwrap is removed again.

GAP-11 -- ebook, comic and PDF serving was invisible and un-killable: no meter,
no transfer record, no Refuse, no watcher, on a route that serves cbz/cbr/pdf
files routinely 100 MB-1 GB+. It now follows the ABS file-handler idiom. Note
guardRevocationCut is deliberately *not* reused here: it keys on a session_id
URL param and an ?st= token this route does not carry, so it would have
compiled and silently guarded nothing. Cap-exempt per decision A4 -- admission
is untouched and neither route consumes a stream slot.

#10 -- the no-proxy remote transcode hop forwarded segments through a bare
RollingDeadlineWriter, so bytes on the API hop went unaccounted for a supported
topology. Metering is scoped to media bodies; manifests are excluded so a
rewritten playlist is not counted as media, and a mid-copy failure is no longer
silently discarded.

#16 -- native, proxy and compat subtitle pours were entry-gated only. They now
carry a transport span, a meter and an in-flight watcher. Proxy subtitle bytes
are attributed only when a tracker record already exists: taking Track/Remove
lifecycle ownership per subtitle request would walk straight into the
overlapping-request defect (#1) that Batch 2 addresses. Compat subtitle
extraction is buffered and rejects bitmap formats, so a cut stops delivery but
not extraction already in progress.

M2 -- the proxy deferred tracker Remove with the request context, which is
already canceled on client disconnect, so the Redis DEL never happened and the
key lingered until TTL -- a false over-cap window that could get a legitimate
stream killed. Cleanup now uses a short bounded context.

GAP-13 -- mergeStreams took the freshest record wholesale and never merged
BytesServed, so a stream that poured 8 GiB at an edge could report 0. Merged as
a max, not a sum: the records are two observers of one pour. Fixed in
DedupeSessionInfos too, which had the same hole and feeds the admin view.

#11 needed no behaviour change -- that route was already metered, registered and
watched, and commit c24d839 plus this Unwrap fix are what make its cut work.
Its comment claimed download-class exemption while the comment above it said the
?token= form is for iOS streaming; both facts and decision A4 are now stated.

Part of #305.
CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
… canonical

Five defects that all produced a WRONG over-cap count, which is why they land
before the revocation batch: decision A1 raises the over-cap revocation TTL from
5m to ~24h, removing the self-healing that currently limits the damage of a
miscount. A false positive after A1 blocks a legitimate stream for a day, so the
count has to be trustworthy first.

#1 -- overlapping edge requests deleted a live stream. Tracker.sessions was a
set and Remove tore down all state plus the Redis key, while both proxy pour
handlers deferred removal unconditionally. Two overlapping Range GETs on one
session id -- ordinary seek behaviour -- meant the first to finish deleted the
record while the second was still pouring, and later AddBytes calls were then
dropped because AddBytes ignores bytes for a session with no live record. The
stream went invisible to authoritative monitoring while still serving.

Track now returns a Lease that the request-scoped caller releases exactly once;
teardown happens when the last live lease is released. A plain refcount would
have been wrong: Track(A) -> Remove -> Track(B) -> Release(A) decrements B, and
clamping at zero does not help because the count legitimately belongs to B. That
is not hypothetical -- the transcode node deliberately replaces sessions under
the same id so a quality switch does not orphan ffmpeg, and it calls
unconditional Remove from its reaper and stop paths. So each generation carries
an epoch, Remove and Cleanup bump it, and a release from a superseded generation
is a logged no-op. Lease identity is a set rather than a counter, which makes a
duplicate release detectable instead of silently destructive.

The transcode node keeps using Remove: its Track calls are not request-scoped and
are correctly owned by session lifecycle. "Every Track needs a paired Release" is
true only of the request-scoped callers.

#8 -- async transcode tracking could leave a permanent ghost. The tracking write
ran as a bare goroutine with a WithoutCancel context, so if stop won the race the
delayed Track recreated the record after cleanup -- and because it landed in
sessions, Snapshot treated it as live until Remove and it NEVER idle-expired. A
permanent phantom inflating its owner's count, able to trigger false over-cap
kills of that user's real streams. The write now takes the per-session lifecycle
lock that stop and reap already hold, and re-checks session pointer identity
before writing, so a stopped or replaced generation cannot resurrect a record.
Pointer identity rather than id equality is what makes same-id replacement safe.
The write stays off the request path -- the API server and the playback client
are blocked on the 202.

#9 + M3 -- protocol-v3 counted one stream twice. The stream token carries a
transport id distinct from the logical session id, and the node tracked under the
transport id while the API/proxy record used the logical one, so mergeStreams saw
two streams. M3 was the reason this had not yet bitten: the v3 fresh-start caller
sent no owner attribution at all, so the transport record landed under user 0,
which the enforcer skips -- silently exempting the stream from the cap entirely.
Fresh v3 starts now carry the logical session id and full owner attribution
(both were already in scope at the call site), and merging is keyed on logical
identity where present via one shared helper used by both merge functions, which
had already drifted apart once.

The enforcer view resolves SessionID to the logical id so a kill targets the real
session rather than a replaceable transport generation. The raw admin view keeps
the transport id and exposes logical_session_id as an additive omitempty field,
advertised on the node-sessions capability endpoint, so the v1 response shape is
unchanged.

GAP-15 -- edge transcode liveness was request-observed. touchTranscodeSession
fired before proxying, so hammering dead segment URLs advanced LastServedAt with
zero bytes served. Visibility and liveness are now separate operations:
EnsureEphemeral makes a session visible without claiming bytes were served, and
served-byte liveness advances only from a 2xx/206 upstream response. Previously
the proxy metered every upstream body regardless of status, so a node 404's error
body counted as served bytes -- moving the touch later would not have fixed it.

S4 -- LiveLocalSessions moved from the HTTP handlers package to streammonitor,
which owns monitoring. A background enforcer importing api/handlers was
backwards. Pure move; its existing mapping assertions moved with it. The
LastActivityAt fallback inside it is left as-is -- decision A5 removes it in the
liveness batch.

Verified with go test -race across nodesessions, proxy and transcodenode; the
overlap regression test was confirmed to fail under the old unconditional
teardown.

Part of #305.
zippyy added a commit to techrelay/silo-server-fork that referenced this pull request Aug 8, 2026
…ection-test

Support auth provider connection tests and role claims
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