Skip to content

fix(progress): re-enter Continue Watching when re-watching a finished item - #109

Closed
d3v1l1989 wants to merge 1 commit into
Silo-Server:mainfrom
d3v1l1989:fix/continue-watching-rewatch-restart
Closed

d3v1l1989 wants to merge 1 commit into
Silo-Server:mainfrom
d3v1l1989:fix/continue-watching-rewatch-restart

Conversation

@d3v1l1989

Copy link
Copy Markdown
Contributor

Problem

Re-watching an already-finished item never re-enters the Continue Watching row until the user manually marks it unwatched.

The row is built by ListProgress(profileID, "in_progress"), whose SQL filters user_watch_progress to WHERE completed = FALSE. But the playback heartbeat path (UpdateProgress, used by both the native player and the jellycompat stream handler) latched completed one-way:

completed = CASE WHEN excluded.completed THEN TRUE ELSE user_watch_progress.completed END,
position_seconds = GREATEST(excluded.position_seconds, user_watch_progress.position_seconds)

Once an item is finished (completed = TRUE, position reset to duration), starting it again reports a fresh low position — but the CASE keeps completed = TRUE and GREATEST keeps the old end-of-file position, so the re-watch is invisible to the in-progress query forever. Only ClearProgress/ClearProgressBatch (mark-unwatched) releases the latch.

Fix

In UpdateProgress, release the latch and adopt the fresh resume point when an early-position heartbeat lands on an already-completed row — gated by two guards:

  • Fraction guard (RestartDetectFraction = 0.5): the incoming position must be below 50% of the max known runtime, distinguishing a genuine rewatch-from-the-start from a brief end-of-file seek. GREATEST/MAX(excluded, stored) duration handles multi-version/edition rewatches where the runtime differs.
  • Time-gap guard (RestartMinGapSeconds = 60): at least 60s must have elapsed since the row was last updated, rejecting a stale heartbeat from a concurrent/offline session arriving just after completion.

Both guards are AND-ed, so any failure (including a NULL julianday in the SQLite path) defaults to keeping the item completed — the conservative choice.

Scoped to UpdateProgress only. In-progress rows (completed = FALSE) are provably unchanged (both new branches require completed = TRUE), and existing finished rows are untouched until actually re-watched.

The SQLite userdb store gets the same logic, plus the min-resume early-return guard it was previously missing (silent divergence from the Postgres store).

Testing

  • New table-driven tests (internal/userdb): in-progress unchanged, rewatch releases latch + adopts position, late heartbeat (>50%) does not release, recent completion (<60s) blocked by the time guard, completion still latches, multi-version duration via MAX, zero stored duration fallback, below-min-resume discard. go test ./internal/userdb/ ./internal/userstore/... passes; go build clean; gofmt clean.
  • Postgres CASE logic validated against a live populated catalog; deployed and confirmed fixing the reported behavior.

AI-assisted: implementation and tests were written with Claude and reviewed line-by-line by me.

… item

UpdateProgress latched `completed` one-way to TRUE and used GREATEST(position),
so re-watching a finished item never re-entered "Continue Watching"
(ListProgress "in_progress" filters completed = FALSE) until the user manually
marked it unwatched.

Release the latch and adopt the fresh resume point when an early-position
heartbeat (< RestartDetectFraction of the max known runtime) lands on an
already-completed row at least RestartMinGapSeconds after it was finished. The
fraction guard distinguishes a genuine rewatch-from-the-start from a brief
end-of-file seek; the time-gap guard rejects stale heartbeats from a
concurrent/offline session arriving just after completion. Scoped to
UpdateProgress only: in-progress rows are unchanged and existing completed rows
are untouched until re-watched.

The SQLite userdb store gets the same logic (and the min-resume early-return
guard it was previously missing) for parity, plus table-driven tests covering
the rewatch release, the time-gap and late-heartbeat non-release paths,
multi-version durations, zero stored duration, and min-resume discard.
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@d3v1l1989, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 37 minutes and 21 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a0ae24c6-8abc-43df-9418-3150db2de7b7

📥 Commits

Reviewing files that changed from the base of the PR and between eee622e and f4a598f.

📒 Files selected for processing (5)
  • internal/userdb/helpers.go
  • internal/userdb/progress.go
  • internal/userdb/progress_test.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/threshold.go
✨ 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 and usage tips.

@Quick104

Quick104 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for this — the diagnosis is exactly right (the one-way completed latch + GREATEST position pinning makes rewatches permanently invisible to Continue Watching), and the table-driven tests are solid. We're going to close this in favor of a model-level fix, for two reasons we confirmed while reviewing the guard mechanism:

  1. The 60s time-gap guard is self-defeating for immediate rewatches. Blocked heartbeats still execute the DO UPDATE, so updated_at = excluded.updated_at refreshes on every rejected report. The gap is then measured against the last heartbeat (~10s cadence), not against completion — once one qualifying heartbeat lands inside the 60s window, the latch can never release for the rest of the session, and the rewatch's progress is silently discarded. Reproduced with a clock-pinned test: a 10-minute episode restarted 30s after finishing stayed completed=true through 4+ minutes of heartbeats. Any item shorter than ~20 min restarted promptly hits this, as does any seek past 5% within a minute of finishing.

  2. A position-0 heartbeat un-watches a finished item. The min-resume early return requires position > 0, so an exactly-zero report falls through to the upsert, where 0 < MAX(duration)*0.5 and the time guard (item finished long ago) both pass → latch released at position 0. The native player's persistProgress has no position > 0 guard (the jellycompat path does), so opening a watched item and backing out before playing clears its watched state.

Rather than adding more guards, we're adopting the Jellyfin invariant that removes the need for restart detection entirely: completion resets position_seconds to 0 (instead of pinning it to duration), completed stays a pure one-way watched latch, and the resume query keys on position_seconds > 0 instead of completed = FALSE. A rewatch heartbeat then hits GREATEST(new, 0) and re-enters Continue Watching naturally — no thresholds, no clock math, no race windows — and the watched badge survives the rewatch (matching Plex and current Jellyfin master, see jellyfin/jellyfin#15762).

A replacement PR is in progress and will reference this one. Thanks again for the thorough writeup — it's what made the underlying model problem obvious.

@Quick104 Quick104 closed this Jun 9, 2026
Quick104 added a commit that referenced this pull request Jun 9, 2026
* fix(progress): track resume points independently of watched state

Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).

Adopt the Jellyfin invariant instead of guard heuristics:

- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
  SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
  position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
  Continue Watching through plain GREATEST/MAX while the watched flag and
  PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
  the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
  (resumePositionTicks no longer zeroes played items) — the DTO shape real
  Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
  stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
  via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
  0: a Goose migration for Postgres and a user_version-gated one-time fix
  for the per-user SQLite DBs.

Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(progress): address review — migration gate, one-way latch, missed writers/readers

Review fixes for the position-based watch-progress model:

- The per-user SQLite data fix is now migrateToV11 in the existing
  versioned runMigrations chain (schemaVersion 11). The previous
  standalone PRAGMA gate compared against 1, but existing DBs already
  sit at user_version 10, so the reset never ran for them — and the
  gate would have rewound the version. Fresh DBs short-circuit to the
  current version as before.
- `completed` is now one-way across every playback/sync writer:
  SetProgress (the RecordPlaybackStop path — stopping a rewatch below
  the watched threshold no longer clears the watched state),
  SetProgressAt, SetProgressIfNewer (both stores), and the history
  import upsert, which also stops pinning completed imports to
  position = duration. Mark-unwatched still releases the latch via
  ClearProgress/ClearProgressBatch.
- MarkProgressBatch regains its freshness guard: a delayed batch mark
  carrying an old timestamp can no longer zero a newer rewatch resume
  point (the position-reset now rides the original updated_at check).
- Catalog read paths align with the new in-progress definition
  (position_seconds > 0, completed-agnostic): smart-collection
  in_progress filter, progress sort ratio, episode progress CTE, and
  both next-up predicates.
- jellycompat derives PlayedPercentage and PlaybackPositionTicks from
  the same clamped position; a played item at rest reports 100 (as the
  old model did) while a rewatch reports its live fraction.
- ABS audiobook UpsertProgress stores position 0 on finish so finished
  books can't surface as phantom resume entries; re-listens still move
  position forward from 0 with the latch intact.
- The web optimistic cache zeroes the resume point on completion,
  mirroring the server invariant until the refetch lands.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jun 11, 2026
* fix(progress): track resume points independently of watched state

Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).

Adopt the Jellyfin invariant instead of guard heuristics:

- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
  SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
  position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
  Continue Watching through plain GREATEST/MAX while the watched flag and
  PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
  the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
  (resumePositionTicks no longer zeroes played items) — the DTO shape real
  Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
  stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
  via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
  0: a Goose migration for Postgres and a user_version-gated one-time fix
  for the per-user SQLite DBs.

Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(progress): address review — migration gate, one-way latch, missed writers/readers

Review fixes for the position-based watch-progress model:

- The per-user SQLite data fix is now migrateToV11 in the existing
  versioned runMigrations chain (schemaVersion 11). The previous
  standalone PRAGMA gate compared against 1, but existing DBs already
  sit at user_version 10, so the reset never ran for them — and the
  gate would have rewound the version. Fresh DBs short-circuit to the
  current version as before.
- `completed` is now one-way across every playback/sync writer:
  SetProgress (the RecordPlaybackStop path — stopping a rewatch below
  the watched threshold no longer clears the watched state),
  SetProgressAt, SetProgressIfNewer (both stores), and the history
  import upsert, which also stops pinning completed imports to
  position = duration. Mark-unwatched still releases the latch via
  ClearProgress/ClearProgressBatch.
- MarkProgressBatch regains its freshness guard: a delayed batch mark
  carrying an old timestamp can no longer zero a newer rewatch resume
  point (the position-reset now rides the original updated_at check).
- Catalog read paths align with the new in-progress definition
  (position_seconds > 0, completed-agnostic): smart-collection
  in_progress filter, progress sort ratio, episode progress CTE, and
  both next-up predicates.
- jellycompat derives PlayedPercentage and PlaybackPositionTicks from
  the same clamped position; a played item at rest reports 100 (as the
  old model did) while a rewatch reports its live fraction.
- ABS audiobook UpsertProgress stores position 0 on finish so finished
  books can't surface as phantom resume entries; re-listens still move
  position forward from 0 with the latch intact.
- The web optimistic cache zeroes the resume point on completion,
  mirroring the server invariant until the refetch lands.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
* fix(progress): track resume points independently of watched state

Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).

Adopt the Jellyfin invariant instead of guard heuristics:

- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
  SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
  position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
  Continue Watching through plain GREATEST/MAX while the watched flag and
  PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
  the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
  (resumePositionTicks no longer zeroes played items) — the DTO shape real
  Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
  stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
  via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
  0: a Goose migration for Postgres and a user_version-gated one-time fix
  for the per-user SQLite DBs.

Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(progress): address review — migration gate, one-way latch, missed writers/readers

Review fixes for the position-based watch-progress model:

- The per-user SQLite data fix is now migrateToV11 in the existing
  versioned runMigrations chain (schemaVersion 11). The previous
  standalone PRAGMA gate compared against 1, but existing DBs already
  sit at user_version 10, so the reset never ran for them — and the
  gate would have rewound the version. Fresh DBs short-circuit to the
  current version as before.
- `completed` is now one-way across every playback/sync writer:
  SetProgress (the RecordPlaybackStop path — stopping a rewatch below
  the watched threshold no longer clears the watched state),
  SetProgressAt, SetProgressIfNewer (both stores), and the history
  import upsert, which also stops pinning completed imports to
  position = duration. Mark-unwatched still releases the latch via
  ClearProgress/ClearProgressBatch.
- MarkProgressBatch regains its freshness guard: a delayed batch mark
  carrying an old timestamp can no longer zero a newer rewatch resume
  point (the position-reset now rides the original updated_at check).
- Catalog read paths align with the new in-progress definition
  (position_seconds > 0, completed-agnostic): smart-collection
  in_progress filter, progress sort ratio, episode progress CTE, and
  both next-up predicates.
- jellycompat derives PlayedPercentage and PlaybackPositionTicks from
  the same clamped position; a played item at rest reports 100 (as the
  old model did) while a rewatch reports its live fraction.
- ABS audiobook UpsertProgress stores position 0 on finish so finished
  books can't surface as phantom resume entries; re-listens still move
  position forward from 0 with the latch intact.
- The web optimistic cache zeroes the resume point on completion,
  mirroring the server invariant until the refetch lands.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[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