Skip to content

Commit 464448c

Browse files
browclaude
andauthored
fix(mobile): resync read state from the last fetch, not the whole week (#8903)
## Summary Every read-state resync (each reconnect and each resume from background) fetches every read-state blob (kind 30078, `#t: read-state`) from the past week, then opens a live subscription with no `since`, which replays the same blobs again. Merging keeps the newest mark per context, so blobs from before the previous fetch add nothing. Each blob is a whole device's read marks, about 100KB for a heavy reader. A later fetch and the live subscription now start `relayCrossDeviceSkewSeconds` (1860s) before the last successful fetch was sent. The relay rejects a `created_at` more than 900s from its clock, and blobs come from other devices, so a writer 900s slow and this phone 900s fast are at most 1800s apart. Every blob stored since that fetch falls inside the window. A failed fetch keeps the earlier start. The first fetch of a manager still covers the whole horizon. Companion to [#8901](#8901) and [#8902](#8902), which do the same for the unread catch-up and the latest-message query. Measured on an iPhone 12 mini against the internal relay, resuming after 60s in the background (kind 30078 websocket bytes, instrumented profile build): | | main | this PR | | --- | --- | --- | | Read-state resync on resume | about 1.8MB (91 blobs, fetch plus subscription replay) | 415KB (4 blobs changed since the last fetch) | ## Testing - New test: the first fetch covers the horizon, the live subscription and later fetches start 1860s before the last successful fetch was sent, and a failed fetch keeps that start. Confirmed it fails without the fix and with the earlier 960s window. - New test: after the clock moves back, a resync whose fetch fails isn't retried on every later read; the next reconnect fetches the whole horizon. Confirmed it fails without the fix. - `just mobile-check` and `just mobile-test` pass. - Device: resumed the app on the 12 mini on Wi-Fi; the resync fetched only the 4 blobs stored since the previous fetch, and the live subscription replayed none. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9d1b684 commit 464448c

3 files changed

Lines changed: 239 additions & 2 deletions

File tree

‎mobile/lib/shared/read_state/read_state_manager.dart‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,10 @@ class ReadStateManager {
8181
Completer<void>? _publishCompleter;
8282
bool _remoteUnsupported = false;
8383
int _maxFetchedCreatedAt = 0;
84+
// When the last successful history fetch was sent. A later fetch and the
85+
// live subscription ask only for blobs stored since then.
86+
int? _lastFetchSentAt;
87+
final int Function() _now;
8488
final Map<String, int> _contextSourceCreatedAt = {};
8589
final Set<String> _pendingSyncedAdvances = {};
8690

@@ -93,7 +97,9 @@ class ReadStateManager {
9397
required SignedEventRelay? signedEventRelay,
9498
required bool remoteEnabled,
9599
required VoidCallback onChanged,
96-
}) : _crypto = crypto,
100+
@visibleForTesting int Function() now = currentUnixSeconds,
101+
}) : _now = now,
102+
_crypto = crypto,
97103
_storage = ReadStateStorage(prefs),
98104
_relaySession = relaySession,
99105
_signedEventRelay = signedEventRelay,
@@ -142,6 +148,7 @@ class ReadStateManager {
142148

143149
void markContextRead(String contextId, int unixTimestamp) {
144150
if (_disposed || isOverrideContext(contextId)) return;
151+
_resyncIfClockMovedBack();
145152
// Set first: retention keeps the most recently written marks, so the
146153
// save that follows must already see this read as the newest.
147154
_contextSourceCreatedAt[contextId] = max(
@@ -274,6 +281,7 @@ class ReadStateManager {
274281
}
275282

276283
Future<bool> _fetchAndMerge() async {
284+
final sentAt = _now();
277285
try {
278286
final events = await _relaySession!.fetchHistory(
279287
NostrFilter(
@@ -282,11 +290,15 @@ class ReadStateManager {
282290
tags: const {
283291
'#t': ['read-state'],
284292
},
285-
since: currentUnixSeconds() - readStateHorizonSeconds,
293+
since: max(
294+
sentAt - readStateHorizonSeconds,
295+
_storedSinceLastFetch ?? 0,
296+
),
286297
limit: readStateFetchLimit,
287298
),
288299
);
289300
_mergeEvents(events);
301+
_lastFetchSentAt = sentAt;
290302
_persistLocalState();
291303
_onChanged();
292304
return true;
@@ -364,6 +376,32 @@ class ReadStateManager {
364376
return changed;
365377
}
366378

379+
/// The earliest `created_at` a blob stored since the last successful fetch
380+
/// was sent can carry, or null before one. Merging takes the newest mark per
381+
/// context, so blobs from before it add nothing. Blobs come from other
382+
/// devices, so this reaches back [relayCrossDeviceSkewSeconds].
383+
int? get _storedSinceLastFetch {
384+
final sentAt = _lastFetchSentAt;
385+
// A clock set back since then can't place blobs relative to it, so the
386+
// next fetch covers the whole horizon again.
387+
if (sentAt == null || sentAt > _now()) return null;
388+
return sentAt - relayCrossDeviceSkewSeconds;
389+
}
390+
391+
/// The live subscription keeps the `since` it was opened with. When the
392+
/// clock has since moved back behind the last fetch, that `since` may be in
393+
/// the relay's future and hide other devices' blobs until a reconnect, so
394+
/// resync now: the fetch covers the whole horizon and the subscription is
395+
/// reopened from the corrected clock. The last fetch's time is dropped
396+
/// first, so a resync that fails isn't retried on every read; the next
397+
/// fetch covers the whole horizon either way.
398+
void _resyncIfClockMovedBack() {
399+
final sentAt = _lastFetchSentAt;
400+
if (_unsubscribeLive == null || sentAt == null || sentAt <= _now()) return;
401+
_lastFetchSentAt = null;
402+
unawaited(reinitializeRemote());
403+
}
404+
367405
Future<bool> _startLiveSubscription() async {
368406
try {
369407
final unsub = await _relaySession!.subscribe(
@@ -373,6 +411,8 @@ class ReadStateManager {
373411
tags: const {
374412
'#t': ['read-state'],
375413
},
414+
// The fetch just merged everything stored before this.
415+
since: _storedSinceLastFetch,
376416
limit: readStateFetchLimit,
377417
),
378418
_handleIncomingEvent,

‎mobile/lib/shared/relay/relay_reconnect_policy.dart‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ const relayReplaySkewSeconds = 5;
2727
/// narrower window would miss it for a quiet subscription.
2828
const relayLiveWindowSkewSeconds = 960;
2929

30+
/// Seconds a repeated read of events other devices wrote reaches behind the
31+
/// moment the previous read was sent. The relay accepts a `created_at` up to
32+
/// 900s either side of its own clock, so a writer 900s slow and a reader 900s
33+
/// fast are 1800s apart, plus 60s of margin. [relayLiveWindowSkewSeconds]
34+
/// covers only the reader's own skew.
35+
const relayCrossDeviceSkewSeconds = 1860;
36+
3037
/// Whether [closeCode] says the relay is restarting or going away.
3138
bool isRelayServiceRestartClose(int? closeCode) =>
3239
closeCode == 1012 || closeCode == 1001;

‎mobile/test/features/channels/read_state/read_state_manager_test.dart‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,192 @@ void main() {
685685
expect(relay.liveSubscriptions, 0);
686686
});
687687

688+
test('a re-sync asks only for blobs stored since the last fetch', () async {
689+
SharedPreferences.setMockInitialValues({});
690+
final prefs = await SharedPreferences.getInstance();
691+
final keychain = nostr.Keys.generate();
692+
final crypto = ReadStateCrypto.tryCreate(
693+
nsec: keychain.nsec,
694+
pubkey: keychain.public,
695+
)!;
696+
final relay = _FakeRelaySession();
697+
final manager = ReadStateManager(
698+
pubkey: keychain.public,
699+
relayUrl: _relayUrl,
700+
prefs: prefs,
701+
crypto: crypto,
702+
relaySession: relay,
703+
signedEventRelay: _FakeSignedEventRelay(),
704+
remoteEnabled: true,
705+
onChanged: () {},
706+
);
707+
708+
final before = currentUnixSeconds();
709+
await manager.initialize();
710+
final after = currentUnixSeconds();
711+
// The first fetch covers the whole horizon.
712+
expect(
713+
relay.fetchFilters.single.since,
714+
inInclusiveRange(
715+
before - readStateHorizonSeconds,
716+
after - readStateHorizonSeconds,
717+
),
718+
);
719+
// Blobs come from other devices: a writer 900s slow and this reader 900s
720+
// fast are 1800s apart, plus a margin.
721+
const overlap = 2 * 900 + 60;
722+
final firstSince = inInclusiveRange(before - overlap, after - overlap);
723+
expect(relay.subscribeFilters.single.since, firstSince);
724+
725+
// A failed re-sync fetch leaves the next one starting from the last
726+
// successful fetch.
727+
relay.failNextFetch = true;
728+
await manager.reinitializeRemote();
729+
await manager.reinitializeRemote();
730+
expect(relay.fetchFilters, hasLength(3));
731+
expect(relay.fetchFilters[1].since, firstSince);
732+
expect(relay.fetchFilters[2].since, firstSince);
733+
expect(relay.subscribeFilters.last.since, isNotNull);
734+
735+
manager.dispose();
736+
});
737+
738+
test('a clock set back after a fetch resyncs the whole horizon', () async {
739+
SharedPreferences.setMockInitialValues({});
740+
final prefs = await SharedPreferences.getInstance();
741+
final keychain = nostr.Keys.generate();
742+
final crypto = ReadStateCrypto.tryCreate(
743+
nsec: keychain.nsec,
744+
pubkey: keychain.public,
745+
)!;
746+
final relay = _FakeRelaySession();
747+
var now = 1000000 + 7200;
748+
final manager = ReadStateManager(
749+
pubkey: keychain.public,
750+
relayUrl: _relayUrl,
751+
prefs: prefs,
752+
crypto: crypto,
753+
relaySession: relay,
754+
signedEventRelay: _FakeSignedEventRelay(),
755+
remoteEnabled: true,
756+
onChanged: () {},
757+
now: () => now,
758+
);
759+
760+
// The first fetch ran while the clock was two hours fast.
761+
await manager.initialize();
762+
now = 1000000;
763+
await manager.reinitializeRemote();
764+
expect(relay.fetchFilters.last.since, now - readStateHorizonSeconds);
765+
expect(
766+
relay.subscribeFilters.last.since,
767+
now - relayCrossDeviceSkewSeconds,
768+
);
769+
770+
manager.dispose();
771+
});
772+
773+
test(
774+
'a read after the clock moves back reopens the live subscription',
775+
() async {
776+
SharedPreferences.setMockInitialValues({});
777+
final prefs = await SharedPreferences.getInstance();
778+
final keychain = nostr.Keys.generate();
779+
final crypto = ReadStateCrypto.tryCreate(
780+
nsec: keychain.nsec,
781+
pubkey: keychain.public,
782+
)!;
783+
final relay = _FakeRelaySession();
784+
var now = 1000000 + 7200;
785+
final manager = ReadStateManager(
786+
pubkey: keychain.public,
787+
relayUrl: _relayUrl,
788+
prefs: prefs,
789+
crypto: crypto,
790+
relaySession: relay,
791+
signedEventRelay: _FakeSignedEventRelay(),
792+
remoteEnabled: true,
793+
onChanged: () {},
794+
now: () => now,
795+
);
796+
797+
// Initialized while the clock was two hours fast, so the live
798+
// subscription's since is in the relay's future.
799+
await manager.initialize();
800+
expect(
801+
relay.subscribeFilters.last.since,
802+
now - relayCrossDeviceSkewSeconds,
803+
);
804+
805+
// The clock is corrected while connected. The next read resyncs.
806+
now = 1000000;
807+
manager.markContextRead('channel-a', now);
808+
await pumpEventQueue();
809+
expect(relay.fetchFilters.last.since, now - readStateHorizonSeconds);
810+
expect(
811+
relay.subscribeFilters.last.since,
812+
now - relayCrossDeviceSkewSeconds,
813+
);
814+
expect(relay.subscribeCount, 2);
815+
expect(relay.liveSubscriptions, 1);
816+
817+
// Once resynced, reads don't resync again.
818+
final fetches = relay.fetchCount;
819+
manager.markContextRead('channel-b', now);
820+
await pumpEventQueue();
821+
expect(relay.fetchCount, fetches);
822+
expect(relay.subscribeCount, 2);
823+
824+
manager.dispose();
825+
},
826+
);
827+
828+
test(
829+
'a failed resync after the clock moves back is not retried on every read',
830+
() async {
831+
SharedPreferences.setMockInitialValues({});
832+
final prefs = await SharedPreferences.getInstance();
833+
final keychain = nostr.Keys.generate();
834+
final crypto = ReadStateCrypto.tryCreate(
835+
nsec: keychain.nsec,
836+
pubkey: keychain.public,
837+
)!;
838+
final relay = _FakeRelaySession();
839+
var now = 1000000 + 7200;
840+
final manager = ReadStateManager(
841+
pubkey: keychain.public,
842+
relayUrl: _relayUrl,
843+
prefs: prefs,
844+
crypto: crypto,
845+
relaySession: relay,
846+
signedEventRelay: _FakeSignedEventRelay(),
847+
remoteEnabled: true,
848+
onChanged: () {},
849+
now: () => now,
850+
);
851+
await manager.initialize();
852+
853+
// The clock is corrected, and the resync's fetch fails.
854+
now = 1000000;
855+
relay.failNextFetch = true;
856+
manager.markContextRead('channel-a', now);
857+
await pumpEventQueue();
858+
final fetches = relay.fetchCount;
859+
expect(relay.liveSubscriptions, 1);
860+
expect(relay.subscribeFilters.last.since, isNull);
861+
862+
// Later reads don't fetch again; the next reconnect covers the horizon.
863+
manager.markContextRead('channel-b', now);
864+
manager.markContextRead('channel-c', now);
865+
await pumpEventQueue();
866+
expect(relay.fetchCount, fetches);
867+
await manager.reinitializeRemote();
868+
expect(relay.fetchFilters.last.since, now - readStateHorizonSeconds);
869+
870+
manager.dispose();
871+
},
872+
);
873+
688874
test('remote read-state rollback is ignored', () async {
689875
SharedPreferences.setMockInitialValues({});
690876
final prefs = await SharedPreferences.getInstance();
@@ -874,13 +1060,16 @@ class _FakeRelaySession extends RelaySessionNotifier {
8741060
int fetchCount = 0;
8751061
int subscribeCount = 0;
8761062
int liveSubscriptions = 0;
1063+
final List<NostrFilter> fetchFilters = [];
1064+
final List<NostrFilter> subscribeFilters = [];
8771065

8781066
@override
8791067
Future<List<NostrEvent>> fetchHistory(
8801068
NostrFilter filter, {
8811069
Duration timeout = const Duration(seconds: 8),
8821070
}) async {
8831071
fetchCount++;
1072+
fetchFilters.add(filter);
8841073
await fetchGate;
8851074
if (failNextFetch) {
8861075
failNextFetch = false;
@@ -896,6 +1085,7 @@ class _FakeRelaySession extends RelaySessionNotifier {
8961085
void Function(String message)? onClosed,
8971086
}) async {
8981087
subscribeCount++;
1088+
subscribeFilters.add(filter);
8991089
liveSubscriptions++;
9001090
var open = true;
9011091
return () {

0 commit comments

Comments
 (0)