fix(discover): let a refreshed row override a stale local watch patch

Pausing an episode on one device, finishing it on another and pressing
Refresh left the first device showing the old "minutes left". Restarting the
app showed the right value. Two independent defects produce that, and either
alone reproduces the report.

The first is the watch-state overlay. Every local watch event lands in
WatchStateStore as a patch, and WatchStateSnapshot.apply overwrites
viewOffsetMs unconditionally; isNewerThan only ever orders one patch against
another, never against the server row underneath. Nothing expires a patch and
nothing clears the map except a profile switch, so the Mac's own paused
position kept winning over every subsequent fetch until the process died.

A patch exists to bridge the gap between a local action and the next server
read of that item, so it should stop applying once that read happens. The
store now records the watermark at which a successful authoritative response
returned each key, and suppresses an acknowledged session patch at or below
it. Only a watermark is stored, never the observed state: WatchStateSnapshot
cannot hold a container's leaf counts, and keeping max() per key makes the
order two concurrent responses complete irrelevant. Suppression is a
read-time predicate, so nothing mutates during build.

The barrier covers the parentChain too. patchForItem picks the newest of the
item's own entry and its ancestors', so retiring only the item's entry would
let an older season mark win and render watched/0 -- worse than either the
stale value or the fresh one. An authoritative read of a child already
reflects any container mark that preceded it, so the child's observation
judges its ancestors as well; a newer container action still wins.

Provenance decides what may be suppressed at all. WatchStateEvent now carries
serverAcknowledged, defaulting to false so an unclassified emit site degrades
to today's behaviour rather than silently becoming retireable. An offline
write is owed to the server and a read must never retire it, so it stays
until a WatchPatchPromotionNotifier promotion says the queue replayed it. That
channel is deliberately not a WatchStateEvent: OfflineWatchSyncService reacts
to watched/unwatched by purging queued progress, so replaying one there would
delete a newer rewatch. Promotion matches an exact WatchPatchId -- session
minted for live crossings, derived from the persisted (profile, row, revision)
for queued ones so it still joins after a restart.

Report acceptance is not delivery: PlaybackReportSession resolves true for a
same-state startup heartbeat it drops, so acknowledgement now keys on
onDelivered. A MediaBrowser Started saves play count and last-played date but
not the position, so it cannot acknowledge an offset. No report-derived
watched crossing is acknowledged on any backend -- Jellyfin hard-codes its
threshold and Plex never loads the server pref that would tell it the real
one -- so only an awaited explicit markWatched settles one.

The second defect is that a failed Refresh reported success. Plex _fetchHubs
and the Jellyfin hub legs both degrade a failure to an empty list, and the
library prefetch discarded its failures, so a server whose every hub request
failed was recorded as succeeded; DiscoverProvider then kept the previous rows,
set loaded and surfaced nothing. Worse, the background Continue Watching
refresh wiped the row outright on zero success.

Hub legs now report what they degraded through a HubFetchDiagnostics sink,
which keeps partial rows alongside the failure and leaves every existing
caller untouched. Failures ride through the aggregation results, a leg that
could not run because discovery failed contributes that failure rather than a
successful no-op, and loaded-server ids became succeeded - failed - cancelled
so one bad leg no longer caches a server as covered and blocks its retry. The
toolbar awaits a DiscoverRefreshOutcome and shows the existing unableToLoad
snackbar on failure while the retained rows stay on screen. Rollback after a
mid-pass exception is version-guarded, refilters against the current hidden
libraries and no longer publishes a system shelf the pass never committed.

Observations are staged with the pass and flushed only once the same disposal,
generation and exception checks that authorise committing those rows have
passed, so a discarded or rolled-back response can never suppress a patch.

Also fixes a live data-loss race the promotion work would have built on:
upsertProgressAction stamped a millisecond timestamp and updated the row in
place, so a rewatch queued during an in-flight replay was deleted by id.
Revisions are now strictly monotonic per row, replay deletes and retry updates
compare against them, and the upsert resets the retry fields because a new
revision is a new logical action.

close #1829
This commit is contained in:
edde746
2026-08-08 09:09:48 +02:00
parent 3364b3c22c
commit 5f397a99d9
21 changed files with 1885 additions and 236 deletions
+86 -1
View File
@@ -71,6 +71,8 @@ class _FakeAggregationService extends DataAggregationService {
Set<String>? hubSucceededServerIds;
Set<String> onDeckCancelledServerIds = const {};
Set<String> hubCancelledServerIds = const {};
Set<String> onDeckFailedServerIds = const {};
Set<String> hubFailedServerIds = const {};
List<MediaItem> Function() onDeckResult = () => const [];
List<MediaHub> Function() hubsResult = () => const [];
Future<void>? onDeckGate;
@@ -93,8 +95,10 @@ class _FakeAggregationService extends DataAggregationService {
final items = onDeckResult();
return (
items: limit != null && items.length > limit ? items.sublist(0, limit) : items,
observedItems: [for (final item in items) (item: item, clientScope: null)],
succeededServerIds: onDeckSucceededServerIds ?? serverIds ?? const {'server_1'},
cancelledServerIds: onDeckCancelledServerIds,
failedServerIds: onDeckFailedServerIds,
);
}
@@ -112,10 +116,16 @@ class _FakeAggregationService extends DataAggregationService {
if (started != null && !started.isCompleted) started.complete();
final gate = hubGate;
if (gate != null) await gate;
final hubs = hubsResult();
return (
hubs: hubsResult(),
hubs: hubs,
observedItems: [
for (final hub in hubs)
for (final item in hub.items) (item: item, clientScope: null),
],
succeededServerIds: hubSucceededServerIds ?? serverIds ?? const {'server_1'},
cancelledServerIds: hubCancelledServerIds,
failedServerIds: hubFailedServerIds,
);
}
}
@@ -697,6 +707,81 @@ void main() {
expect(aggregation.onDeckCalls, greaterThan(callsBefore));
});
group('manual refresh reports what actually happened (#1829)', () {
test('a zero-success refresh reports failure while keeping the rows visible', () async {
aggregation.onDeckResult = () => [_item('a')];
aggregation.hubsResult = () => [_hub('hub-1')];
await provider.load();
aggregation.onDeckSucceededServerIds = const {};
aggregation.hubSucceededServerIds = const {};
aggregation.onDeckFailedServerIds = const {'server_1'};
aggregation.hubFailedServerIds = const {'server_1'};
aggregation.onDeckResult = () => const [];
aggregation.hubsResult = () => const [];
expect(await provider.refreshNow(), DiscoverRefreshOutcome.failed);
// Retained content still renders: the error is surfaced by the caller as
// a snackbar, never by blanking the screen.
expect(provider.onDeck.map((i) => i.id), ['a']);
expect(provider.hubs.map((h) => h.id), ['hub-1']);
expect(provider.errorMessage, isNull);
});
test('a partly failed refresh is degraded, not a success', () async {
aggregation.onDeckResult = () => [_item('a')];
aggregation.hubsResult = () => [_hub('hub-1')];
await provider.load();
aggregation.hubFailedServerIds = const {'server_2'};
expect(await provider.refreshNow(), DiscoverRefreshOutcome.degraded);
});
test('a cancelled refresh is not reported as a failure', () async {
aggregation.onDeckSucceededServerIds = const {};
aggregation.hubSucceededServerIds = const {};
aggregation.onDeckCancelledServerIds = const {'server_1'};
aggregation.hubCancelledServerIds = const {'server_1'};
expect(await provider.refreshNow(), DiscoverRefreshOutcome.cancelled);
});
test('a fully successful refresh reports success', () async {
aggregation.onDeckResult = () => [_item('a')];
aggregation.hubsResult = () => [_hub('hub-1')];
expect(await provider.refreshNow(), DiscoverRefreshOutcome.refreshed);
});
test('a server that failed one leg stays eligible for retry', () async {
aggregation.onDeckResult = () => [_item('a')];
aggregation.hubsResult = () => [_hub('hub-1')];
// Succeeded and failed are unions, so one server can appear in both;
// loaded ids must exclude it or syncToOnlineServers never retries.
aggregation.hubFailedServerIds = const {'server_1'};
await provider.load();
final callsBefore = aggregation.hubCalls;
await provider.syncToOnlineServers({'server_1'});
expect(aggregation.hubCalls, greaterThan(callsBefore));
});
test('a zero-success background refresh retains rows and stays silent', () async {
aggregation.onDeckResult = () => [_item('a')];
await provider.load();
aggregation.onDeckSucceededServerIds = const {};
aggregation.onDeckFailedServerIds = const {'server_1'};
aggregation.onDeckResult = () => const [];
await provider.refreshContinueWatching();
// Previously this wiped the row outright.
expect(provider.onDeck.map((i) => i.id), ['a']);
expect(provider.errorMessage, isNull);
expect(provider.isLoading, isFalse);
});
});
test('a disrupted half is independent: on-deck commits while hubs stay loading', () async {
aggregation.onDeckResult = () => [_item('a')];
aggregation.hubSucceededServerIds = const {};