Skip to content

fix(collections): correct multi-library sync — match all bound libraries and dedupe items - #184

Merged
Quick104 merged 2 commits into
mainfrom
fix/collections-sync-multi-library
Jun 26, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/collections-sync-multi-library

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Two commits, both correcting collection sync: one fixes which libraries are matched, the second hardens the write path against a duplicate-key 500 that the first commit makes more likely.

Problem

1. Collection sync silently dropped items from all but one library.
A collection can be bound to several libraries (for example a "Netflix Originals"
collection spanning both the movie and series libraries). On the admin/library
collections view, such a collection listed and opened correctly — but every time it
ran a scheduled or manual sync, its membership collapsed down to just one library's
matches. Operators saw collections that opened with ~161 items shrink to ~50 after a
sync, with the entire other class (e.g. all the series) disappearing. Worst hit were the
cross-class merged collections where the surviving "legacy" library was a single
movie-only or series-only folder, so a whole media class vanished.

2. Some collections became permanently un-syncable, with no error in the logs.
A single collection could start returning a generic failure on every sync — HTTP 500,
0 items, in ~250ms, with no error or warning line on the server. Through the CDN it
rendered as a misleading "524 - A Timeout Occurred" page, so it looked like a network
timeout rather than an application error. It was data-dependent, so it surfaced
unpredictably as catalogs grew (on dev, 1 of 50 collections hit it). The multi-library
union in the first fix widens the set of matched items, which makes this failure more
likely to appear.

Solution

fix(collections): sync matches across all bound libraries

Collections were historically 1:1 with a library via the legacy
library_collections.library_id. Migration 015 added the N:N membership table
library_collection_libraries; the listing and catalog open read paths were
already updated to use it, and GetByID already populates collection.LibraryIDs from
the N:N table (falling back to [LibraryID] when empty —
internal/catalog/library_collection_repo.go:169). Only the sync path was left
matching against the single legacy collection.LibraryID, so ReplaceItems (a full
overwrite) rebuilt membership from just one library.

The fix routes every sync matcher through the already-existing multi-folder helper
LibraryItemRepository.GetItemsInFolders (internal/catalog/library_repo.go:164,
media_folder_id = ANY($1)) and threads collection.LibraryIDs through the resolvers,
all in internal/catalog/library_collection_service.go:

  • MDBList path: syncMDBListCollection membership query now uses
    GetItemsInFolders(ctx, candidateIDs, collection.LibraryIDs)
    (library_collection_service.go:337).
  • resolveTMDBEntry (:1069) and resolveTraktEntry (:1104) take libraryIDs []int
    and call GetItemsInFolders internally (:1092, :1128).
  • All four call sites (tmdb_preset :472, tmdb_franchise :636, tmdb_discover :811,
    trakt_preset :973) pass collection.LibraryIDs.
  • "No match" warning strings updated to print the library set (%v over LibraryIDs).

Because GetByID guarantees LibraryIDs contains at least the legacy id, single-library
collections are byte-for-byte unaffected. No schema change.

This unblocks merging the duplicated per-library collections into single multi-library
collections.

fix(collections): dedupe matched items by media_item_id before ReplaceItems

Each sync resolves source entries (external IDs) to library content_ids and appends one
LibraryCollectionItemInput{MediaItemID: <content_id>} per matched entry, without
deduping by MediaItemID
. When two different source entries resolve to the same
library item — a remake/duplicate listing, one entry matched by IMDb and another by TMDB
pointing at the same local item, or (post-union) the same item present in more than one of
the collection's bound folders — the same content_id is appended twice.

library_collection_items has a composite primary key
(collection_id, media_item_id) (migrations/sql/001_schema.sql:1302).
ReplaceItems (internal/catalog/library_collection_repo.go:724) inserts each row
individually, so the second insert of a colliding media_item_id raises a duplicate-key
violation that fails the whole transaction. All five sync paths
(syncMDBListCollection, syncTMDBPresetCollection, syncTMDBFranchiseCollection,
syncTMDBDiscoverCollection, syncTraktPresetCollection) share the pattern.

The fix dedupes at the single choke point in ReplaceItems: a seen set skips repeated
media_item_ids (first occurrence wins, preserving rank order), and position is
renumbered over the surviving rows so it stays dense. This covers all five paths at once
and is why it lives in the repo rather than each matcher.

Separately, HandleSyncAdminCollection
(internal/api/handlers/library_collections.go:1559) mapped every non-sentinel sync
error to a generic 500 and logged nothing, which is why this was invisible on the
server. It now slog.Errors the underlying error with the collection id before returning
the 500.

Why bundle the two fixes: they touch the same five sync functions and the same
ReplaceItems write path, the branch is unmerged, and the first commit's multi-library
union directly increases the duplicate-collision rate the second commit defends against —
so shipping the union without the dedupe guard would ship a partial regression.

Risk / follow-ups

  • HandleGetLibraryCollectionItems (internal/api/handlers/library_collections.go) still
    gates on collection.LibraryID != libraryID. Only the pinned-collection carousel
    consumes it and it hides the rail silently on 404 — converting that to a membership
    check is a low-priority follow-up, out of scope here.
  • Retiring the legacy library_id column's role entirely is a larger change, deferred.
  • Deduping in ReplaceItems means position is renumbered over survivors; any caller
    relying on positions matching the pre-dedupe input slice would see denser values. No
    current caller does.
  • The collection-maker cron currently retries syncs at a reduced limit on a 500 as a
    lossy workaround for the dedupe bug; that workaround should be removed now this is fixed.
  • No new unit test was added for the union path: items/libraryItems are concrete
    DB-backed repositories (not interfaces), so a meaningful test requires a Postgres
    integration harness that does not yet exist in this package. Existing single-library
    tests cover the LibraryIDs == [LibraryID] path and stay green.

Verification

  • go build ./internal/catalog/... ./internal/api/handlers/...
  • go vet ./internal/catalog/...
  • go test ./internal/catalog/... (passes)
  • Manual diff review against the change spec; confirmed no remaining
    GetItemsInFolder/collection.LibraryID references in the sync matchers, and that the
    dedupe path preserves rank order and dense positions.
  • Original repro for the dedupe 500: an mdblist list whose 76–100 matched range contained
    a collider returned 500 at limit=100 and 200 at limit<=75; with the fix it syncs to
    N-1 distinct items without error.

AI-use disclosure

Implemented with AI assistance (Claude) from a human-authored handoff spec and bug report.

Summary by CodeRabbit

  • Bug Fixes
    • Improved library-collection syncing to match items across multiple library folders/IDs for external sources (TMDB, Trakt, MDB), ensuring “no match” and membership checks work with multi-library configurations.
  • Bug Fixes
    • Improved collection item replacement by deduplicating duplicate entries by media item and restoring consistent sequential item ordering.
  • Observability
    • Enhanced error logging during admin sync failures with collection context for easier troubleshooting.

@CoffeeKnyte
CoffeeKnyte requested a review from Quick104 as a code owner June 19, 2026 04:58
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 739f0b4c-9694-4fe6-a399-d94785e1aa8e

📥 Commits

Reviewing files that changed from the base of the PR and between baa5949 and dc03e16.

📒 Files selected for processing (2)
  • internal/api/handlers/library_collections.go
  • internal/catalog/library_collection_repo.go
✅ Files skipped from review due to trivial changes (1)
  • internal/api/handlers/library_collections.go

📝 Walkthrough

Walkthrough

Library collection sync is refactored to check item membership across multiple library IDs instead of a single library. resolveTMDBEntry and resolveTraktEntry parameter signatures change from libraryID int to libraryIDs []int, and their membership checks switch from GetItemsInFolder to GetItemsInFolders. All five sync functions pass collection.LibraryIDs to these resolvers and update "no match" warnings accordingly. ReplaceItems now deduplicates incoming items by media_item_id and renumbers positions sequentially. The sync handler adds error logging for sync failures.

Changes

Collection sync multi-library support and robustness

Layer / File(s) Summary
resolveTMDBEntry and resolveTraktEntry multi-library signatures
internal/catalog/library_collection_service.go
Both resolver functions change from libraryID int to libraryIDs []int and replace GetItemsInFolder with GetItemsInFolders, checking membership across all configured libraries. resolveTraktEntry iterates candidates and returns the first found in any library.
Sync function call sites updated to pass libraryIDs
internal/catalog/library_collection_service.go
syncMDBListCollection, syncTMDBPresetCollection, syncTMDBFranchiseCollection, syncTMDBDiscoverCollection, and syncTraktPresetCollection each pass collection.LibraryIDs to the updated resolver functions and reference collection.LibraryIDs in "no match" warning log messages.
Collection item deduplication in ReplaceItems
internal/catalog/library_collection_repo.go
Incoming items are deduplicated by media_item_id before insertion, skipping duplicates to prevent composite key violations. Positions are renumbered sequentially based on first occurrence order instead of using direct item position values.
Error logging in sync handler
internal/api/handlers/library_collections.go
HandleSyncAdminCollection now logs collection_id and error details via slog.Error for non-unsupported sync failures before returning the internal server error response.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • Quick104
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main fixes: correcting multi-library sync by matching all bound libraries and deduplicating items, which directly address the core bugs described in the PR objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/collections-sync-multi-library

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Collection sync resolved item membership against only the legacy
library_collections.library_id, so a collection bound to multiple
libraries (N:N library_collection_libraries) had its items collapsed to a
single library on every sync.

Switch the MDBList/TMDB/Trakt sync matchers to the existing
LibraryItemRepository.GetItemsInFolders over collection.LibraryIDs.
GetByID already populates LibraryIDs from the N:N table (falling back to
[LibraryID]), so single-library collections are unaffected. No schema
change; listing and the catalog open path were already N:N-aware.

Unblocks merging duplicated per-library collections into single
multi-library collections.
@CoffeeKnyte
CoffeeKnyte force-pushed the fix/collections-sync-multi-library branch from 84b2a0a to baa5949 Compare June 19, 2026 05:02
…eItems

A collection sync resolves source entries (external IDs) to library
content_ids and appends one item per matched entry without deduping by
media_item_id. When two different source entries resolve to the same
library item, the same content_id is appended twice; ReplaceItems then
hits the library_collection_items composite PK (collection_id,
media_item_id) with a duplicate-key violation, failing the whole sync
with an HTTP 500 and zero items.

The multi-library union added in the previous commit (GetItemsInFolders
over collection.LibraryIDs) widens the matched set and so raises the
collision probability, making this latent bug more likely to fire.

Dedupe at the single choke point in ReplaceItems (first occurrence wins,
preserving rank order) so all five sync paths are covered at once, and
renumber position over the surviving rows so it stays dense.

Also log the underlying error in HandleSyncAdminCollection, which
previously mapped every non-sentinel sync error to a generic 500 with
no log line, making this failure invisible on the server.
@CoffeeKnyte CoffeeKnyte changed the title fix(collections): sync matches across all bound libraries fix(collections): correct multi-library sync — match all bound libraries and dedupe items Jun 20, 2026
@CoffeeKnyte

CoffeeKnyte commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Added a second commit (dc03e162) while testing this branch.

It fixes a dedupe bug: if the same media item showed up twice in a collection, the sync crashed on a primary-key collision (library_collection_items is keyed on collection_id, media_item_id) — the whole sync 500'd with zero items, and the handler logged nothing so it was invisible.

The duplicate happens when the same item appears more than once — either because it's in multiple of the collection's libraries, or because the mdblist itself lists it twice. The multi-library union in this PR makes it more likely, which is how it surfaced.

The commit dedupes by media_item_id in ReplaceItems (first one wins, positions renumbered) so all five sync paths are covered in one place, and adds a slog.Error so failures show up in the logs. Bundled here since the union change is what makes the collision likely.

@Quick104
Quick104 merged commit 9881cf5 into main Jun 26, 2026
1 check passed
@Quick104
Quick104 deleted the fix/collections-sync-multi-library branch June 26, 2026 16:28
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…ies and dedupe items (Silo-Server#184)

* fix(collections): sync matches across all bound libraries

Collection sync resolved item membership against only the legacy
library_collections.library_id, so a collection bound to multiple
libraries (N:N library_collection_libraries) had its items collapsed to a
single library on every sync.

Switch the MDBList/TMDB/Trakt sync matchers to the existing
LibraryItemRepository.GetItemsInFolders over collection.LibraryIDs.
GetByID already populates LibraryIDs from the N:N table (falling back to
[LibraryID]), so single-library collections are unaffected. No schema
change; listing and the catalog open path were already N:N-aware.

Unblocks merging duplicated per-library collections into single
multi-library collections.

* fix(collections): dedupe matched items by media_item_id before ReplaceItems

A collection sync resolves source entries (external IDs) to library
content_ids and appends one item per matched entry without deduping by
media_item_id. When two different source entries resolve to the same
library item, the same content_id is appended twice; ReplaceItems then
hits the library_collection_items composite PK (collection_id,
media_item_id) with a duplicate-key violation, failing the whole sync
with an HTTP 500 and zero items.

The multi-library union added in the previous commit (GetItemsInFolders
over collection.LibraryIDs) widens the matched set and so raises the
collision probability, making this latent bug more likely to fire.

Dedupe at the single choke point in ReplaceItems (first occurrence wins,
preserving rank order) so all five sync paths are covered at once, and
renumber position over the surviving rows so it stays dense.

Also log the underlying error in HandleSyncAdminCollection, which
previously mapped every non-sentinel sync error to a generic 500 with
no log line, making this failure invisible on the server.
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.

2 participants