Skip to content

Commit f71c6c7

Browse files
square-tombclaude
andcommitted
fix(mobile): start a repeated catch-up before the relay's drift window
A repeated unread catch-up started 60s before the newest message an earlier one returned. A message that reaches the relay late with an older created_at, such as one composed offline, could fall before that start and never count as unread. The relay rejects events whose created_at is more than 900s from its clock, so the next catch-up now starts relayLiveWindowSkewSeconds (960s, as reconnect replay uses) before the previous one was sent. That covers every message stored since, however late, and needs no event timestamps. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent a873876 commit f71c6c7

3 files changed

Lines changed: 49 additions & 55 deletions

File tree

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

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ extension _UnreadCatchUp on ChannelsNotifier {
7373
return;
7474
}
7575

76-
_recordUnreadCaughtUp(events, readAtByChannel, requestedAt);
76+
_recordUnreadCaughtUp(readAtByChannel, requestedAt);
7777

7878
// Keep this response's deletion evidence independently of the bounded
7979
// cross-request tombstones: a large batch can evict its own early IDs.
@@ -192,44 +192,27 @@ extension _UnreadCatchUp on ChannelsNotifier {
192192
/// refresh path catches up again (resume, reconnect, join), and on a slow
193193
/// link re-downloading up to [_unreadCatchUpLimit] messages per channel each
194194
/// time keeps the batch from ever finishing. A later catch-up therefore
195-
/// starts from the newest message an earlier one returned, less
196-
/// [_unreadCatchUpOverlap] for events that reach the relay out of order.
197-
/// Messages before that point were already recorded or skipped. A read
198-
/// timestamp that moved back since then makes the full window apply again.
195+
/// starts [relayLiveWindowSkewSeconds] before an earlier one was sent. The
196+
/// earlier one returned every message stored before it was sent, and the
197+
/// relay stores no event with a `created_at` more than 900s behind its own
198+
/// clock, so anything stored since then is newer than that start, however
199+
/// late it arrived. A read timestamp that moved back since then makes the
200+
/// full window apply again.
199201
int _unreadCatchUpSince(String channelId, int? readAt) {
200202
final afterRead = (readAt ?? -1) + 1;
201203
final caughtUp = _unreadCaughtUpByChannel[channelId];
202204
if (caughtUp == null || (readAt ?? -1) < (caughtUp.readAt ?? -1)) {
203205
return afterRead;
204206
}
205-
return max(afterRead, caughtUp.through - _unreadCatchUpOverlap);
207+
return max(afterRead, caughtUp.sentAt - relayLiveWindowSkewSeconds);
206208
}
207209

208-
/// Remembers, per channel, the newest event [events] returned, capped at
209-
/// [requestedAt] so a client clock running ahead cannot skip messages.
210-
void _recordUnreadCaughtUp(
211-
List<NostrEvent> events,
212-
Map<String, int?> readAtByChannel,
213-
int requestedAt,
214-
) {
215-
final newest = <String, int>{};
216-
for (final event in events) {
217-
final channelId = event.channelId;
218-
if (channelId == null || !readAtByChannel.containsKey(channelId)) {
219-
continue;
220-
}
221-
newest.update(
222-
channelId,
223-
(at) => max(at, event.createdAt),
224-
ifAbsent: () => event.createdAt,
225-
);
226-
}
227-
for (final MapEntry(key: channelId, value: at) in newest.entries) {
228-
final previous = _unreadCaughtUpByChannel[channelId]?.through;
229-
_unreadCaughtUpByChannel[channelId] = (
230-
through: max(previous ?? 0, min(at, requestedAt)),
231-
readAt: readAtByChannel[channelId],
232-
);
210+
/// Remembers when a catch-up that covered every channel in
211+
/// [readAtByChannel] was sent, and the read timestamps it used.
212+
void _recordUnreadCaughtUp(Map<String, int?> readAtByChannel, int sentAt) {
213+
for (final MapEntry(key: channelId, value: readAt)
214+
in readAtByChannel.entries) {
215+
_unreadCaughtUpByChannel[channelId] = (sentAt: sentAt, readAt: readAt);
233216
}
234217
}
235218
}

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

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,6 @@ part 'channels_provider_lifecycle.dart';
3434
const _channelTypeOrder = {'stream': 0, 'forum': 1, 'dm': 2};
3535
const _unreadCatchUpLimit = 1000;
3636

37-
/// How far before the newest message it already returned a later unread
38-
/// catch-up starts. See `_unreadCatchUpSince`.
39-
const _unreadCatchUpOverlap = 60;
40-
4137
/// Relay requests one channel-history batch keeps in flight at most.
4238
const _historyRequestConcurrency = 4;
4339
const _participatedRootIdsPrefix = 'buzz-thread-participation.v1';
@@ -68,9 +64,9 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
6864
String? _subscriptionRelayBaseUrl;
6965
Timer? _backstopTimer;
7066
final Map<String, int> _latestObservedByChannel = {};
71-
// Per channel, the newest message an earlier unread catch-up in this session
72-
// returned and the read timestamp it used. See [_UnreadCatchUp].
73-
final Map<String, ({int through, int? readAt})> _unreadCaughtUpByChannel = {};
67+
// Per channel, when an earlier unread catch-up in this session was sent and
68+
// the read timestamp it used. See [_UnreadCatchUp].
69+
final Map<String, ({int sentAt, int? readAt})> _unreadCaughtUpByChannel = {};
7470
final Map<String, Map<String, ObservedUnreadEvent>>
7571
_observedUnreadEventsByChannel = {};
7672
final Map<String, Set<String>> _unreadDeletedIdsByChannel = {};

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

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2163,12 +2163,13 @@ void main() {
21632163
});
21642164

21652165
test(
2166-
'a repeated catch-up starts near the newest message it already has',
2166+
'a repeated catch-up starts before the last one by the relay drift',
21672167
() async {
2168+
int now() => DateTime.now().millisecondsSinceEpoch ~/ 1000;
21682169
final session = _FakeRelaySession(
21692170
memberships: [_membership(_channelA, myPk)],
21702171
metadata: [_meta(id: _channelA, name: 'general')],
2171-
recentMessages: [message('seen', 10000, mention: true)],
2172+
recentMessages: [message('seen', now() - 3600, mention: true)],
21722173
);
21732174
final container = _buildContainer(session: session);
21742175
addTearDown(container.dispose);
@@ -2177,34 +2178,48 @@ void main() {
21772178
for (final filter in session.queryBatches.lastWhere(isUnread))
21782179
filter.since,
21792180
];
2181+
Future<(int, int)> refreshed() async {
2182+
final before = session.queryBatches.where(isUnread).length;
2183+
final from = now();
2184+
await notifier.refresh();
2185+
await _waitUntil(
2186+
() => session.queryBatches.where(isUnread).length > before,
2187+
);
2188+
await _settle();
2189+
return (from, now());
2190+
}
21802191

2192+
final firstFrom = now();
21812193
await container.read(channelsProvider.future);
21822194
await _waitUntil(() => session.queryBatches.any(isUnread));
21832195
await _settle();
2196+
final firstTo = now();
21842197
// Never read: the first catch-up asks for the whole window.
21852198
expect(lastUnreadSince(), [0, 0]);
21862199

2187-
// A message lands while the app is away, then a refresh catches up.
2188-
session.recentMessages.add(message('missed', 10030, mention: true));
2189-
final before = session.queryBatches.where(isUnread).length;
2190-
await notifier.refresh();
2191-
await _waitUntil(
2192-
() => session.queryBatches.where(isUnread).length > before,
2200+
// While the app is away, a message composed offline reaches the relay
2201+
// with a created_at well before the newest one the app has seen.
2202+
session.recentMessages.add(
2203+
message('late', firstFrom - 600, mention: true),
21932204
);
2194-
await _settle();
2195-
expect(lastUnreadSince(), [10000 - 60, 10000 - 60]);
2205+
final (secondFrom, secondTo) = await refreshed();
2206+
for (final since in lastUnreadSince()) {
2207+
expect(
2208+
since,
2209+
inInclusiveRange(firstFrom - 960, firstTo - 960),
2210+
reason: 'starts 960s before the previous catch-up was sent',
2211+
);
2212+
}
21962213
expect(
21972214
notifier.observedUnreadEventsByChannel[_channelA]?.keys,
2198-
unorderedEquals(['seen', 'missed']),
2215+
unorderedEquals(['seen', 'late']),
21992216
);
22002217

22012218
// Each catch-up moves the start forward.
2202-
final again = session.queryBatches.where(isUnread).length;
2203-
await notifier.refresh();
2204-
await _waitUntil(
2205-
() => session.queryBatches.where(isUnread).length > again,
2206-
);
2207-
expect(lastUnreadSince(), [10030 - 60, 10030 - 60]);
2219+
await refreshed();
2220+
for (final since in lastUnreadSince()) {
2221+
expect(since, inInclusiveRange(secondFrom - 960, secondTo - 960));
2222+
}
22082223
},
22092224
);
22102225

0 commit comments

Comments
 (0)