Skip to content

fix(watchsync): correct Trakt TV episode sync payload - #254

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Pukabyte:fix/trakt-episode-sync
Jul 1, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Pukabyte:fix/trakt-episode-sync

Conversation

@Pukabyte

@Pukabyte Pukabyte commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two related defects broke Trakt TV-episode watch sync:

  1. Wrong series targeted on series mark-watched. Empty Trakt episode ids were being emitted, so a series-level mark-watched could target the wrong show.
  2. Episode history dropped by Trakt. Episode history exports were emitted into the flat episodes[] array with a bogus sibling show object, which Trakt rejected — episodes never synced.

Fix

  • Omit empty Trakt episode ids so series mark-watched resolves to the correct show.
  • Emit TV episodes via a valid nested shows[].seasons[].episodes[] payload instead of the flat array, matching Trakt's history contract.

Notes

  • Scope is limited to internal/watchsync/providers/trakt/ plus a small internal/watchstate/identity.go helper.
  • Unit tests added/updated in provider_test.go; go test ./internal/watchsync/providers/trakt/ passes.

AI-use disclosure: authored with AI assistance.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Trakt history exports and removals now support nested show-based episode payloads when episode-specific IDs aren’t available.
  • Bug Fixes

    • Episode watches now use more complete identity data, improving how history entries are matched and exported.
    • Multiple episodes from the same show and season are now grouped more consistently in history payloads.

Pukabyte and others added 2 commits July 1, 2026 07:05
…argets the right show

omitempty on a struct value is a no-op in encoding/json, so the history
export sent all-zero episode ids ({tmdb:0,tvdb:0}); Trakt matched the
degenerate id to one default show, mis-recording every watched series.
Make episode IDs a *traktIDs pointer and attach it only when a real id
exists, else use the show + season/number fallback (mirroring scrobble).
Adds a debug log on the show-fallback path and payload tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Episode history exports were dropped by Trakt because they were emitted
into the flat episodes[] array with a bogus sibling show object plus
season/number keys — a shape the Trakt API does not accept, so it
silently discarded them (200/201 with no history recorded). Movies were
unaffected since they always carry their own external IDs.

Two coordinated changes:

- watchstate/identity.go: ResolveHistoryIdentity now carries the
  episode's own imdb/tmdb/tvdb IDs (already stored on the episodes
  table) so episodes with real IDs export via the flat episodes[].ids
  form, matching how movies work.

- watchsync/providers/trakt/provider.go: episodes without their own ID
  now serialize into the correct nested shows[].seasons[].episodes[]
  structure keyed by the show's IDs, merging episodes by show/season.
  Same fix applied to the history-remove payload. Empty-payload guards
  account for the new shows[] list.

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

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Pukabyte, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 48 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dc2ef27c-1782-44cf-8cca-f8c0a8b20638

📥 Commits

Reviewing files that changed from the base of the PR and between 658508a and fb6d6ff.

📒 Files selected for processing (1)
  • internal/watchstate/identity.go
📝 Walkthrough

Walkthrough

This PR adds episode-specific provider IDs (IMDB/TMDB/TVDB) to watch identity resolution and extends the Trakt provider to support nested show/season/episode structures in history export/remove payloads when episode-level IDs are unavailable, merging repeated episodes under the same show/season, with expanded test coverage.

Changes

Episode Identity and Trakt Nested History Payloads

Layer / File(s) Summary
Episode ProviderIDs in watch identity resolution
internal/watchstate/identity.go
ResolveHistoryIdentity now populates ProviderIDs for episode identities via a new episodeProviderIDs helper that builds a map from trimmed IMDB/TMDB/TVDB fields.
Trakt history payload types and emptiness checks
internal/watchsync/providers/trakt/provider.go
Adds Shows field to history payload structs, adds log/slog import, and updates ExportHistory/RemoveHistory empty-payload checks to include the new Shows collection.
Nested show fallback routing in buildHistoryPayload
internal/watchsync/providers/trakt/provider.go
Adds playOwnIDs, playSeriesIDs, and hasAnyID helpers, and updates buildHistoryPayload to route episodes lacking episode-level IDs into nested Shows structures with debug logging.
Nested show fallback and merging in buildHistoryRemovePayload
internal/watchsync/providers/trakt/provider.go
Refactors buildHistoryRemovePayload to reuse the fallback routing and adds appendNestedEpisode/appendNestedRemoveEpisode helpers merging entries by show IDs and season number.
Tests for nested show payload fallback and merging
internal/watchsync/providers/trakt/provider_test.go
Updates remove-history assertions to expect nested shows instead of flat episodes, and adds tests for single-episode fallback, multi-episode merging, and preservation of flat episode entries when real episode IDs exist.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Client as watchsync Client
    participant Provider as TraktProvider
    participant Builder as buildHistoryPayload
    participant Payload as HistoryPayload

    Client->>Provider: ExportHistory(plays)
    Provider->>Builder: build payload from plays
    loop for each play
        Builder->>Builder: playOwnIDs(play)
        alt episode IDs present
            Builder->>Payload: append to Movies/Episodes
        else no episode IDs
            Builder->>Builder: playSeriesIDs(play)
            Builder->>Builder: appendNestedEpisode(show, season, episode)
            Builder->>Payload: merge into Shows[]
        end
    end
    Provider->>Provider: check Movies/Episodes/Shows all empty?
    Provider->>Client: send request or skip if empty
Loading

Estimated code review effort: 3 (Moderate) | ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% 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 matches the main change: fixing Trakt TV episode sync payload handling in watchsync.
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 unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
internal/watchstate/identity.go (1)

51-60: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Don't require series IDs when the episode already has its own IDs.

Line 52 still drops the entire episode identity when seriesIDs is empty. That means episodes with a valid episode IMDb/TMDB/TVDB ID but missing series IDs never reach internal/watchsync/service.go as LocalPlay.IMDbID/TMDBID/TVDBID, so the new flat episodes[].ids path is skipped even though Trakt could address the episode directly. Only gate on seriesIDs when episodeProviderIDs(episode) is also empty and you truly need the nested show fallback.

Proposed fix
-			seriesIDs := providerIDMap(r.loadProviderIDs(ctx, episode.SeriesID))
-			if len(seriesIDs) == 0 {
+			episodeIDs := episodeProviderIDs(episode)
+			seriesIDs := providerIDMap(r.loadProviderIDs(ctx, episode.SeriesID))
+			if len(episodeIDs) == 0 && len(seriesIDs) == 0 {
 				return userstore.WatchIdentity{}
 			}
@@
 			return userstore.WatchIdentity{
 				StableType:        "episode",
-				ProviderIDs:       episodeProviderIDs(episode),
+				ProviderIDs:       episodeIDs,
 				SeriesProviderIDs: seriesIDs,
 				Season:            &seasonNumber,
 				Episode:           &episodeNumber,
 			}
🤖 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/watchstate/identity.go` around lines 51 - 60, In
watchstate/identity.go, the WatchIdentity builder currently returns an empty
identity whenever seriesIDs is empty, even if episodeProviderIDs(episode)
already contains usable episode IDs. Update the logic around the WatchIdentity
construction to only require seriesIDs when episodeProviderIDs(episode) is also
empty and you need the nested show fallback, so episode-specific IMDb/TMDB/TVDB
IDs still flow through to internal/watchsync/service.go.
🤖 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/watchstate/identity.go`:
- Around line 51-60: In watchstate/identity.go, the WatchIdentity builder
currently returns an empty identity whenever seriesIDs is empty, even if
episodeProviderIDs(episode) already contains usable episode IDs. Update the
logic around the WatchIdentity construction to only require seriesIDs when
episodeProviderIDs(episode) is also empty and you need the nested show fallback,
so episode-specific IMDb/TMDB/TVDB IDs still flow through to
internal/watchsync/service.go.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ff3213b-ca89-473b-915e-c855eb02d69d

📥 Commits

Reviewing files that changed from the base of the PR and between 656c487 and 658508a.

📒 Files selected for processing (3)
  • internal/watchstate/identity.go
  • internal/watchsync/providers/trakt/provider.go
  • internal/watchsync/providers/trakt/provider_test.go

Address CodeRabbit review on PR Silo-Server#254: the episode identity builder
dropped the whole identity whenever series IDs were empty, so episodes
with a valid episode IMDb/TMDB/TVDB ID but no series IDs never reached
the flat episodes[].ids Trakt path. Only require series IDs when the
episode has no IDs of its own (nested show fallback).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pukabyte added a commit to Pukabyte/silo-server that referenced this pull request Jul 1, 2026
Address CodeRabbit review on PR Silo-Server#254: the episode identity builder
dropped the whole identity whenever series IDs were empty, so episodes
with a valid episode IMDb/TMDB/TVDB ID but no series IDs never reached
the flat episodes[].ids Trakt path. Only require series IDs when the
episode has no IDs of its own (nested show fallback).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104
Quick104 merged commit cccf6d0 into Silo-Server:main Jul 1, 2026
1 check passed
@Pukabyte
Pukabyte deleted the fix/trakt-episode-sync branch July 2, 2026 05:26
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
* fix(watchsync): omit empty Trakt episode ids so series mark-watched targets the right show

omitempty on a struct value is a no-op in encoding/json, so the history
export sent all-zero episode ids ({tmdb:0,tvdb:0}); Trakt matched the
degenerate id to one default show, mis-recording every watched series.
Make episode IDs a *traktIDs pointer and attach it only when a real id
exists, else use the show + season/number fallback (mirroring scrobble).
Adds a debug log on the show-fallback path and payload tests.

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

* fix(watchsync): sync TV episodes to Trakt via valid nested shows payload

Episode history exports were dropped by Trakt because they were emitted
into the flat episodes[] array with a bogus sibling show object plus
season/number keys — a shape the Trakt API does not accept, so it
silently discarded them (200/201 with no history recorded). Movies were
unaffected since they always carry their own external IDs.

Two coordinated changes:

- watchstate/identity.go: ResolveHistoryIdentity now carries the
  episode's own imdb/tmdb/tvdb IDs (already stored on the episodes
  table) so episodes with real IDs export via the flat episodes[].ids
  form, matching how movies work.

- watchsync/providers/trakt/provider.go: episodes without their own ID
  now serialize into the correct nested shows[].seasons[].episodes[]
  structure keyed by the show's IDs, merging episodes by show/season.
  Same fix applied to the history-remove payload. Empty-payload guards
  account for the new shows[] list.

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

* fix(watchstate): keep episode identity when episode has its own IDs

Address CodeRabbit review on PR Silo-Server#254: the episode identity builder
dropped the whole identity whenever series IDs were empty, so episodes
with a valid episode IMDb/TMDB/TVDB ID but no series IDs never reached
the flat episodes[].ids Trakt path. Only require series IDs when the
episode has no IDs of its own (nested show fallback).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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