Skip to content

Commit d342cf1

Browse files
browclaude
andauthored
fix(mobile): catch up unread from the newest message already seen (#8901)
## Summary Every channel refresh path (app resume, reconnect, the backstop, joining a channel) re-runs the unread catch-up. Each run asked for every channel's messages since its read timestamp, up to 1000 full messages per channel. For a reader with long-unread channels that is megabytes, every time. Measured on an iPhone 12 mini against the internal relay (gzip wire bytes, instrumented profile build): | | main | this PR | | --- | --- | --- | | Cold start unread catch-up | 3.5MB | 3.5MB (unchanged, first catch-up) | | Unread catch-up on app resume | 3.5MB | 23KB | The 60s foreground backstop is one of those paths, so on main an open app downloads the full catch-up again every minute (about 3.5MB a minute on this account). With this PR each tick costs about 23KB. On an Edge-class link (Network Link Conditioner "Edge", about 30KB/s) a 3.5MB batch needs about two minutes but has an 8s history timeout, so it never completes and the next refresh starts it again. A later catch-up in the same session now starts `relayCrossDeviceSkewSeconds` (1860s) before the previous one was sent. The relay rejects events whose `created_at` is more than 900s from its clock, so a sender 900s slow and this phone 900s fast are at most 1800s apart. Every message stored since the previous catch-up therefore falls inside the window, including one that arrives late with an older timestamp (for example, composed offline or on a phone with a slow clock). Messages before that point were already recorded or skipped, so unread and attention state is unchanged. The record is cleared with the rest of the unread state when the channel list is rebuilt (community or identity switch), and ignored if a channel's read timestamp ever moves back. A channel whose websocket fallback filter failed (without a deadline, so the batch still completes) is not recorded, so the next catch-up asks for its whole window again. A deletion that removes an unread event the app already recorded also drops the channel's record. That event may have been the oldest of a full window of quiet agent messages, standing in for older unread ones the window hides, and only a whole-window catch-up finds them again. A catch-up that was already out when that happened doesn't restore the record, since its response only covers the narrower window. A channel muted or unmuted since its record also catches up over its whole window, because muting changes which messages count. ## Testing - New test: a repeated catch-up starts 1860s before the previous one was sent, and still records a message that arrived late with a timestamp 1500s before it. Confirmed it fails without the drift window (`since` starts at the previous send time) and with the earlier 960s window. - New test: a rebuilt channel list catches up over the whole window again. - New test: a channel whose batch and websocket fallback both failed catches up over its whole window on the next refresh. Confirmed it fails without the fix. - Extended test: deleting the quiet-window marker while a catch-up is out makes the next catch-up ask for the whole window, and the next quiet message stands in. Confirmed it fails without each fix. - New test: a channel unmuted since its last catch-up asks for its whole window and records its ordinary backlog. Confirmed it fails without the fix. - The test fake now honors `since` and `until` like the relay. The deletion cases now use recent timestamps, because a relay never stores a 1970 event late. - `just mobile-check` and `just mobile-test` pass. - Device: resumed Buzz on the 12 mini on Wi-Fi with the fix; backgrounded for a minute, the catch-up requests were 22KB and 0.5KB instead of 3.2MB and 287KB (f71c6c7). 🤖 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 464448c commit d342cf1

5 files changed

Lines changed: 361 additions & 6 deletions

File tree

‎mobile/lib/features/channels/channel_unread_catch_up.dart‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ extension _UnreadCatchUp on ChannelsNotifier {
3838
for (final channel in activeChannels)
3939
channel.id: readState.effectiveTimestamp(channel.id),
4040
};
41+
final requestedAt = currentUnixSeconds();
42+
final cursorsAtStart = {
43+
for (final channel in activeChannels)
44+
channel.id: _unreadCaughtUpByChannel[channel.id],
45+
};
4146
final filters = [
4247
for (final channel in activeChannels)
4348
for (final kinds in [
@@ -49,15 +54,21 @@ extension _UnreadCatchUp on ChannelsNotifier {
4954
tags: {
5055
'#h': [channel.id],
5156
},
52-
since: (readAtByChannel[channel.id] ?? -1) + 1,
57+
since: _unreadCatchUpSince(
58+
channel.id,
59+
readAtByChannel[channel.id],
60+
muted: mutedChannelIds.contains(channel.id),
61+
),
5362
limit: _unreadCatchUpLimit,
5463
),
5564
];
5665

66+
final failedChannelIds = <String>{};
5767
final events = await _fetchChannelHistoryBatch(
5868
session,
5969
filters,
6070
operation: 'unread catch-up',
71+
failedChannelIds: failedChannelIds,
6172
);
6273
// Unavailable: keep the unread state already observed.
6374
if (events == null) return;
@@ -69,6 +80,14 @@ extension _UnreadCatchUp on ChannelsNotifier {
6980
return;
7081
}
7182

83+
_recordUnreadCaughtUp(
84+
readAtByChannel,
85+
requestedAt,
86+
failedChannelIds,
87+
cursorsAtStart: cursorsAtStart,
88+
mutedChannelIds: mutedChannelIds,
89+
);
90+
7291
// Keep this response's deletion evidence independently of the bounded
7392
// cross-request tombstones: a large batch can evict its own early IDs.
7493
final batchDeletedIds = <String>{};
@@ -179,4 +198,61 @@ extension _UnreadCatchUp on ChannelsNotifier {
179198
}
180199
}
181200
}
201+
202+
/// Where a channel's catch-up starts.
203+
///
204+
/// The first catch-up in a session starts after the read timestamp. Every
205+
/// refresh path catches up again (resume, reconnect, join), and on a slow
206+
/// link re-downloading up to [_unreadCatchUpLimit] messages per channel each
207+
/// time keeps the batch from ever finishing. A later catch-up therefore
208+
/// starts [relayCrossDeviceSkewSeconds] before an earlier one was sent. The
209+
/// earlier one returned every message stored before it was sent, and the
210+
/// relay stores no event with a `created_at` more than 900s from its own
211+
/// clock, so anything stored since then is newer than that start, however
212+
/// late it arrived and however far this phone's clock is from the sender's. A read timestamp that moved back since then, or a mute
213+
/// change (which changes what counts as unread), makes the full window apply
214+
/// again.
215+
int _unreadCatchUpSince(
216+
String channelId,
217+
int? readAt, {
218+
required bool muted,
219+
}) {
220+
final afterRead = (readAt ?? -1) + 1;
221+
final caughtUp = _unreadCaughtUpByChannel[channelId];
222+
if (caughtUp == null ||
223+
caughtUp.muted != muted ||
224+
(readAt ?? -1) < (caughtUp.readAt ?? -1)) {
225+
return afterRead;
226+
}
227+
return max(afterRead, caughtUp.sentAt - relayCrossDeviceSkewSeconds);
228+
}
229+
230+
/// Remembers when a catch-up over [readAtByChannel] was sent, and the read
231+
/// timestamps and mute state it used, for every channel except
232+
/// [failedChannelIds]: their filters failed, so the next catch-up still needs
233+
/// their earlier window. A channel whose cursor changed while the request was
234+
/// out, such as a live deletion of its marker, keeps that change: this
235+
/// response only covered the window the old cursor asked for.
236+
void _recordUnreadCaughtUp(
237+
Map<String, int?> readAtByChannel,
238+
int sentAt,
239+
Set<String> failedChannelIds, {
240+
required Map<String, ({int sentAt, int? readAt, bool muted})?>
241+
cursorsAtStart,
242+
required Set<String> mutedChannelIds,
243+
}) {
244+
for (final MapEntry(key: channelId, value: readAt)
245+
in readAtByChannel.entries) {
246+
if (failedChannelIds.contains(channelId)) continue;
247+
final atStart = cursorsAtStart[channelId];
248+
if (atStart != null && _unreadCaughtUpByChannel[channelId] != atStart) {
249+
continue;
250+
}
251+
_unreadCaughtUpByChannel[channelId] = (
252+
sentAt: sentAt,
253+
readAt: readAt,
254+
muted: mutedChannelIds.contains(channelId),
255+
);
256+
}
257+
}
182258
}

‎mobile/lib/features/channels/channel_unread_deletions.dart‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,12 @@ extension _UnreadDeletions on ChannelsNotifier {
3030
: [channelId];
3131
for (final id in channels) {
3232
final observed = _observedUnreadEventsByChannel[id];
33+
final before = observed?.length;
3334
observed?.removeWhere((key, _) => targets.contains(key));
35+
// The deleted event may have been the marker standing in for a full
36+
// window of quiet messages, which can hide older unread ones. Read the
37+
// channel's whole window again rather than only since the last read.
38+
if (observed?.length != before) _unreadCaughtUpByChannel.remove(id);
3439
if (observed == null || observed.isEmpty) {
3540
_observedUnreadEventsByChannel.remove(id);
3641
_latestObservedByChannel.remove(id);

‎mobile/lib/features/channels/channels_provider.dart‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import 'channel_management_provider.dart'
1616
import 'channel_mutes/channel_mutes_provider.dart';
1717
import 'huddle_channel_filter.dart';
1818
import '../../shared/read_state/read_state_provider.dart';
19+
import '../../shared/read_state/read_state_time.dart';
1920
import '../../shared/profile/user_cache_provider.dart';
2021
import 'thread_follows/thread_follows_provider.dart';
2122
import 'unread_badge/is_high_priority_event.dart';
@@ -63,6 +64,10 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
6364
String? _subscriptionRelayBaseUrl;
6465
Timer? _backstopTimer;
6566
final Map<String, int> _latestObservedByChannel = {};
67+
// Per channel, when an earlier unread catch-up in this session was sent, and
68+
// the read timestamp and mute state it used. See [_UnreadCatchUp].
69+
final Map<String, ({int sentAt, int? readAt, bool muted})>
70+
_unreadCaughtUpByChannel = {};
6671
final Map<String, Map<String, ObservedUnreadEvent>>
6772
_observedUnreadEventsByChannel = {};
6873
final Map<String, Set<String>> _unreadDeletedIdsByChannel = {};
@@ -241,6 +246,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
241246
_clearLiveSubscriptions();
242247
_latestObservedByChannel.clear();
243248
_observedUnreadEventsByChannel.clear();
249+
_unreadCaughtUpByChannel.clear();
244250
_unreadDeletedIdsByChannel.clear();
245251
_unscopedUnreadDeletedIds.clear();
246252
_backstopTimer?.cancel();
@@ -587,6 +593,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
587593
}
588594

589595
/// Returns null when the batch is unavailable: it hit a relay deadline.
596+
/// Adds to [failedChannelIds] the channels whose fallback filter failed
597+
/// another way; the result has none of their events.
590598
///
591599
/// The relay rejects a request whose filters name more than
592600
/// [kMaxExplicitChannelValues] channels in aggregate, so larger batches are
@@ -595,6 +603,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
595603
RelaySessionNotifier session,
596604
List<NostrFilter> filters, {
597605
required String operation,
606+
Set<String>? failedChannelIds,
598607
}) async {
599608
final requests = <List<NostrFilter>>[];
600609
var channelValues = 0;
@@ -654,13 +663,15 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
654663
final fallbackEvents = await _fetchChannelHistoryFallback(
655664
session,
656665
fallback,
666+
failedChannelIds,
657667
);
658668
return fallbackEvents == null ? null : [...events, ...fallbackEvents];
659669
}
660670

661671
Future<List<NostrEvent>?> _fetchChannelHistoryFallback(
662672
RelaySessionNotifier session,
663673
List<NostrFilter> filters,
674+
Set<String>? failedChannelIds,
664675
) async {
665676
final events = <NostrEvent>[];
666677
var deadline = false;
@@ -679,7 +690,11 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
679690
return await session.fetchHistory(filter);
680691
} catch (error) {
681692
// A timed-out filter makes the batch unavailable, not empty.
682-
if (isRelayDeadlineError(error)) deadline = true;
693+
if (isRelayDeadlineError(error)) {
694+
deadline = true;
695+
} else {
696+
failedChannelIds?.addAll(filter.tags['#h'] ?? const []);
697+
}
683698
return const <NostrEvent>[];
684699
}
685700
}),

‎mobile/test/features/channels/channels_provider_deletion_cases.dart‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@ void _unreadDeletionCases() {
55
test(
66
'deleted mentions stop unread (kind ${format.$1}, h ${format.$2})',
77
() async {
8+
// Timestamps below are offsets from a recent base: a repeated
9+
// catch-up starts within the relay's drift window, and the relay
10+
// stores nothing older than that since then.
11+
final base = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 100;
812
NostrEvent message(String id, int at) => NostrEvent(
913
id: id,
1014
pubkey: 'alice',
11-
createdAt: at,
15+
createdAt: base + at,
1216
kind: 9,
1317
tags: const [
1418
['h', _channelA],
@@ -20,7 +24,7 @@ void _unreadDeletionCases() {
2024
NostrEvent deletion(String id, String target, int at) => NostrEvent(
2125
id: id,
2226
pubkey: 'alice',
23-
createdAt: at,
27+
createdAt: base + at,
2428
kind: format.$1,
2529
tags: [
2630
if (format.$2) ['h', _channelA],
@@ -108,7 +112,7 @@ void _unreadDeletionCases() {
108112
NostrEvent unreact(String id, int at) => NostrEvent(
109113
id: id,
110114
pubkey: 'alice',
111-
createdAt: at,
115+
createdAt: base + at,
112116
kind: EventKind.deletion,
113117
tags: [
114118
['e', 'reaction-$id'],

0 commit comments

Comments
 (0)