From 2c7e67fcc17ca17e6557d81fc9dec82b0cf4fa58 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 25 Nov 2026 13:53:55 -0800 Subject: [PATCH] fix(mobile): keep Active activity unknown after deletions the gap hides (#9951) Follow-up to #9832, which derives the Active filter's activity from the channel list's own reads. Three cases could leave a channel marked known with activity that is too old or too new. Each now leaves it unknown, so it stays visible until the next list read re-reads it (the filter's existing fail-open path). - **A latest post deleted while offline, after the read marker moved past the deletion on another device.** The catch-up asked for deletions only after the read marker, so it never saw this one, and the channel kept the deleted post's time. The gap read, which already runs for a channel an Active section shows that has an activity gap, now also asks for deletions of each such channel's current latest post (`#e` plus `#h`, since the gap's start) and forgets a head they removed. With up to 64 such channels, those deletions are read in the gap read's own request. Past that, the gap posts are read and applied first, and the deletions are then read only for the channels whose latest post no gap post replaced, so a failed deletion read leaves only those channels unknown. When the read marker sits on the latest post, so the gap read is moot, the catch-up's deletion filter for that channel starts one second earlier instead, so a deletion in that post's second is seen. A deletion from that extra second only updates the Active filter's activity. ([review comment](https://github.com/block/buzz/pull/9832#issuecomment-7053648925)) - **A gap read whose one post is already deleted.** The gap read asks for the newest post in the gap (`limit: 1`). When the catch-up has just found that post deleted, an older post in the gap may survive, but the channel was marked covered. It now stays unknown. ([review comment](https://github.com/block/buzz/pull/9832#discussion_r4688526643)) - **A gap read whose signature checks throw.** The channels were marked covered with nothing recorded. They now stay unknown, as the catch-up already does when its own checks throw. ([review comment](https://github.com/block/buzz/pull/9832#discussion_r4688526649)) ### Validation - Added three steps to the journey test [Active filter activity survives rebuilds, read gaps, failed catch-ups and deletions](https://github.com/block/buzz/blob/bc664ae8a9bfa603419f42a5ea7a3fd5fea80755/mobile/test/features/channels/channels_provider_test.dart), one per case, plus a step that another post's deletion in the extra second leaves a page being saved current. Added [gap posts settle Active activity even when the head deletion read fails](https://github.com/block/buzz/blob/55144f79be4ddbf191d460fd8f5fcd62f8594300/mobile/test/features/channels/channels_provider_test.dart) for 65 gap channels, with every gap channel holding a cached head (two requests) and with two empty ones (one request). - Full-app run on an iOS 27 simulator signed in to a Builderlab community: channel list on launch, Active filter (7 days) collapsing each section to its active channels, opening a channel and back, background and resume, pull to refresh, and a cold relaunch with Active kept. All behaved as on main, with no error notice. The three changed paths need staged deletions and failures a live community can't produce, so only the journey test covers them. ### Regressions - **Network:** no new requests while a gap read's posts and the head ids fit in one request (128 channel values, so always up to 64 such channels). Past that, one more optional request per 128 channels, sent after the gap posts settle and only for the channels whose latest post no gap post replaced. The optional gap read, sent after the unread badges and only for channels an Active section shows with an activity gap, names their latest posts by id and returns only deletions of those posts. The unread catch-up's filters are unchanged, except that a shown channel whose latest post sits at the read marker asks for deletions from one second earlier. - **Unread state and saved pages:** unchanged for `h`-tagged deletions, including those from the extra second, which only update the Active filter's activity. A deletion without an `h` tag stamped in that extra second takes the ordinary unread path, as main already does for one a second later. For a reaction removal (what agents send when a turn ends), that republishes the list once, with no saved page or badge change. An untagged deletion of a post already observed would also reset that channel's unread catch-up cursor, so the next reconnect fetches its backlog again, but no shipped client sends one: desktop, mobile and the SDK all tag `h` on post deletions. - **Activity:** each change only turns a channel unknown, which keeps it visible in Active, never hidden. buzz-review-completed --------- Signed-off-by: Tom Brow Co-authored-by: studio --- .../channels/channel_latest_activity.dart | 3 + .../channels/channel_unread_catch_up.dart | 180 +++++++++++- .../channels/channels_provider_test.dart | 258 +++++++++++++++++- 3 files changed, 422 insertions(+), 19 deletions(-) diff --git a/mobile/lib/features/channels/channel_latest_activity.dart b/mobile/lib/features/channels/channel_latest_activity.dart index 8e5571d856..dd9c94a907 100644 --- a/mobile/lib/features/channels/channel_latest_activity.dart +++ b/mobile/lib/features/channels/channel_latest_activity.dart @@ -40,6 +40,9 @@ class _ChannelActivity { /// The channel's activity time, for deciding whether a read can change it. int? latestAt(String channelId) => _latest[channelId]?.at; + /// The id of the channel's latest post, if one is known. + String? latestId(String channelId) => _latest[channelId]?.id; + /// Whether a latest read or live message covered [channelId] since its /// latest post was last deleted, if ever. A list read that keeps the list's /// times still reads the channels without one. diff --git a/mobile/lib/features/channels/channel_unread_catch_up.dart b/mobile/lib/features/channels/channel_unread_catch_up.dart index 4074177b69..f5826355e9 100644 --- a/mobile/lib/features/channels/channel_unread_catch_up.dart +++ b/mobile/lib/features/channels/channel_unread_catch_up.dart @@ -1,5 +1,9 @@ part of 'channels_provider.dart'; +// Channels per gap-head deletion filter: half the relay's per-request `#h` +// cap, so two such filters fit in one request. +const _headDeletionChannels = kMaxExplicitChannelValues ~/ 2; + extension _UnreadCatchUp on ChannelsNotifier { /// Backfills unread badges for the channels this refresh just installed. /// @@ -58,16 +62,19 @@ extension _UnreadCatchUp on ChannelsNotifier { }; final filters = [ for (final channel in activeChannels) - for (final kinds in [ - EventKind.channelMessageEventKinds, - [EventKind.deletion, EventKind.nip29DeleteEvent], + for (final (kinds, since) in [ + (EventKind.channelMessageEventKinds, sinceByChannel[channel.id]!), + ( + [EventKind.deletion, EventKind.nip29DeleteEvent], + _deletionsSince(channel.id, sinceByChannel[channel.id]!), + ), ]) NostrFilter( kinds: kinds, tags: { '#h': [channel.id], }, - since: sinceByChannel[channel.id], + since: since, limit: _unreadCatchUpLimit, ), ]; @@ -140,8 +147,19 @@ extension _UnreadCatchUp on ChannelsNotifier { final batchDeletedIds = {}; var appliedDeletion = false; final activityCandidates = []; + // Deletions from before a channel's own window come only from + // [_deletionsSince], which asks for them to see whether the Active head + // went. They are not new to the unread state, so they only reach it. + final headDeletedIds = {}; for (final event in events) { final channelId = event.channelId; + if (channelId != null && + event.createdAt < (sinceByChannel[channelId] ?? 0) && + (event.kind == EventKind.deletion || + event.kind == EventKind.nip29DeleteEvent)) { + headDeletedIds.addAll(_deletionTargets(event)); + continue; + } if (channelById.containsKey(channelId) || (channelId == null && event.kind == EventKind.deletion)) { if (_applyUnreadDeletion(event)) { @@ -249,7 +267,10 @@ extension _UnreadCatchUp on ChannelsNotifier { // checked. gapFilters.removeWhere((id, _) => failedChannelIds.contains(id)); deferredGaps.removeAll(failedChannelIds); - final coverageChanged = _activity.forgetHeads(batchDeletedIds); + final coverageChanged = _activity.forgetHeads({ + ...batchDeletedIds, + ...headDeletedIds, + }); if (recordedAtByChannel.isNotEmpty || appliedDeletion || coverageChanged) { @@ -384,6 +405,13 @@ extension _UnreadCatchUp on ChannelsNotifier { /// Reads the newest post in each channel's [_activityGap], after the unread /// catch-up and apart from it, so its failure only leaves activity unknown. /// A failed gap is not retried: the next list read's catch-up reads it again. + /// + /// The unread catch-up asks for deletions only after the read marker, so + /// one made in the gap while disconnected, and read past on another + /// device, can still hold the activity head. This also asks for those of + /// the heads: with the posts when they fit in one request, otherwise once + /// the posts have settled, and only for the heads no gap post replaced, so + /// a failed deletion read never costs the posts. Future _catchUpActivityGaps( RelaySessionNotifier session, Map filtersByChannel, @@ -393,39 +421,69 @@ extension _UnreadCatchUp on ChannelsNotifier { int subscriptionGeneration, ) async { final channelIds = filtersByChannel.keys.toSet(); + final heads = { + for (final channelId in channelIds) + channelId: ?_activity.latestId(channelId), + }; + final since = filtersByChannel.values + .map((filter) => filter.since!) + .reduce(min); + final shared = + channelIds.length + heads.length <= kMaxExplicitChannelValues; final failedChannelIds = {}; List? events; + var headDeletions = const []; var authenticIds = const {}; var rejected = const {}; try { - events = await _fetchChannelHistoryBatch( + final read = await _fetchChannelHistoryBatch( session, - filtersByChannel.values.toList(), + [ + ...filtersByChannel.values, + if (shared) ..._headDeletionFilters(heads, since), + ], operation: 'activity gap read', failedChannelIds: failedChannelIds, optional: true, ); - if (events != null) { + if (read != null) { + // A deletion can carry an `h` tag too, so it must not count as a post. + final posts = []; + final deletions = []; + for (final event in read) { + (event.kind == EventKind.deletion || + event.kind == EventKind.nip29DeleteEvent + ? deletions + : posts) + .add(event); + } + events = posts; + headDeletions = deletions; (authentic: authenticIds, :rejected) = await _authenticActivityHeads( events, deletedIds, ); } } catch (error) { + // Unverified, the posts read cannot settle the gaps. + events = null; debugPrint('[ChannelsNotifier] activity gap read failed: $error'); } if (!_lifecycleRef.mounted || _isCatchUpRetired(fence, subscriptionGeneration)) { return; } + final deleted = { + ...deletedIds, + ..._deletedAmong(events), + for (final deletion in headDeletions) ..._deletionTargets(deletion), + }; var changed = false; for (final event in events ?? const []) { final channelId = event.channelId; if (channelId == null || !channelIds.contains(channelId) || - deletedIds.contains(event.id) || - _unscopedUnreadDeletedIds.contains(event.id) || - _unreadDeletedIdsByChannel[channelId]?.contains(event.id) == true) { + deleted.contains(event.id)) { continue; } changed |= _activity.note( @@ -434,15 +492,98 @@ extension _UnreadCatchUp on ChannelsNotifier { (event) => authenticIds.contains(event.id), ); } + // Each gap read asks for one post, so a deleted one hides whether an + // older post in the gap survives. final failed = events == null ? channelIds : { ...failedChannelIds, ...rejected, - ..._deletedHeadChannels(events, authenticIds, deletedIds), + for (final event in events) + if (event.channelId case final channelId? + when deleted.contains(event.id)) + channelId, }; - changed |= _activity.noteCatchUp(channelIds, failed, sentAt: sentAt); + // After the gap's posts, so a head they replaced stays known. + changed |= _activity.forgetHeads(deleted); + // The heads whose deletions are still unread stay unknown until they are. + final unprobed = shared || events == null + ? const {} + : { + for (final MapEntry(key: channelId, value: id) in heads.entries) + if (!failed.contains(channelId) && + _activity.latestId(channelId) == id) + channelId, + }; + changed |= _activity.noteCatchUp( + channelIds.difference(unprobed), + failed, + sentAt: sentAt, + ); if (changed) _publishUnreadCatchUp(const {}); + if (unprobed.isEmpty) return; + + List? probed; + try { + probed = await _fetchChannelHistoryBatch( + session, + _headDeletionFilters({ + for (final channelId in unprobed) channelId: heads[channelId]!, + }, since), + operation: 'activity head deletion read', + optional: true, + ); + } catch (error) { + debugPrint( + '[ChannelsNotifier] activity head deletion read failed: $error', + ); + } + if (!_lifecycleRef.mounted || + _isCatchUpRetired(fence, subscriptionGeneration)) { + return; + } + final forgot = _activity.forgetHeads({ + for (final deletion in probed ?? const []) + ..._deletionTargets(deletion), + }); + if (forgot | + _activity.noteCatchUp( + unprobed, + probed == null ? unprobed : const {}, + sentAt: sentAt, + )) { + _publishUnreadCatchUp(const {}); + } + } + + /// Filters for deletions of each channel's [heads] made since [since], + /// [_headDeletionChannels] channels per filter. + List _headDeletionFilters(Map heads, int since) { + final entries = heads.entries.toList(); + return [ + for ( + var start = 0; + start < entries.length; + start += _headDeletionChannels + ) + NostrFilter( + kinds: const [EventKind.deletion, EventKind.nip29DeleteEvent], + tags: { + '#h': [ + for (final head + in entries.skip(start).take(_headDeletionChannels)) + head.key, + ], + '#e': [ + for (final head + in entries.skip(start).take(_headDeletionChannels)) + head.value, + ], + }, + since: since, + limit: _unreadCatchUpLimit, + ), + ]; } /// [_ChannelActivity.authenticHeadIds] of [events], skipping posts that are @@ -506,10 +647,21 @@ extension _UnreadCatchUp on ChannelsNotifier { return max(afterRead, caughtUp.sentAt - relayCrossDeviceSkewSeconds); } + /// Where [channelId]'s catch-up asks for deletions. When an Active section + /// shows it and its latest post is from the second before [since], as when + /// the read marker sits on that post, the gap read is moot, so a deletion + /// of that post made in the same second is asked for here. + int _deletionsSince(String channelId, int since) => + _activity.isWatched(channelId) && + _activity.latestAt(channelId) == since - 1 + ? since - 1 + : since; + /// The stretch a catch-up starting at [since] skips since the last read /// that covered the channel, for the Active filter: a post that arrived /// while disconnected and was read on another device lies there, as does one - /// before an unread cursor reset. The catch-up asks for its newest post. + /// before an unread cursor reset. The catch-up asks for its newest post, + /// and for deletions of the latest post known made since it began. /// A channel known only from a live post counts as covered at that post. /// Null when nothing covered the channel yet or nothing is skipped. ({int since, int until})? _activityGap(String channelId, int since) { diff --git a/mobile/test/features/channels/channels_provider_test.dart b/mobile/test/features/channels/channels_provider_test.dart index e3aaf5c693..ce2070149f 100644 --- a/mobile/test/features/channels/channels_provider_test.dart +++ b/mobile/test/features/channels/channels_provider_test.dart @@ -2849,11 +2849,23 @@ void main() { recentMessages: [old], enforceHistoryLimits: true, ); + final savedDir = await Directory.systemTemp.createTemp('active-saved'); + addTearDown(() => savedDir.delete(recursive: true)); final container = _buildContainer( session: session, overrides: [ readStateProvider.overrideWith(_ActivityReadState.new), _testPubkeyProvider.overrideWith(_ActivityPubkey.new), + savedMessageScopeProvider.overrideWithValue(( + communityId: 'community', + pubkey: _activityPk, + )), + savedMessageStoreProvider.overrideWith( + (ref) => SavedMessageStore( + root: () async => savedDir, + diagnostics: const NoopDiagnosticReporter(), + ), + ), ], ); addTearDown(container.dispose); @@ -3022,11 +3034,12 @@ void main() { // Deleting the latest post forgets the channel's activity until the next // list read re-reads it. - NostrEvent deletionOf(NostrEvent post) => NostrEvent.fromJson( + NostrEvent deletionOf(NostrEvent post, {int? at}) => NostrEvent.fromJson( signNostrEvent( kind: EventKind.deletion, content: '', secretKey: _activityKey, + createdAt: at, tags: [ ['h', _channelA], ['e', post.id], @@ -3052,6 +3065,131 @@ void main() { await reconnect(); expect(notifier.activityFor(_channelA), (known: true, at: old.createdAt)); + // A gap read answers with its newest post. When the catch-up found that + // post deleted, an older one in the gap may survive, so the channel stays + // unknown. + final kept = message('kept', now - 8); + session.emit(kept); + await _waitUntil( + () => notifier.activityFor(_channelA).at == kept.createdAt, + ); + final older = message('older', now - 7); + final deletedInGap = message('deletedInGap', now - 6); + session.recentMessages = [ + old, + kept, + older, + deletedInGap, + deletionOf(deletedInGap), + ]; + (container.read(readStateProvider.notifier) as _ActivityReadState) + .markReadThrough(_channelA, now - 4); + await reconnect(); + expect(notifier.activityFor(_channelA).known, isFalse); + session.recentMessages = [old, kept, older]; + await reconnect(); + expect(notifier.activityFor(_channelA), (known: true, at: older.createdAt)); + + // So does a gap read whose signature checks fail to run. + final unchecked = message('unchecked', now - 5); + session.recentMessages = [old, kept, older, unchecked]; + final checks = debugRunActivityChecks; + debugRunActivityChecks = (run) async { + final verified = await checks(run); + if (verified.contains(unchecked.id)) throw StateError('checks failed'); + return verified; + }; + try { + await reconnect(); + expect(notifier.activityFor(_channelA).known, isFalse); + } finally { + debugRunActivityChecks = checks; + } + await reconnect(); + expect(notifier.activityFor(_channelA), ( + known: true, + at: unchecked.createdAt, + )); + + // A deletion made while offline counts even when the read marker has + // since moved past it on another device. + final gone2 = message('gone2', now - 4); + session.emit(gone2); + await _waitUntil( + () => notifier.activityFor(_channelA).at == gone2.createdAt, + ); + session.recentMessages = [old, unchecked, deletionOf(gone2, at: now - 3)]; + (container.read(readStateProvider.notifier) as _ActivityReadState) + .markReadThrough(_channelA, now - 2); + await reconnect(); + expect(notifier.activityFor(_channelA).known, isFalse); + session.recentMessages = [old, unchecked]; + await reconnect(); + expect(notifier.activityFor(_channelA), ( + known: true, + at: unchecked.createdAt, + )); + + // A newer post in the gap replaces the deleted one, so the channel stays + // known. + final gone3 = message('gone3', now - 4); + session.emit(gone3); + await _waitUntil( + () => notifier.activityFor(_channelA).at == gone3.createdAt, + ); + final after = message('after', now - 3); + session.recentMessages = [ + old, + unchecked, + after, + deletionOf(gone3, at: now - 3), + ]; + await reconnect(); + expect(notifier.activityFor(_channelA), (known: true, at: after.createdAt)); + + // So does a deletion in the same second as the latest post the read + // marker sits on. + final boundary = message('boundary', now - 1); + session.emit(boundary); + await _waitUntil( + () => notifier.activityFor(_channelA).at == boundary.createdAt, + ); + session.recentMessages = [ + old, + unchecked, + after, + deletionOf(boundary, at: now - 1), + ]; + (container.read(readStateProvider.notifier) as _ActivityReadState) + .markReadThrough(_channelA, now - 1); + // The earlier second it reads only serves the Active head: another post's + // deletion there is not new, so a page being saved meanwhile still is. + final regular = session.recentMessages; + session.recentMessages = [ + old, + unchecked, + after, + deletionOf(older, at: now - 1), + ]; + final store = container.read(savedMessageStoreProvider); + final page = (channelId: _channelA, rootId: ''); + final ticket = store.capture( + container.read(savedMessageScopeProvider)!, + page, + ); + await reconnect(); + expect(store.isCurrent(ticket), isTrue); + expect(notifier.activityFor(_channelA), ( + known: true, + at: boundary.createdAt, + )); + session.recentMessages = regular; + await reconnect(); + expect(notifier.activityFor(_channelA).known, isFalse); + session.recentMessages = [old, unchecked, after]; + await reconnect(); + expect(notifier.activityFor(_channelA), (known: true, at: after.createdAt)); + // A channel no Active section shows skips its gap read, and reads as // unknown until a catch-up while it is shown. shown.close(); @@ -3224,6 +3362,107 @@ void main() { ); } + // Past one request's channel values, the head deletions go out on their + // own after the gap posts; below it, with them. + for (final empty in [0, 2]) { + test('gap posts settle Active activity even when the head deletion read ' + 'fails ($empty channels without a head)', () async { + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final ids = [ + for (var i = 0; i <= kMaxExplicitChannelValues ~/ 2; i++) 'gap-$i', + ]; + final heads = { + for (final id in ids.take(ids.length - empty)) + id: _signedPost(now - 100, channel: id, content: id), + }; + final newer = _signedPost(now - 30, channel: ids[0], content: 'newer'); + final deletion = NostrEvent.fromJson( + signNostrEvent( + kind: EventKind.deletion, + content: '', + secretKey: _activityKey, + createdAt: now - 50, + tags: [ + ['h', ids[1]], + ['e', heads[ids[1]]!.id], + ], + ).toMap(), + ); + final session = _FakeRelaySession( + memberships: [for (final id in ids) _membership(id, _activityPk)], + metadata: [for (final id in ids) _meta(id: id, name: id)], + recentMessages: heads.values.toList(), + enforceHistoryLimits: true, + ); + final container = _buildContainer( + session: session, + overrides: [ + readStateProvider.overrideWith(_ActivityReadState.new), + _testPubkeyProvider.overrideWith(_ActivityPubkey.new), + ], + ); + addTearDown(container.dispose); + await container.read(channelsProvider.future); + final notifier = container.read(channelsProvider.notifier); + await notifier.waitForUnreadCatchUp(); + for (final id in ids) { + final shown = container.listen( + channelFilterActivityProvider(id), + (_, _) {}, + ); + addTearDown(shown.close); + } + Future reconnect() async { + final batches = session.queryBatches.length; + session.setStatus(SessionStatus.reconnecting); + session.setStatus(SessionStatus.connected); + await _waitUntil( + () => session.queryBatches + .skip(batches) + .any((batch) => batch.every((filter) => filter.since != null)), + ); + await notifier.waitForUnreadCatchUp(); + await _settle(); + } + + // Read on another device while disconnected, so every channel has a gap. + session.recentMessages = [...heads.values, newer, deletion]; + for (final id in ids) { + (container.read(readStateProvider.notifier) as _ActivityReadState) + .markReadThrough(id, now - 15); + } + session.headDeletionBatchError = RelayException( + 503, + '{"error":"query timed out"}', + ); + final before = session.queryBatches.length; + await reconnect(); + expect( + session.queryBatches + .skip(before) + .where( + (batch) => + _isGapBatch(batch) || + batch.every((filter) => filter.tags.containsKey('#e')), + ), + hasLength(empty == 0 ? 2 : 1), + ); + expect(notifier.activityFor(ids[0]), (known: true, at: newer.createdAt)); + expect(notifier.activityFor(ids[1]).known, isFalse); + // Only a separate deletion read can fail on its own. + expect(notifier.activityFor(ids[2]).known, empty > 0); + + // Once the deletions are read, only the deleted head stays unknown. + session.headDeletionBatchError = null; + await reconnect(); + expect(notifier.activityFor(ids[1]).known, isFalse); + expect(notifier.activityFor(ids[2]), ( + known: true, + at: heads[ids[2]]!.createdAt, + )); + }); + } + test('live channel events update channel lastMessageAt', () async { final session = _FakeRelaySession( memberships: [_membership(_channelA, myPk)], @@ -4697,8 +4936,7 @@ NostrEvent _signedPost( ); bool _isGapBatch(List batch) => - batch.isNotEmpty && - batch.every((filter) => filter.until != null && filter.limit == 1); + batch.any((filter) => filter.until != null && filter.limit == 1); /// Drains pending microtasks so provider rebuilds and awaited writes land. Future _settle() async { @@ -4787,6 +5025,8 @@ class _FakeRelaySession extends RelaySessionNotifier { Object? messageBatchError; // Fails batches made only of the catch-up's activity gap reads. Object? gapBatchError; + // Fails a batch that only reads deletions of given posts. + Object? headDeletionBatchError; // Holds the next batch of activity gap reads. Completer? gapBatchGate; Object? latestBatchError; @@ -5180,8 +5420,16 @@ class _FakeRelaySession extends RelaySessionNotifier { throw RelayException(400, '{"error":"too many explicit channels"}'); } if (messageBatchError case final error?) throw error; - if (filters.isNotEmpty && - filters.every((f) => f.until != null && f.limit == 1)) { + if (headDeletionBatchError case final error? + when filters.isNotEmpty && + filters.every( + (filter) => + filter.tags.containsKey('#e') && + filter.kinds.contains(EventKind.deletion), + )) { + throw error; + } + if (_isGapBatch(filters)) { if (gapBatchError case final error?) throw error; final gate = gapBatchGate; gapBatchGate = null;