Repository navigation
Fix watch-state unwatch sync across user data and Jellyfin mappings - #179
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (16)
🚧 Files skipped from review as they are similar to previous changes (5)
📝 WalkthroughWalkthroughExtends the user-store interface with ChangesCompleted history awareness for watch progress
Sequence Diagram(s)sequenceDiagram
rect rgba(70, 130, 180, 0.5)
Note over ImportWatched,UserStore: Watch import and progress update flow
participant ImportWatched
participant RecordImportedWatchIfNewer
participant UserStore
ImportWatched->>RecordImportedWatchIfNewer: (targetID, duration, position=0, completed, updatedAt, watchedAt, source)
RecordImportedWatchIfNewer->>UserStore: SetProgressIfNewer (completed = existing OR incoming)
UserStore-->>RecordImportedWatchIfNewer: updated=true/false
RecordImportedWatchIfNewer->>UserStore: AddMissingImportedHistory (if updated)
UserStore-->>ImportWatched: (changed bool, error)
end
rect rgba(60, 179, 113, 0.5)
Note over APIHandler,UserStore: Progress enrichment with completed history overlay
participant APIHandler
participant ListProgressWithCompletedHistory
participant UserStore
APIHandler->>ListProgressWithCompletedHistory: profileID, mediaItemIDs
ListProgressWithCompletedHistory->>UserStore: ListProgressByMediaItems
UserStore-->>ListProgressWithCompletedHistory: progress map
ListProgressWithCompletedHistory->>UserStore: ListCompletedHistoryItems (for not-yet-completed IDs)
UserStore-->>ListProgressWithCompletedHistory: completed history items
ListProgressWithCompletedHistory-->>APIHandler: enriched progress map (Completed=true overlaid)
end
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
🚥 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 docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a02dc7baa0
ℹ️ 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".
| } | ||
| } | ||
| return result, store.DeleteHistoryBySource(ctx, profileID, targetIDs, source) | ||
| return result, store.RemoveHistoryItems(ctx, profileID, targetIDs, time.Now().UTC()) |
There was a problem hiding this comment.
Preserve watch marks made in the same second
When a client marks an item unwatched and then watched again within the same second, RemoveHistoryItems records a watermark from time.Now(), while the subsequent progress and history timestamps are formatted with second-precision time.RFC3339 (formatWatchedAt and the stores' nowUTC). Because the visibility checks suppress timestamps equal to or below the watermark, the new watched state remains hidden; use consistent timestamp precision or clear/advance the watermark when recording a new local watch.
Useful? React with 👍 / 👎.
| if _, err := store.SetProgressIfNewer(ctx, profileID, targetID, position, duration, completed, updatedAt); err != nil { | ||
| return false, err | ||
| } | ||
| return s.addImportedHistoryIfMissingWithSource(ctx, store, profileID, targetID, duration, completed, watchedAt, source) |
There was a problem hiding this comment.
Do not overlay an older imported watch onto newer progress
When an imported watched event is older than an existing local resume row, SetProgressIfNewer correctly declines to replace that row, but this unconditional history insert still records the older event as completed. The new GetProgressWithCompletedHistory/ListProgressWithCompletedHistory helpers then overlay that completed history onto the newer progress, so API and Jellyfin clients report the item as played despite the test's intended preservation of the newer uncompleted resume. Only project the imported completion when it wins the timestamp comparison, or make the history overlay respect the progress timestamp.
Useful? React with 👍 / 👎.
| const pageSize = 500 | ||
| var entries []userstore.WatchHistoryEntry | ||
| for offset := 0; ; offset += pageSize { | ||
| page, err := store.ListCompletedHistory(ctx, userstore.CompletedHistoryQuery{ |
There was a problem hiding this comment.
Deduplicate history before dispatching an unwatch
For an item that has been manually marked watched many times, this pagination now returns every historical manual play, although the only caller converts them all into one outbound unwatch request. That creates duplicate provider payload entries and removes the previous len(targetIDs) * 20 bound, so a long-lived profile or a whole-series unwatch can allocate and transmit an arbitrarily large request. Return one representative history entry per target (or otherwise bound/deduplicate the result) because provider removal is item-based.
Useful? React with 👍 / 👎.
| for _, mediaItemID := range mediaItemIDs { | ||
| hiddenBeforeText := removedAtText | ||
| var maxWatchedAt sql.NullString | ||
| if err := tx.QueryRow(` | ||
| SELECT MAX(watched_at) |
There was a problem hiding this comment.
Keep SQLite batch unwatch set-based
In SQLite-backed deployments, unwatching a series now executes a MAX(watched_at) query and an upsert for every episode before the two deletes. A several-hundred-episode series therefore turns the previous constant-number batch operation into hundreds or thousands of SQL statements while holding a write transaction, increasing request latency and lock contention. Compute and upsert the watermarks with set-based SQL or a temporary values table rather than looping over every target.
Useful? React with 👍 / 👎.
| if progress == nil { | ||
| return &WatchProgress{ | ||
| ProfileID: profileID, | ||
| MediaItemID: mediaItemID, | ||
| Completed: true, | ||
| }, nil |
There was a problem hiding this comment.
Preserve the last-played timestamp for history-only items
When an item is completed only through a history row, this synthetic progress object leaves UpdatedAt empty even though the history query has a real watched_at. directUserDataService converts this object to upstreamProgress, and userDataDTO then exposes the empty value as LastPlayedDate, so Jellyfin clients lose recently-played metadata for imported or legacy watched items. Return the latest visible completed-history timestamp, not just the item ID, and populate UpdatedAt on the synthetic projection.
Useful? React with 👍 / 👎.
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/catalog/user_data_rollup.go`:
- Around line 32-37: The calculation of UnplayedCount and Played status uses
len(episodes) as the denominator, but this includes nil episode placeholders
that are skipped during iteration. Track the actual count of non-nil episodes
encountered in the loop instead of using len(episodes) directly. When
calculating UnplayedCount in the return statement for SeasonUserData and when
determining the Played boolean condition, use the actual non-nil episode count
rather than len(episodes) to ensure these fields accurately reflect only real
episodes.
In `@internal/watchstate/service.go`:
- Around line 346-353: The `completedHistoryForTargets` function uses OFFSET
pagination with `ListCompletedHistory`, but the ordering is unstable because it
only sorts by `watched_at`, causing tied timestamps to result in unpredictable
page boundaries that can skip or duplicate rows. Add a stable secondary sort key
`id` to the `ListCompletedHistory` ordering in both SQLite and Postgres store
implementations so that rows are ordered deterministically as `watched_at ASC,
id ASC`, ensuring consistent pagination results regardless of tied timestamps.
🪄 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: a81f5a0b-5c9a-4ac0-ac8d-87b4254a9943
📒 Files selected for processing (28)
internal/access/resolver_test.gointernal/api/handlers/catalog_resources.gointernal/api/handlers/items.gointernal/api/handlers/items_user_data_test.gointernal/api/handlers/user_state.gointernal/api/handlers/user_state_test.gointernal/catalog/user_data_rollup.gointernal/jellycompat/content_direct.gointernal/jellycompat/content_direct_test.gointernal/jellycompat/mapping.gointernal/jellycompat/mapping_userdata_test.gointernal/jellycompat/series_userdata_test.gointernal/jellycompat/userdata_direct.gointernal/jellycompat/userdata_direct_test.gointernal/recommendations/signals_test.gointernal/userdb/progress.gointernal/userdb/progress_test.gointernal/userdb/sqlitestore.gointernal/userstore/pgstore/progress.gointernal/userstore/progress_helpers.gointernal/userstore/store.gointernal/userstore/storetest/suite.gointernal/userstore/types.gointernal/watchstate/mark_played_batch_test.gointernal/watchstate/service.gointernal/watchstate/service_test.gointernal/watchsync/service.gointernal/watchsync/service_test.go
💤 Files with no reviewable changes (1)
- internal/watchstate/mark_played_batch_test.go
| for offset := 0; ; offset += pageSize { | ||
| page, err := store.ListCompletedHistory(ctx, userstore.CompletedHistoryQuery{ | ||
| ProfileID: profileID, | ||
| MediaItemIDs: targetIDs, | ||
| IncludeSources: includeSources, | ||
| Limit: pageSize, | ||
| Offset: offset, | ||
| }) |
There was a problem hiding this comment.
Use a stable sort key for paginated completed-history reads.
completedHistoryForTargets uses OFFSET pagination, but both store implementations sort completed history only by watched_at. With tied timestamps, page boundaries are unstable, so ManualMarkResult.Entries can miss or duplicate rows.
A deterministic secondary key (id) should be added to ListCompletedHistory ordering in both SQLite and Postgres (ORDER BY watched_at ASC, id ASC) before using OFFSET paging here.
🤖 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/service.go` around lines 346 - 353, The
`completedHistoryForTargets` function uses OFFSET pagination with
`ListCompletedHistory`, but the ordering is unstable because it only sorts by
`watched_at`, causing tied timestamps to result in unpredictable page boundaries
that can skip or duplicate rows. Add a stable secondary sort key `id` to the
`ListCompletedHistory` ordering in both SQLite and Postgres store
implementations so that rows are ordered deterministically as `watched_at ASC,
id ASC`, ensuring consistent pagination results regardless of tied timestamps.
…ilo-Server#179) * Refine playback session handling and API responses * fix(watchstate): harden completed-history visibility
Summary
Testing
Summary by CodeRabbit