Repository navigation
Add poster-aware collection templates and async sync queueing - #1
Conversation
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
There was a problem hiding this comment.
💡 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".
- 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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesTemplate Poster Management and Sync Refinement
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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 winInclude failure-only outcomes in the success summary toast.
Line 146 currently suppresses any toast when only failures are returned (
failureCount > 0with 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 winCap 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 oversizedGetByExternalIDscalls 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 := &movieBatchBased 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
⛔ Files ignored due to path filters (150)
web/public/images/collection-templates/mdblist_awards_golden_globes_winners.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_awards_oscar_winners.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_best_of_2023.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_best_of_2024.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_best_of_2025.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_charts_popular_movies.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_misc_a24.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_misc_criterion_collection.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_misc_ifc_films.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_misc_studio_ghibli.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_aapi_heritage_month.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_christmas.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_easter.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_halloween.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_latinx_heritage_month.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_new_year.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_pride_month.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_thanksgiving.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_seasonal_valentines_day.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_apple_tv_plus.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_disney_plus_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_hbo_max_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_hulu_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_netflix_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_peacock_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_prime_video_originals.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/mdblist_streaming_shudder.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/raw/mdblist_awards_golden_globes_winners.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_awards_oscar_winners.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_best_of_2023.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_best_of_2024.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_best_of_2025.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_charts_popular_movies.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_misc_a24.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_misc_criterion_collection.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_misc_ifc_films.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_misc_studio_ghibli.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_aapi_heritage_month.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_christmas.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_easter.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_halloween.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_latinx_heritage_month.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_new_year.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_pride_month.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_thanksgiving.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_seasonal_valentines_day.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_apple_tv_plus.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_disney_plus_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_hbo_max_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_hulu_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_netflix_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_peacock_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_prime_video_originals.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/mdblist_streaming_shudder.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_kids_movies.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_action.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_adventure.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_animation.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_comedy.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_crime.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_documentary.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_drama.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_family.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_fantasy.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_history.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_horror.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_music.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_mystery.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_romance.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_science_fiction.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_thriller.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_war.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_popular_western.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_action.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_adventure.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_animation.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_comedy.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_crime.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_documentary.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_drama.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_family.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_fantasy.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_history.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_horror.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_music.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_mystery.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_romance.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_science_fiction.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_thriller.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_war.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_discover_top_rated_western.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_fast_furious.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_hobbit.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_james_bond.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_jurassic_park.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_lord_of_the_rings.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_mission_impossible.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_monsterverse.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_pirates_of_the_caribbean.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_placeholder.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_star_wars.pngis excluded by!**/*.pngweb/public/images/collection-templates/raw/tmdb_franchise_wizarding_world.pngis excluded by!**/*.pngweb/public/images/collection-templates/tmdb_discover_kids_movies.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_action.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_adventure.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_animation.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_comedy.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_crime.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_documentary.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_drama.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_family.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_fantasy.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_history.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_horror.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_music.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_mystery.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_romance.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_science_fiction.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_thriller.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_war.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_popular_western.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_action.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_adventure.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_animation.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_comedy.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_crime.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_documentary.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_drama.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_family.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_fantasy.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_history.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_horror.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_music.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_mystery.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_romance.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_science_fiction.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_thriller.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_war.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_discover_top_rated_western.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_fast_furious.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_hobbit.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_james_bond.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_jurassic_park.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_lord_of_the_rings.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_mission_impossible.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_monsterverse.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_pirates_of_the_caribbean.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_placeholder.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_star_wars.jpgis excluded by!**/*.jpgweb/public/images/collection-templates/tmdb_franchise_wizarding_world.jpgis excluded by!**/*.jpg
📒 Files selected for processing (29)
AGENTS.mddocs/wiki/admin/collection-templates.mdinternal/api/handlers/collections.gointernal/api/handlers/library_collections.gointernal/api/handlers/user_collection_imports.gointernal/catalog/library_collection_repo.gointernal/catalog/library_collection_service.gointernal/collections/templates/builtin.gointernal/collections/templates/templates_test.gointernal/collectionutil/collectionutil.gointernal/metadata/tmdb/client.gointernal/metadata/trakt/client.gointernal/models/library_collection.gointernal/sections/repo.gointernal/usercollections/sync.gointernal/userstore/pgstore/collections.gointernal/userstore/types.gomigrations/134_library_collection_poster_template_origin.down.sqlmigrations/134_library_collection_poster_template_origin.up.sqlweb/src/api/types.tsweb/src/components/CollectionTemplateGallery/CollectionTemplateCard.test.tsxweb/src/components/CollectionTemplateGallery/CollectionTemplateCard.tsxweb/src/components/CollectionTemplateGallery/CollectionTemplateConfigForm.tsxweb/src/components/CollectionTemplateGallery/CollectionTemplateGallery.tsxweb/src/components/CollectionTemplateGallery/TemplatePosterField.tsxweb/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsxweb/src/hooks/queries/admin/collections.tsweb/src/lib/collectionTemplates.tsweb/src/pages/adminCollectionsShared.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/usercollections/sync.go (1)
245-270: 💤 Low valueConsider right-sizing capacity allocation when limit is smaller than total.
The pre-allocation uses
totalfor bothmatchedandseencapacities. Whenlimitis significantly smaller thantotal(e.g., limit=50, total=500), this over-allocates. A minor optimization would be to usemin(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
📒 Files selected for processing (2)
internal/api/handlers/library_collections.gointernal/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
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/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
📒 Files selected for processing (6)
cmd/silo/main.gointernal/api/handlers/collection_artwork.gointernal/api/handlers/collection_artwork_test.gointernal/api/handlers/library_collections.gointernal/api/handlers/user_collection_imports.gointernal/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
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
web/src/hooks/queries/admin/collections.ts (1)
203-212: ⚡ Quick winAdd a polling fallback for template apply job status.
useTemplateBundleApplyJobshas norefetchInterval, 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
📒 Files selected for processing (9)
cmd/silo/main.gointernal/adminjob/runner.gointernal/adminjob/template_bundle_apply.gointernal/api/handlers/library_collections.gointernal/api/router.goweb/src/components/CollectionTemplateGallery/CollectionTemplateGallery.tsxweb/src/hooks/queries/admin/collections.tsweb/src/lib/collectionTemplates.tsweb/src/pages/AdminCollections.tsx
- 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
There was a problem hiding this comment.
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 winDon’t keep applying a library after the existing-collections preload fails.
When
ListByLibraryfails here, the code still continues into create/adopt handling for that same library with an emptycollectionsByLibraryID/remainingByLibrarySlugview. That can create duplicate collections or misreport delete/adoption results because the apply run no longer knows what already exists.Based on learnings: Reliability is the first priority; keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).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 {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
📒 Files selected for processing (3)
internal/api/handlers/library_collections.gointernal/api/handlers/user_collection_imports.gointernal/usercollections/sync.go
| 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 |
There was a problem hiding this comment.
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
}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).
…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]>
* 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]>
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.
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.
… 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.
…ection-test Support auth provider connection tests and role claims
Summary
Testing
internal/collections/templates/templates_test.go.Summary by CodeRabbit
New Features
Improvements
Tests
Documentation