fix(plex): the reclaim window rolls, and a refused finish is not performed through a third route

Two ways round 6's own fixes did not bound what their comments said they bounded.

The reclaim budget's window anchor was written only where the window RESET, so it marked the window's
start rather than the last loss — a tumbling window, not the rolling one the constant is named for.
Any loss cadence slower than half the window satisfied the reset on every second loss, so the budget
never reached its bound: measured over 200 loss cycles, 61/70/90/119s apart all gave 200 reclaims and
never an error, while 5s and 30s apart correctly gave two and then the honest answer. The failing
band is exactly the case the ERROR handler names — a transcode that falls behind realtime — and both
committed tests spaced their losses 0s and 10min apart, i.e. outside it. The anchor now moves with
every loss.

And `finish`'s refusal handler lowered the play-through latch, which is the only gate on the 10s
interval, the page-hide beacon and `settle`. All three post `absRef`, which on the play-to-the-end
path IS the end of the media, and the backend reads a position within `_FINISH_MARGIN_S` of the
duration as a finish — so within ten seconds of the toast saying the mark had failed, the item was
marked watched, its position cleared and a scrobble sent to Plex. Round 6 closed the explicit
rollback write and left the other three open; the test it added set `upNext: false`, which tears the
effect down before any of them can fire. The refusal now takes back the CLAIM rather than the latch:
a second flag stops `settle` re-asserting watched, and playing again clears both.

`FINISH_MARGIN_S` duplicated the backend's constant in a second language with nothing relating them,
and its comment had the asymmetry backwards — if the BACKEND's margin grows, this guard starts
admitting a rollback the backend reads as a finish, i.e. re-opens the defect above. Pinned by a
contract test that reads the Python, and the comment corrected.
This commit is contained in:
2026-09-12 16:21:51 +02:00
parent 71d7646bf1
commit 8036251589
5 changed files with 149 additions and 14 deletions
+35 -11
View File
@@ -23,9 +23,16 @@ import { PLEX_SCALE, normalizeVolumeIn, stepVolumeIn } from "./playerVolume";
// How close to the end the backend counts as "finished" (`_FINISH_MARGIN_S` in routes/plex/playback):
// a progress checkpoint at or past `duration - this` marks the item watched and clears the position.
// Mirrored here because `finish`'s rollback must not accidentally drive that branch. It is a
// one-way safety margin, not a shared contract — if the two ever diverge, the worst case is a
// rollback that is skipped or a resume point set a few seconds from the end.
// Mirrored here because `finish`'s rollback must not accidentally drive that branch.
//
// Drift is NOT symmetric, which an earlier version of this comment had backwards. If THIS value
// grows, the rollback is skipped where it need not be — a lost resume point, annoying. If the
// BACKEND's grows (its own comment invites that tuning by contrasting it with the feed's 10 s),
// this guard starts admitting a rollback the backend reads as a finish, which marks the item
// watched, clears the position and scrobbles to Plex — re-performing the very write that was just
// refused, i.e. exactly the defect this constant was introduced to close. So the invariant is
// one-directional and it is PINNED, not described: `plexFinishMargin.contract.test.ts` reads the
// Python and fails if this value ever drops below it (round 7).
const FINISH_MARGIN_S = 30;
// A live wall clock for the top bar, re-rendered every 15s (minute resolution is enough for the
@@ -111,6 +118,16 @@ export function usePlexProgress(opts: {
const finishRef = useRef<(confirmed?: Promise<unknown>) => void>(() => {});
useEffect(() => {
let finished = false;
// Raised when the caller's watched write came back REFUSED. The play-through latch itself stays
// up, because lowering it re-armed three other routes to the same write: the 10s interval, the
// page-hide beacon and `settle` all post `absRef`, which on this path IS the end of the media,
// and the backend reads a position within `_FINISH_MARGIN_S` of the duration as a finish. So the
// branch named "take the finish back" marked the item watched, cleared the position and
// scrobbled to Plex within ten seconds — the refused write performed through a third route,
// under an error toast saying it had failed. Round 6 closed only the explicit rollback write;
// this closes the other three (deep-review round 7). What the refusal does take back is the
// CLAIM: the cache must not say watched, and `settle` must not re-assert it on the way out.
let finishRefused = false;
// `final` = a settled checkpoint (pause / page-hide / leaving the player) vs. the periodic tick.
// Only final checkpoints get mirrored to a linked Plex account (backend-side debounce), so Plex
// sees the resume position when the user actually stops — not a timeline call every 10 seconds.
@@ -157,6 +174,7 @@ export function usePlexProgress(opts: {
window.addEventListener("pagehide", onHide);
const onPlayAgain = () => {
finished = false;
finishRefused = false;
};
video?.addEventListener("play", onPlayAgain);
// Back (unmount) persists the position server-side via flush(), but reopening the same item in
@@ -170,9 +188,14 @@ export function usePlexProgress(opts: {
// Match the language-keyed detail query (E5 S6) so the optimistic resume patch lands.
const key = qk.plexItem(id, plexLang());
if (finished) {
qc.setQueryData(key, (old) =>
old ? { ...old, status: "watched", position_seconds: 0 } : old,
);
// A refused finish claims nothing: the server has the item unwatched at the position the
// rollback restored, and the catch below has already dropped this entry, so the next open
// fetches the truth. Re-patching "watched / 0" here would put back the very lie the
// refusal handler removed.
if (!finishRefused)
qc.setQueryData(key, (old) =>
old ? { ...old, status: "watched", position_seconds: 0 } : old,
);
return;
}
flush(true);
@@ -185,14 +208,15 @@ export function usePlexProgress(opts: {
finishRef.current = (confirmed?: Promise<unknown>) => {
finished = true;
// The latch has to go up BEFORE the media pauses, so it cannot wait for the server. If the
// watched write is then refused, the latch is taken back: the cached detail said watched /
// position 0 while the server still had the item unwatched at the last checkpoint, and the
// once-per-id start guard meant the corrected detail arriving later was never used — the
// episode reopened at 0:00 with a Watched badge the server disagreed with (round 5).
// watched write is then refused, what is taken back is the CLAIM, not the latch (see
// `finishRefused`): the cached detail said watched / position 0 while the server still had
// the item unwatched at the last checkpoint, and the once-per-id start guard meant the
// corrected detail arriving later was never used — the episode reopened at 0:00 with a
// Watched badge the server disagreed with (round 5).
const pos = Math.floor(absRef.current);
const dur = durationRef.current;
void confirmed?.catch(() => {
finished = false;
finishRefused = true;
// Restore the resume point the finish replaced — but ONLY where there is one to restore.
// On the play-to-the-end path `pos` IS the end of the media, and the backend reads a
// position within `_FINISH_MARGIN_S` of the duration as a finish: it would set watched,