Skip to content

feat(watchsync): sync watchlists with Trakt/Simkl/MDBList - #227

Merged
Quick104 merged 3 commits into
mainfrom
claude/vibrant-pare-274bda
Jun 26, 2026
Merged

Quick104 merged 3 commits into
mainfrom
claude/vibrant-pare-274bda

Conversation

@Quick104

@Quick104 Quick104 commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Watch-providers synced favorites but not a user's watchlist. This adds watchlist sync for Trakt, Simkl, and MDBList, plus auto-removal of watched items and optional MDBList sort-order mirroring.

What changed

  • Generalized pipeline — the favorites sync becomes one ListKind-parameterized pipeline (internal/watchsync/lists.go) that drives both favorites and watchlist; per-favorites service methods are replaced by kind-generic ones. The shadow table watch_provider_favorite_items → watch_provider_list_items with a list_kind discriminator.
  • Providers
    • Trakt: adds watchlist sync via /sync/watchlist* (a list distinct from favorites).
    • Simkl: adds plan-to-watch sync (its watchlist) — Simkl gets list sync for the first time.
    • MDBList: re-mapped favorites → watchlist (its only list is a watchlist). Capabilities now report import_favorites=false / import_watchlist=true; the migration re-binds existing MDBList connections.
  • Auto-remove watched from watchlist — standalone, default-on profile preference (user_profiles.remove_watched_from_watchlist): a movie leaves the watchlist when watched, a series only once every episode is watched. Implemented as watchstate.CompletionObserver (internal/watchlist.Maintainer), wired into the native mark-watched, playback-stop, and Jellyfin-compat mark-played paths. Imports do not trigger it.
  • Optional MDBList sort-order mirroring — opt-in, capability-gated toggle mirrors MDBList's watchlist order into Silo via user_watchlist.sort_index; ListWatchlist orders by sort_index then added_at, so both /api/v1/watchlist and the catalog watchlist view inherit it. Disabling reverts to newest-first.
  • Timing — local add/remove pushes to connected providers in real time (removals gated by the opt-in removals toggle); the hourly job handles inbound import + retry/reconcile.
  • Web — watch-provider settings gain watchlist import/export/removals toggles, a "mirror watchlist order" toggle, and watchlist sync stats.

Why this approach

The favorites and watchlist pipelines are ~90% identical. Generalizing into one kind-parameterized path follows CLAUDE.md's anti-duplication guidance instead of cloning the favorites machinery.

API / compat

Additive-only per the Silo v1 rule: all new fields on ConnectionStatus / Capabilities / ConnectionUpdate / SyncRun and the web types are additions — no existing field renamed, removed, or retyped.

Risks / follow-up

  • MDBList capability flip is intentional and client-visible — silo-android / silo-apple may need to surface MDBList under the watchlist (not favorites) UI.
  • Existing MDBList users: their MDBList list previously mirrored Silo favorites and now mirrors Silo watchlist; the first post-migration sync is a union (removals default off), so nothing is destructively purged.
  • Order mirroring reflects the order MDBList returns from /watchlist/items (couldn't confirm against MDBList docs — Cloudflare-blocked). If it ever diverges from the configured UI sort, adding an explicit sort param is a small follow-up.

Testing

  • New unit tests: auto-remove maintainer (movie/series/partial/preference-off/dedupe) and watchlist sort-order (apply/re-sync/clear). Provider + service tests updated.
  • go build ./..., go test (affected packages), make migrate-validate, make verify-local-paths, and web prettier/eslint/tsc all pass. (The only failing tests in the tree are pre-existing, environment-dependent PID-liveness tests in jellycompat, untouched here.)

Note for reviewers: please link the watch-providers capability epic / scope item (Part of #NNN) — I didn't have the issue number.

AI-use disclosure

Implemented with Claude Code (Claude Opus 4.8).

Summary by CodeRabbit

  • New Features

    • Added watchlist synchronization for supported providers (import/export/removal), including optional mirroring of watchlist order.
    • Added automatic watchlist cleanup when items are marked fully watched, working consistently across playback and Jellyfin-compat “mark watched” flows.
    • Extended watch-provider settings and sync run stats with watchlist sync toggles, last-sync tracking, and additional watchlist counters.
  • Bug Fixes

    • Improved deterministic watchlist ordering by prioritizing synced items’ stored sort order with a clear fallback for locally added items.
    • Ensured watched-item removal honors the user’s “remove watched from watchlist” preference.

Extend the watch-providers feature to sync a user's watchlist, generalizing
the existing favorites pipeline rather than duplicating it.

What changed
- Generalize the favorites sync into one ListKind-parameterized pipeline
  (internal/watchsync/lists.go) driving both favorites and watchlist; the
  per-favorites service methods are replaced by kind-generic ones. The shadow
  table watch_provider_favorite_items becomes watch_provider_list_items with a
  list_kind discriminator.
- Providers: Trakt gains watchlist sync (/sync/watchlist, distinct from
  favorites); Simkl gains plan-to-watch sync; MDBList is re-mapped from
  favorites to watchlist (its only list is a watchlist) — its capabilities now
  report import_favorites=false / import_watchlist=true, and the migration
  re-binds existing MDBList connections.
- Auto-remove watched items from the watchlist: a standalone, default-on
  profile preference (user_profiles.remove_watched_from_watchlist) removes a
  movie when watched and a series once every episode is watched. Implemented as
  watchstate.CompletionObserver (internal/watchlist.Maintainer), wired into the
  manual mark-watched, playback-stop, and jellycompat mark-played paths.
- Optional MDBList sort-order mirroring: an opt-in, capability-gated toggle
  mirrors MDBList's watchlist order into Silo via user_watchlist.sort_index;
  ListWatchlist orders by sort_index then added_at, so both /api/v1/watchlist
  and the catalog watchlist view inherit it.
- Real-time + scheduled: local add/remove pushes to connected providers
  immediately (removals gated by the opt-in removals toggle); the hourly job is
  the inbound/import + retry/reconcile path.
- Web: watch-provider settings gain watchlist import/export/removals and
  "mirror watchlist order" toggles plus watchlist sync stats.

Why
- The favorites and watchlist pipelines are ~90% identical; generalizing keeps
  one code path (per CLAUDE.md's anti-duplication guidance) instead of cloning.

API/compat
- All new fields on ConnectionStatus/Capabilities/ConnectionUpdate/SyncRun and
  the web types are additive (Silo v1 additive-only rule). No existing field is
  renamed, removed, or retyped.

Risks / follow-up
- MDBList capability flip is intentional and client-visible: silo-android /
  silo-apple may need to surface MDBList under the watchlist (not favorites) UI.
- MDBList existing users: their MDBList list previously mirrored Silo favorites
  and now mirrors Silo watchlist; the first post-migration sync is a union
  (removals default off), so nothing is destructively purged.
- Order mirroring reflects the order MDBList returns from /watchlist/items
  (couldn't confirm against their docs — Cloudflare-blocked); if it ever
  diverges from the UI sort, a sort param is the small follow-up.

Tests: new maintainer (auto-remove) and watchlist-order unit tests; provider +
service tests updated. go build, go test (affected pkgs), migrate-validate,
verify-local-paths, web prettier/eslint/tsc all pass.

AI-use disclosure: implemented with Claude Code (Claude Opus 4.8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds watch-completion observation, automatic watchlist removal, ordered watchlist storage, unified list synchronization, provider watchlist support, and watch-provider API/UI updates.

Changes

Watch completion and list wiring

Layer / File(s) Summary
Completion observer wiring
cmd/silo/main.go, internal/api/handlers/favorites.go, internal/api/handlers/items.go, internal/api/handlers/playback.go, internal/api/router.go, internal/jellycompat/server.go, internal/jellycompat/router.go, internal/jellycompat/userdata_direct.go, internal/watchstate/service.go
watchstate.Service now notifies a completion observer, and the API/router/compat startup paths wire that observer plus the new local list dispatcher into handlers.
Watchlist storage and migrations
internal/access/resolver_test.go, internal/jellycompat/content_direct_test.go, internal/userdb/*, internal/userstore/*, migrations/sql/20260626174211_watch_provider_watchlist.sql, migrations/sql/20260626185649_watchlist_sort_order.sql
The user-store interface, SQLite/Postgres implementations, schema, migrations, and tests add watchlist timestamps, ordering, and removal preference support.
Watchlist maintainer
internal/watchlist/maintainer.go, internal/watchlist/maintainer_test.go
watchlist.Maintainer removes fully watched items from a user's watchlist and emits local watchlist removal events.

Watchsync contracts and repository state

Layer / File(s) Summary
Watchsync contracts and repository state
internal/watchsync/types.go, internal/watchsync/repository.go, internal/watchsync/service.go, internal/watchsync/service_test.go
Watchsync types, repository queries, and connection status/update handling gain list-item state, watchlist counters, and watchlist enablement fields.

Unified list sync engine and provider adapters

Layer / File(s) Summary
Unified list sync engine
internal/watchsync/lists.go, internal/watchsync/service.go, internal/watchsync/service_test.go
watchsync.Service now processes favorites and watchlist through shared list bindings for import, export, removal, and local list events.
Provider watchlist adapters
internal/watchsync/providers/mdblist/*, internal/watchsync/providers/simkl/*, internal/watchsync/providers/trakt/*
MDBList, Simkl, and Trakt provider capabilities and watchlist fetch/export/remove methods are updated to use watchlist semantics.

Web watch-provider UI

Layer / File(s) Summary
Web watch-provider UI
web/src/hooks/queries/watchProviders.ts, web/src/pages/settings/WatchProvidersSettings.tsx
The watch-provider query models and settings UI add watchlist sync fields, counts, and toggles.

Sequence Diagram(s)

sequenceDiagram
  participant PlaybackHandler
  participant WatchState as watchstate.Service
  participant Maintainer as watchlist.Maintainer
  participant PersonalDataHandler
  participant LocalListEventDispatcher
  PlaybackHandler->>WatchState: persist stop / mark watched
  WatchState->>Maintainer: HandleWatchedCompleted(...)
  Maintainer->>PersonalDataHandler: remove watchlist item
  Maintainer->>LocalListEventDispatcher: HandleLocalListEvent(ListKindWatchlist, ListChangeRemoved)
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related PRs

  • Silo-Server/silo-server#179: Also changes internal/watchstate completion handling and watched/completed propagation, which is directly related to the new completion-observer flow.

Suggested labels

v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.78% 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 clearly summarizes the main change: adding watchlist sync support for Trakt, Simkl, and MDBList.
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.
✨ 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 claude/vibrant-pare-274bda

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jun 26, 2026

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

🧹 Nitpick comments (1)
internal/watchsync/service_test.go (1)

276-290: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the fake’s list-state transitions aligned with Postgres.

The fake replaces the whole state on upsert and mark methods do not clear LastError, while the Postgres implementation preserves/merges fields and clears errors on successful exported/removed transitions. Tests using this fake can miss retry and merge regressions.

Also applies to: 348-376

🤖 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/watchsync/service_test.go` around lines 276 - 290, The
serviceFakeRepo list-state behavior diverges from Postgres because
UpsertListItemStates replaces the whole record and the mark methods keep
LastError around, which can hide retry/merge regressions. Update the fake’s
UpsertListItemStates and the related exported/removed transition methods to
mirror the Postgres semantics by merging preserved fields instead of wholesale
replacement and clearing LastError on successful transitions, using the existing
serviceFakeRepo and ListItemState symbols as the reference points.
🤖 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/watchlist/maintainer.go`:
- Around line 121-145: The lookup flow in the watchlist cleanup path is
swallowing real catalog errors by treating any m.items.GetByID failure as a
non-catalog item and falling through to episode lookup. Update the logic in the
watchlist manager method that resolves mediaItemID so only a true “not found”
result takes the episode path, while unexpected repository errors are returned
to the caller. Keep the existing seriesCandidate and episodes.GetByID behavior,
but propagate transient catalog lookup failures instead of silently no-oping.

In `@internal/watchsync/lists.go`:
- Around line 411-427: The per-item result handling in the export loop only
marks items as exported or not found, so failed or omitted items stay pending
and can be retried forever. Update the item-processing block in the loop around
s.repo.MarkListItemExported and s.repo.MarkListItemError to also detect
exportResult.Failed and any toSend item missing from all provider result sets,
then persist a failure state or error via the existing repository methods so the
pending queue can advance. Use the existing symbols exportResultSentSet,
exportResult.NotFound, and the item iteration over toSend to add the missing
failure handling consistently.
- Around line 461-480: The removal flow in removePendingListItems and the
realtime removal path is marking items remote-removed without honoring each
item’s actual outcome. Update the logic around removeItems, exportResultSentSet,
and MarkListItemRemoteRemoved so only Sent and NotFound are treated as removed,
while Failed items are left pending or explicitly marked with MarkListItemError
for retry; keep the per-item outcome handling consistent in both branches that
process list item removals.
- Around line 622-651: The exportLocalListItems flow is still passing the
original items slice into b.exportItems, so the normalized ProviderItemKey
values and filtered-out invalid entries are not reflected in the provider call.
Build a normalized slice inside exportLocalListItems while deriving
providerItemKeyForLocalFavorite, skipping empty keys, and then pass that
sanitized slice to b.exportItems instead of the raw items input; keep the
UpsertListItemStates path aligned with the same normalized data.

In `@internal/watchsync/repository.go`:
- Around line 795-807: The pending-removals query in ListPendingListItemRemovals
is filtering out any row with a non-empty last_error, which permanently excludes
items that previously failed removal. Update the WHERE clause so
removePendingListItems/MarkListItemError failures remain eligible for later
scheduled retry, while still preserving the existing filters for connection_id,
list_kind, local_present, and remote_present.

In `@internal/watchsync/service.go`:
- Around line 194-216: Update UpdateConnection and clearWatchlistOrder in
Service so failures to clear stored watchlist order are surfaced instead of only
logged. Make clearWatchlistOrder return an error when storeProvider.ForUser or
store.ReplaceWatchlistOrder fails, and have UpdateConnection propagate that
error after saving the connection so disabling SyncWatchlistOrderEnabled cannot
succeed while old sort_index ordering remains. Use the existing Service,
UpdateConnection, and clearWatchlistOrder symbols to locate the change.

In `@web/src/pages/settings/WatchProvidersSettings.tsx`:
- Line 566: The exported “sent” total in the settings view is undercounting
removal-only syncs because it only sums watched, favorites, and watchlist, while
`deriveRunInfo` already tracks `favoriteRemovals` and does not track watchlist
removals at all. Update the total shown in `WatchProvidersSettings` to include
removal activity appropriately, and if watchlist removals are intended to be
reported, add tracking for them in `deriveRunInfo` and display them consistently
wherever the sent total is rendered.

---

Nitpick comments:
In `@internal/watchsync/service_test.go`:
- Around line 276-290: The serviceFakeRepo list-state behavior diverges from
Postgres because UpsertListItemStates replaces the whole record and the mark
methods keep LastError around, which can hide retry/merge regressions. Update
the fake’s UpsertListItemStates and the related exported/removed transition
methods to mirror the Postgres semantics by merging preserved fields instead of
wholesale replacement and clearing LastError on successful transitions, using
the existing serviceFakeRepo and ListItemState symbols as the reference points.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6b8337aa-b755-4b6f-8352-9997a8738709

📥 Commits

Reviewing files that changed from the base of the PR and between 659e62a and 12a5183.

📒 Files selected for processing (35)
  • cmd/silo/main.go
  • internal/access/resolver_test.go
  • internal/api/handlers/favorites.go
  • internal/api/handlers/items.go
  • internal/api/handlers/playback.go
  • internal/api/router.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/userdata_direct.go
  • internal/userdb/favorites.go
  • internal/userdb/migrate.go
  • internal/userdb/schema.go
  • internal/userdb/sqlitestore.go
  • internal/userdb/watchlist_order_test.go
  • internal/userstore/pgstore/favorites.go
  • internal/userstore/store.go
  • internal/watchlist/maintainer.go
  • internal/watchlist/maintainer_test.go
  • internal/watchstate/service.go
  • internal/watchsync/lists.go
  • internal/watchsync/providers/mdblist/provider.go
  • internal/watchsync/providers/mdblist/provider_test.go
  • internal/watchsync/providers/simkl/provider.go
  • internal/watchsync/providers/simkl/provider_test.go
  • internal/watchsync/providers/trakt/provider.go
  • internal/watchsync/providers/trakt/provider_test.go
  • internal/watchsync/repository.go
  • internal/watchsync/service.go
  • internal/watchsync/service_test.go
  • internal/watchsync/types.go
  • migrations/sql/20260626174211_watch_provider_watchlist.sql
  • migrations/sql/20260626185649_watchlist_sort_order.sql
  • web/src/hooks/queries/watchProviders.ts
  • web/src/pages/settings/WatchProvidersSettings.tsx

Comment thread internal/watchlist/maintainer.go Resolved
Comment thread internal/watchsync/lists.go Resolved
Comment thread internal/watchsync/lists.go Resolved
Comment thread internal/watchsync/lists.go Resolved
Comment on lines +795 to 807
func (r *PostgresRepository) ListPendingListItemRemovals(ctx context.Context, connectionID string, kind ListKind, limit int) ([]ListItemState, error) {
if limit <= 0 || limit > 100 {
limit = 100
}
rows, err := r.pool.Query(ctx, `
SELECT id::text, connection_id::text, media_item_id, provider_item_key, kind, title, year,
remote_present, local_present, last_seen_remote_at, last_seen_local_at,
last_exported_at, last_removed_remote_at, last_removed_local_at, last_error, created_at, updated_at
FROM watch_provider_favorite_items
SELECT `+listItemStateColumns+`
FROM watch_provider_list_items
WHERE connection_id = $1::uuid
AND list_kind = $2
AND local_present = false
AND remote_present = true
AND last_error = ''
ORDER BY last_removed_local_at ASC NULLS LAST, updated_at ASC

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep failed removals eligible for scheduled retry.

removePendingListItems records provider-call failures with MarkListItemError, but this query then excludes those rows forever via last_error = ''. A transient removal failure will not be retried by the hourly reconcile unless another local event clears the error.

Proposed fix
 		  AND local_present = false
 		  AND remote_present = true
-		  AND last_error = ''
 		ORDER BY last_removed_local_at ASC NULLS LAST, updated_at ASC
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (r *PostgresRepository) ListPendingListItemRemovals(ctx context.Context, connectionID string, kind ListKind, limit int) ([]ListItemState, error) {
if limit <= 0 || limit > 100 {
limit = 100
}
rows, err := r.pool.Query(ctx, `
SELECT id::text, connection_id::text, media_item_id, provider_item_key, kind, title, year,
remote_present, local_present, last_seen_remote_at, last_seen_local_at,
last_exported_at, last_removed_remote_at, last_removed_local_at, last_error, created_at, updated_at
FROM watch_provider_favorite_items
SELECT `+listItemStateColumns+`
FROM watch_provider_list_items
WHERE connection_id = $1::uuid
AND list_kind = $2
AND local_present = false
AND remote_present = true
AND last_error = ''
ORDER BY last_removed_local_at ASC NULLS LAST, updated_at ASC
func (r *PostgresRepository) ListPendingListItemRemovals(ctx context.Context, connectionID string, kind ListKind, limit int) ([]ListItemState, error) {
if limit <= 0 || limit > 100 {
limit = 100
}
rows, err := r.pool.Query(ctx, `
SELECT `+listItemStateColumns+`
FROM watch_provider_list_items
WHERE connection_id = $1::uuid
AND list_kind = $2
AND local_present = false
AND remote_present = true
ORDER BY last_removed_local_at ASC NULLS LAST, updated_at ASC
🤖 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/watchsync/repository.go` around lines 795 - 807, The
pending-removals query in ListPendingListItemRemovals is filtering out any row
with a non-empty last_error, which permanently excludes items that previously
failed removal. Update the WHERE clause so
removePendingListItems/MarkListItemError failures remain eligible for later
scheduled retry, while still preserving the existing filters for connection_id,
list_kind, local_present, and remote_present.

Comment thread internal/watchsync/service.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/metadata/provider_id_integrity.go (1)

916-923: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant OR branch makes the provider_item_key predicate dead.

dest.media_item_id = $2 is already asserted unconditionally on Line 920, so the second branch of (src.provider_item_key = dest.provider_item_key OR dest.media_item_id = $2) is always true, which makes the whole OR always true and the provider_item_key comparison inert. The resulting behavior (delete every source row sharing connection_id + list_kind with a destination row) is correct for the (connection_id, list_kind, media_item_id) uniqueness constraint, but the dead clause is misleading. Consider dropping it to match the simpler dedup pattern used by the other steps.

♻️ Proposed simplification
 	{"delete duplicate watch provider list items", `
 			DELETE FROM watch_provider_list_items src
 			USING watch_provider_list_items dest
 			WHERE src.media_item_id = $1
 			  AND dest.media_item_id = $2
 			  AND src.connection_id = dest.connection_id
-			  AND src.list_kind = dest.list_kind
-			  AND (src.provider_item_key = dest.provider_item_key OR dest.media_item_id = $2)`},
+			  AND src.list_kind = dest.list_kind`},
🤖 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/metadata/provider_id_integrity.go` around lines 916 - 923, The
DELETE statement in the provider ID integrity dedup step has a dead `OR
dest.media_item_id = $2` branch inside the `delete duplicate watch provider list
items` query, which makes the `provider_item_key` comparison inert. Simplify the
SQL in `provider_id_integrity.go` by removing the redundant `provider_item_key`
predicate/`OR` branch and keep only the actual uniqueness match used by this
step (`connection_id` + `list_kind` with the destination media item constraint),
matching the pattern used in the other dedup queries.
🤖 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/metadata/provider_id_integrity.go`:
- Around line 916-923: The DELETE statement in the provider ID integrity dedup
step has a dead `OR dest.media_item_id = $2` branch inside the `delete duplicate
watch provider list items` query, which makes the `provider_item_key` comparison
inert. Simplify the SQL in `provider_id_integrity.go` by removing the redundant
`provider_item_key` predicate/`OR` branch and keep only the actual uniqueness
match used by this step (`connection_id` + `list_kind` with the destination
media item constraint), matching the pattern used in the other dedup queries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5770929b-8525-45ac-a43c-8fe12a465328

📥 Commits

Reviewing files that changed from the base of the PR and between 12a5183 and 3bafadd.

📒 Files selected for processing (4)
  • internal/catalog/orphan_cleanup.go
  • internal/catalog/orphan_cleanup_test.go
  • internal/metadata/provider_id_integrity.go
  • internal/metadata/provider_id_integrity_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/catalog/orphan_cleanup_test.go

Addresses CodeRabbit review on #227:
- maintainer: propagate transient catalog lookup errors instead of silently
  treating every items.GetByID failure as "maybe an episode".
- exportList: mark every queued item not confirmed sent (not_found, failed, or
  omitted) so the pending loop always advances; the next run's upsert clears the
  error and re-attempts, so transient failures still retry.
- removePendingListItems + realtime removal: treat Sent and NotFound as
  reconciled; leave true failures pending (no last_error, which would strand
  them from the removal query) so the scheduled run retries, using in-memory
  dedupe to terminate the loop.
- exportLocalListItems: send the normalized items (with computed
  ProviderItemKey), not the original event slice.
- UpdateConnection: clear mirrored watchlist order before persisting the disable
  and propagate failures, so a failed clear can't report "disabled" while
  sort_index ordering is still active.
- web: include favorite + watchlist removal counts in the exported "sent" total.
- test: align serviceFakeRepo list-state with Postgres (clear last_error on
  successful transitions); add maintainer error-propagation test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit review in fc932125. Summary of each finding:

  1. maintainer.go — swallowed catalog lookup errors ✅ resolveCandidate now records a real items.GetByID error and surfaces it when the episode path also can't resolve the id (a not-found miss still falls through to the episode lookup). Added TestMaintainerPropagatesItemLookupError.
  2. lists.go export loop — items stuck pending ✅ Every queued item not confirmed Sent is now marked with an error (via new exportFailureReason, covering Failed, NotFound, and omitted), so the loop always advances. The next run's UpsertListItemStates clears last_error, so transient failures still retry across runs.
  3. lists.go removals — outcomes ignored ✅ removePendingListItems and the realtime removal path now treat Sent and NotFound as reconciled, and leave true failures pending.
  4. repository.go — failed removals never retried ✅ Removal failures no longer set last_error (which the removal query filters out and there's no per-run upsert to clear). Instead the loop uses in-memory dedupe to terminate, leaving failed rows eligible for the next scheduled reconcile.
  5. lists.go:651 — sent the original slice ✅ exportLocalListItems now sends the normalized toSend slice (with computed ProviderItemKey).
  6. service.go — order-clear failure swallowed ✅ UpdateConnection now clears the mirrored order before persisting the disable and propagates the error, so a failed clear leaves both the order and the toggle intact (retriable) instead of reporting "disabled" while sort_index ordering is still active.
  7. web — exported total omitted removals ✅ The "Exported … sent" total now includes favorite + watchlist removal counts.

Nitpick: aligned serviceFakeRepo mark methods to clear last_error on successful transitions, mirroring Postgres.

go build ./..., affected go test, make migrate-validate, make verify-local-paths, and web prettier/eslint/tsc all pass. Also rebased onto 3bafaddd (thanks for catching the two missed watch_provider_favorite_items → watch_provider_list_items references).

@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

🤖 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/watchlist/maintainer_test.go`:
- Around line 230-231: The test in Maintainer.process only checks for any
non-nil failure, so it can pass on the wrong error. Update the assertion to
verify the returned error preserves the original transient lookup failure by
comparing it with the sentinel error used in the test via errors.Is, using the
existing m.process call and the boom error reference.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 42d125d0-066d-4ff7-9108-7b36d6005373

📥 Commits

Reviewing files that changed from the base of the PR and between 3bafadd and fc93212.

📒 Files selected for processing (6)
  • internal/watchlist/maintainer.go
  • internal/watchlist/maintainer_test.go
  • internal/watchsync/lists.go
  • internal/watchsync/service.go
  • internal/watchsync/service_test.go
  • web/src/pages/settings/WatchProvidersSettings.tsx
🚧 Files skipped from review as they are similar to previous changes (5)
  • web/src/pages/settings/WatchProvidersSettings.tsx
  • internal/watchlist/maintainer.go
  • internal/watchsync/lists.go
  • internal/watchsync/service_test.go
  • internal/watchsync/service.go

Comment on lines +230 to +231
if err := m.process(context.Background(), 7, "profile-1", []string{"x"}); err == nil {
t.Fatal("a transient catalog lookup error must propagate, not be swallowed")

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the specific propagated error, not just any failure.

This currently passes if process returns an unrelated error. Check errors.Is(err, boom) so the test actually verifies the lookup error is preserved through Maintainer.process.

Suggested change
-	if err := m.process(context.Background(), 7, "profile-1", []string{"x"}); err == nil {
-		t.Fatal("a transient catalog lookup error must propagate, not be swallowed")
-	}
+	if err := m.process(context.Background(), 7, "profile-1", []string{"x"}); !errors.Is(err, boom) {
+		t.Fatalf("expected propagated lookup error %v, got %v", boom, err)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := m.process(context.Background(), 7, "profile-1", []string{"x"}); err == nil {
t.Fatal("a transient catalog lookup error must propagate, not be swallowed")
if err := m.process(context.Background(), 7, "profile-1", []string{"x"}); !errors.Is(err, boom) {
t.Fatalf("expected propagated lookup error %v, got %v", boom, err)
}
🤖 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/watchlist/maintainer_test.go` around lines 230 - 231, The test in
Maintainer.process only checks for any non-nil failure, so it can pass on the
wrong error. Update the assertion to verify the returned error preserves the
original transient lookup failure by comparing it with the sentinel error used
in the test via errors.Is, using the existing m.process call and the boom error
reference.

@Quick104
Quick104 merged commit 392bc3b into main Jun 26, 2026
3 checks passed
@Quick104
Quick104 deleted the claude/vibrant-pare-274bda branch June 26, 2026 20:05
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…r#227)

* feat(watchsync): sync watchlists with Trakt/Simkl/MDBList

Extend the watch-providers feature to sync a user's watchlist, generalizing
the existing favorites pipeline rather than duplicating it.

What changed
- Generalize the favorites sync into one ListKind-parameterized pipeline
  (internal/watchsync/lists.go) driving both favorites and watchlist; the
  per-favorites service methods are replaced by kind-generic ones. The shadow
  table watch_provider_favorite_items becomes watch_provider_list_items with a
  list_kind discriminator.
- Providers: Trakt gains watchlist sync (/sync/watchlist, distinct from
  favorites); Simkl gains plan-to-watch sync; MDBList is re-mapped from
  favorites to watchlist (its only list is a watchlist) — its capabilities now
  report import_favorites=false / import_watchlist=true, and the migration
  re-binds existing MDBList connections.
- Auto-remove watched items from the watchlist: a standalone, default-on
  profile preference (user_profiles.remove_watched_from_watchlist) removes a
  movie when watched and a series once every episode is watched. Implemented as
  watchstate.CompletionObserver (internal/watchlist.Maintainer), wired into the
  manual mark-watched, playback-stop, and jellycompat mark-played paths.
- Optional MDBList sort-order mirroring: an opt-in, capability-gated toggle
  mirrors MDBList's watchlist order into Silo via user_watchlist.sort_index;
  ListWatchlist orders by sort_index then added_at, so both /api/v1/watchlist
  and the catalog watchlist view inherit it.
- Real-time + scheduled: local add/remove pushes to connected providers
  immediately (removals gated by the opt-in removals toggle); the hourly job is
  the inbound/import + retry/reconcile path.
- Web: watch-provider settings gain watchlist import/export/removals and
  "mirror watchlist order" toggles plus watchlist sync stats.

Why
- The favorites and watchlist pipelines are ~90% identical; generalizing keeps
  one code path (per CLAUDE.md's anti-duplication guidance) instead of cloning.

API/compat
- All new fields on ConnectionStatus/Capabilities/ConnectionUpdate/SyncRun and
  the web types are additive (Silo v1 additive-only rule). No existing field is
  renamed, removed, or retyped.

Risks / follow-up
- MDBList capability flip is intentional and client-visible: silo-android /
  silo-apple may need to surface MDBList under the watchlist (not favorites) UI.
- MDBList existing users: their MDBList list previously mirrored Silo favorites
  and now mirrors Silo watchlist; the first post-migration sync is a union
  (removals default off), so nothing is destructively purged.
- Order mirroring reflects the order MDBList returns from /watchlist/items
  (couldn't confirm against their docs — Cloudflare-blocked); if it ever
  diverges from the UI sort, a sort param is the small follow-up.

Tests: new maintainer (auto-remove) and watchlist-order unit tests; provider +
service tests updated. go build, go test (affected pkgs), migrate-validate,
verify-local-paths, web prettier/eslint/tsc all pass.

AI-use disclosure: implemented with Claude Code (Claude Opus 4.8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(watchsync): update list shadow table references

* fix(watchsync): address review — retry/progress + error propagation

Addresses CodeRabbit review on Silo-Server#227:
- maintainer: propagate transient catalog lookup errors instead of silently
  treating every items.GetByID failure as "maybe an episode".
- exportList: mark every queued item not confirmed sent (not_found, failed, or
  omitted) so the pending loop always advances; the next run's upsert clears the
  error and re-attempts, so transient failures still retry.
- removePendingListItems + realtime removal: treat Sent and NotFound as
  reconciled; leave true failures pending (no last_error, which would strand
  them from the removal query) so the scheduled run retries, using in-memory
  dedupe to terminate the loop.
- exportLocalListItems: send the normalized items (with computed
  ProviderItemKey), not the original event slice.
- UpdateConnection: clear mirrored watchlist order before persisting the disable
  and propagate failures, so a failed clear can't report "disabled" while
  sort_index ordering is still active.
- web: include favorite + watchlist removal counts in the exported "sent" total.
- test: align serviceFakeRepo list-state with Postgres (clear last_error on
  successful transitions); add maintainer error-propagation test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant