Skip to content

Fix watch-state unwatch sync across user data and Jellyfin mappings - #179

Merged
Quick104 merged 2 commits into
mainfrom
codex/fix-watch-history-unwatch-sync
Jun 18, 2026
Merged

Quick104 merged 2 commits into
mainfrom
codex/fix-watch-history-unwatch-sync

Conversation

@Quick104

@Quick104 Quick104 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Keep watch-state rollups and direct item/user-data paths aligned when playback is cleared.
  • Propagate unwatch changes through catalog, access, and Jellyfin compatibility layers so history stays consistent.
  • Update progress storage and sync helpers to handle cleared progress predictably across stores.
  • Add and adjust tests around watch-state service behavior, user-data mapping, and direct content handling.

Testing

  • Automated coverage updated across service, store, mapping, and compatibility tests.
  • Local validation not run here; test suite changes focus on regressions around unwatch propagation and progress clearing.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed watch-state and aggregation logic so series and season completion/watched status now considers completed watch-history items, even when no active progress exists.
    • Updated watch progress mapping to consistently derive “played” and resume details from completed history as well as in-progress tracking.
    • Corrected unwatch behavior so manual and imported history interactions properly preserve the expected watched/unwatched state.

@coderabbitai

coderabbitai Bot commented Jun 18, 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: 40d4f5de-6ff7-493f-8ea2-22a78f82f1e0

📥 Commits

Reviewing files that changed from the base of the PR and between a02dc7b and a541d64.

📒 Files selected for processing (16)
  • internal/access/resolver_test.go
  • internal/catalog/user_data_rollup.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/series_userdata_test.go
  • internal/recommendations/signals_test.go
  • internal/userdb/progress.go
  • internal/userdb/progress_test.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/progress_helpers.go
  • internal/userstore/progress_helpers_test.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
  • internal/userstore/types.go
  • internal/watchstate/service.go
  • internal/watchstate/service_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/jellycompat/content_direct_test.go
  • internal/userstore/storetest/suite.go
  • internal/catalog/user_data_rollup.go
  • internal/watchstate/service_test.go
  • internal/userdb/progress_test.go

📝 Walkthrough

Walkthrough

Extends the user-store interface with ListCompletedHistoryItems method and new query/result types, refactors storage implementations with visibility-aware history updates, introduces progress enrichment helpers that overlay completed-history onto live progress, adds EpisodeRollupUserData to the catalog package, refactors watchstate un-watch and import flows, and updates all API handler and jellycompat paths to use the new completed-history-aware progress helpers.

Changes

Completed history awareness for watch progress

Layer / File(s) Summary
Store interface, types, and conformance suite
internal/userstore/types.go, internal/userstore/store.go, internal/userstore/storetest/suite.go
Adds CompletedHistoryItemQuery and CompletedHistoryItem types. Extends UserStore interface with ListCompletedHistoryItems(ctx, query) method. Adds conformance-suite coverage including removal-watermark and source-filter scenarios.
Storage visibility and hidden-history infrastructure
internal/userdb/progress.go, internal/userstore/pgstore/progress.go
Refactors UpdateProgress, SetProgress, MarkWatched, and MarkProgressBatch to compute visible timestamps via CTEs joined to hidden_history_items. Introduces shared helpers completedHistoryVisibleSQL, completedHistoryFilterSQL, and visibleTimestampSQL. Updates SetProgressIfNewer to OR the completed flag on conflict.
Completed-history queries and visible-timestamp helpers
internal/userdb/progress.go, internal/userdb/progress_test.go, internal/userdb/sqlitestore.go, internal/userstore/pgstore/progress.go
Implements ListCompletedHistoryItems in both SQLite and Postgres backends. Adds AddVisibleHistory and VisibleHistoryTimestamps helpers for visibility-aware history insertion and lookups. Refactors RemoveHistoryItems to compute per-item hidden_before watermarks from max watched_at and delete via correlated subqueries.
Progress enrichment helpers
internal/userstore/progress_helpers.go, internal/userstore/progress_helpers_test.go
Introduces CompletedHistoryItemMap, GetProgressWithCompletedHistory, and ListProgressWithCompletedHistory that overlay completed-history onto live progress. Provides optional capability interfaces and fallback implementations for AddVisibleHistory and VisibleHistoryTimestamps.
Catalog episode-to-season rollup
internal/catalog/user_data_rollup.go, internal/jellycompat/series_userdata_test.go
Adds EpisodeRollupUserData computing WatchedCount, InProgressCount, UnplayedCount, and Played from an episode list and progress map. Migrates series-userdata tests to use the catalog-level function and adjusts nil-episode expectations.
Watchstate un-watch refactoring
internal/watchstate/service.go, internal/watchstate/mark_played_batch_test.go, internal/watchstate/service_test.go
Refactors recordMarkUnwatched to use paginated multi-source completedHistoryForTargets with a single RemoveHistoryItems call. Simplifies recordMarkUnwatchedBatch and removes buildMarkUnplayedBatchSQL. Updates manual/jellycompat un-watch callers to drop source arguments. Adds watchstate tests for unwatch entry suppression.
Watchstate import and visible-history recording
internal/watchstate/service.go, internal/watchstate/service_test.go
Adds RecordImportedWatchIfNewerWithSource using SetProgressIfNewer then AddMissingImportedHistory. Updates RecordPlaybackStop and recordMarkWatched to normalize zero watchedAt and insert via userstore.AddVisibleHistory. Updates batch insertion similarly. Adds comprehensive import-if-newer ordering tests.
Watchsync interface and import integration
internal/watchsync/service.go, internal/watchsync/service_test.go
Renames watchStateImporter method to RecordImportedWatchIfNewerWithSource, adding position and updatedAt parameters. Updates ImportWatched call site. Updates fakes to implement the new signature with full metadata recording. Strengthens import tests.
API handlers: items and user-state progress
internal/api/handlers/items.go, internal/api/handlers/catalog_resources.go, internal/api/handlers/user_state.go, internal/api/handlers/items_user_data_test.go, internal/api/handlers/user_state_test.go
Updates getLeafUserData, listLeafUserData, getAggregateUserData to use completed-history-aware progress helpers and catalog.EpisodeRollupUserData. Updates HandleGetSeasons and resolveItemUserStatesWithOptions. Removes local aggregateUserDataFromProgress. Adds completed-history behavior tests.
Jellycompat content-direct progress paths
internal/jellycompat/content_direct.go, internal/jellycompat/content_direct_test.go
Updates GetItemDetail, ListEpisodes, and all progress-enrichment helpers to use userstore.GetProgressWithCompletedHistory/ListProgressWithCompletedHistory and catalog.EpisodeRollupUserData. Adjusts seasonUserDataFromProgress to accept pointers. Adds progressForContentIDs helper. Stubs ListCompletedHistoryItems in test double.
Jellycompat user-data mapping and compat-layer progress
internal/jellycompat/userdata_direct.go, internal/jellycompat/mapping.go, internal/jellycompat/mapping_userdata_test.go, internal/jellycompat/userdata_direct_test.go
Updates ListProgressByMediaItems and GetProgress to use completed-history-aware helpers. Fixes userDataDTO to OR aggregate Played with progress.Completed. Adds completed-history test coverage and in-memory SQLite store test helpers.
Test stubs and watchstate service coverage
internal/access/resolver_test.go, internal/jellycompat/content_direct_test.go, internal/recommendations/signals_test.go, internal/watchstate/service_test.go
Adds ListCompletedHistoryItems stubs to test doubles. Adds comprehensive watchstate tests for unwatch entry suppression, import-if-newer ordering, and visible-watermark behavior. Includes test helper createWatchstateProfile.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • Silo-Server/silo-server#117: Modifies the same items.go leaf/season user-data mapping paths and jellycompat completed/in-progress gating logic that this PR reworks to be completed-history-aware.
  • Silo-Server/silo-server#178: Refactors the same season/episode user-data aggregation flow in items.go (including getAggregateUserData and episode progress batching) that this PR further updates to use completed-history-aware progress sources.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.43% 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 'Fix watch-state unwatch sync across user data and Jellyfin mappings' directly matches the PR's primary objective of fixing synchronization issues between watch-state rollups and data paths when playback progress is cleared.
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 codex/fix-watch-history-unwatch-sync

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

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +162 to +165
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +344 to +347
const pageSize = 500
var entries []userstore.WatchHistoryEntry
for offset := 0; ; offset += pageSize {
page, err := store.ListCompletedHistory(ctx, userstore.CompletedHistoryQuery{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment thread internal/userdb/progress.go Outdated
Comment on lines +706 to +710
for _, mediaItemID := range mediaItemIDs {
hiddenBeforeText := removedAtText
var maxWatchedAt sql.NullString
if err := tx.QueryRow(`
SELECT MAX(watched_at)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +53 to +58
if progress == nil {
return &WatchProgress{
ProfileID: profileID,
MediaItemID: mediaItemID,
Completed: true,
}, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d6166b and a02dc7b.

📒 Files selected for processing (28)
  • internal/access/resolver_test.go
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • internal/api/handlers/items_user_data_test.go
  • internal/api/handlers/user_state.go
  • internal/api/handlers/user_state_test.go
  • internal/catalog/user_data_rollup.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/mapping_userdata_test.go
  • internal/jellycompat/series_userdata_test.go
  • internal/jellycompat/userdata_direct.go
  • internal/jellycompat/userdata_direct_test.go
  • internal/recommendations/signals_test.go
  • internal/userdb/progress.go
  • internal/userdb/progress_test.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/progress_helpers.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
  • internal/userstore/types.go
  • internal/watchstate/mark_played_batch_test.go
  • internal/watchstate/service.go
  • internal/watchstate/service_test.go
  • internal/watchsync/service.go
  • internal/watchsync/service_test.go
💤 Files with no reviewable changes (1)
  • internal/watchstate/mark_played_batch_test.go

Comment thread internal/catalog/user_data_rollup.go Resolved
Comment on lines +346 to +353
for offset := 0; ; offset += pageSize {
page, err := store.ListCompletedHistory(ctx, userstore.CompletedHistoryQuery{
ProfileID: profileID,
MediaItemIDs: targetIDs,
IncludeSources: includeSources,
Limit: pageSize,
Offset: offset,
})

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

@Quick104
Quick104 merged commit 2b9a048 into main Jun 18, 2026
1 check passed
@Quick104
Quick104 deleted the codex/fix-watch-history-unwatch-sync branch June 18, 2026 23:17
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…ilo-Server#179)

* Refine playback session handling and API responses

* fix(watchstate): harden completed-history visibility
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