Skip to content

Commit a79cbb4

Browse files
matt2eclaude
andauthored
perf(mobile): stop re-scanning the unread backlog on channel list rebuilds (#9780)
## Summary Scrolling the mobile channel list hitched repeatedly after the app had been closed for a long time. To decide which rows are bold and which get a dot, the channel list read every unread message held in memory, for every channel, on every rebuild. After a long absence the unread catch-up holds up to 1000 messages per channel, so each list update cost more than a frame. This change makes a list rebuild independent of the backlog size: - A channel's messages stop being read once its bold and dot state is decided. - Each channel's result is reused until its messages or the read state change. A new message re-reads only its own channel; reordering or filtering the list re-reads nothing. Which rows end up bold or dotted is unchanged. ### Related issue N/A. None found. ### Testing Before (left) and after (right), same script on an iPhone 17 simulator: 200 channels each holding 1000 unread messages, a list update every 150 ms, and a scripted finger (the crosshair) dragging at a steady 420 px per second. https://github.com/user-attachments/assets/07b39b61-406f-4b4b-baca-69aa5be42db7 | | Before | After | |---|---|---| | Frames drawn in the 11-second drag | 279 | 499 | | Frames over 25 ms | 127 (46%) | 92 (18%) | | Median frame | 21.1 ms | 17.2 ms | | Worst frame | 116.8 ms | 65.2 ms | The recording uses scripted data in a debug build, which drops some frames even with no list updates, so the "after" side is not perfectly smooth. Whole frame after one list update, 200 channels, in a widget test on a Mac (not a phone): | Unread messages held per channel | Before | After | |---|---|---| | 0 | 13.3 ms | 12.7 ms | | 300 | 16.5 ms | 6.8 ms | | 1000 | 37.4 ms | 6.6 ms | - New tests in `channel_unread_test.dart` compare the new pass with a copy of the old full scan across a table of cases and 600 random steps of adds, deletions and read marks, and count messages read to guard the early exit and the reuse without timing. - `flutter analyze` and the mobile channel and home tests (2,983) passed with these two commits on `8827f986e43`. They were not rerun after the rebase onto current `main`, so CI is the check for that. - Not run on a phone or against a real community. Worth a close look in review: the reuse depends on every place that changes the stored unread messages marking that channel as changed. The new tests drive this through a stand-in, so they do not prove each real call site does it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <mtoohey@squareup.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent ee4a6ed commit a79cbb4

9 files changed

Lines changed: 703 additions & 37 deletions

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
687687
!_isBroadcastReply(event);
688688
final isHighPriority =
689689
channel.isDm || (!countQuiet && isHighPriorityEvent(event.tags, myPk));
690-
recordObservedUnreadEvent(
690+
final inserted = recordObservedUnreadEvent(
691691
_observedUnreadEventsByChannel,
692692
channel.id,
693693
makeObservedUnreadEvent(
@@ -702,6 +702,10 @@ extension _ObservedUnreadRecording on ChannelsNotifier {
702702
_unreadCatchUpLimit,
703703
);
704704

705+
// Refresh and reconnect replay history the registry already holds. Only
706+
// an insertion changes the channel's events, so only it stamps them.
707+
if (inserted) _observedUnreadRevisions.touch(channel.id);
708+
705709
final current = _latestObservedByChannel[channel.id] ?? 0;
706710
if (event.createdAt > current) {
707711
_latestObservedByChannel[channel.id] = event.createdAt;

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,14 @@ extension _ChannelThreadFollows on ChannelsNotifier {
6666
for (final MapEntry(key: channelId, value: events)
6767
in _observedUnreadEventsByChannel.entries) {
6868
if (dmIds.contains(channelId)) continue;
69+
final before = events.length;
6970
events.removeWhere(
7071
(_, event) =>
7172
!event.highPriority &&
7273
event.rootId != null &&
7374
unfollowed.contains(event.rootId),
7475
);
76+
if (events.length != before) _observedUnreadRevisions.touch(channelId);
7577
}
7678
if (widened.isNotEmpty) {
7779
// Only the widened threads' channels catch up again; a root whose

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

Lines changed: 123 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -57,43 +57,137 @@ _computeHighlights({
5757
final latestObservedByChannel = channelsNotifier.latestObservedByChannel;
5858
final observedEventsByChannel =
5959
channelsNotifier.observedUnreadEventsByChannel;
60+
// Lists rebuild far more often than unread evidence changes, and a backlog
61+
// can hold a thousand events per channel: reuse each channel's outcome
62+
// until its events or the read state change.
63+
final revisionOf = observedEventsByChannel is ObservedUnreadSnapshot
64+
? observedEventsByChannel.revisionOf
65+
: null;
66+
final memo = revisionOf == null
67+
? null
68+
: (_memos[channelsNotifier] ??= _HighlightMemo()).entriesFor(
69+
readState,
70+
separateAttention: separateAttention,
71+
);
6072

6173
for (final channel in channels) {
62-
if (forcedChannelIds.contains(channel.id)) {
63-
unread.add(channel.id);
64-
if (separateAttention) rowUnread.add(channel.id);
74+
final latestObserved = latestObservedByChannel[channel.id];
75+
final revision = revisionOf?.call(channel.id);
76+
final cached = memo?[channel.id];
77+
final int flags;
78+
if (cached != null &&
79+
cached.revision == revision &&
80+
cached.latestObserved == latestObserved &&
81+
cached.isDm == channel.isDm) {
82+
flags = cached.flags;
83+
} else {
84+
flags = _channelHighlights(
85+
channel: channel,
86+
readState: readState,
87+
forced: forcedChannelIds.contains(channel.id),
88+
latestObserved: latestObserved,
89+
observedEvents: observedEventsByChannel[channel.id],
90+
separateAttention: separateAttention,
91+
);
92+
if (memo != null && revision != null) {
93+
memo[channel.id] = (
94+
revision: revision,
95+
latestObserved: latestObserved,
96+
isDm: channel.isDm,
97+
flags: flags,
98+
);
99+
}
65100
}
101+
if (flags & _unread != 0) unread.add(channel.id);
102+
if (flags & _rowUnread != 0) rowUnread.add(channel.id);
103+
if (flags & _attention != 0) attention.add(channel.id);
104+
}
66105

67-
final latestObserved = latestObservedByChannel[channel.id];
68-
if (latestObserved == null) continue;
106+
return highlights;
107+
}
69108

70-
final channelReadAt = readState.effectiveTimestamp(channel.id);
71-
if (channelReadAt != null && latestObserved <= channelReadAt) continue;
109+
const _unread = 1;
110+
const _rowUnread = 2;
111+
const _attention = 4;
72112

73-
final observedEvents = observedEventsByChannel[channel.id];
74-
if (observedEvents == null) continue;
75-
final seenAt = separateAttention
76-
? readState.contexts['seen:${channel.id}']
77-
: null;
78-
for (final event in observedEvents.values) {
79-
final readAt = observedUnreadEventReadAt(
80-
event,
81-
channel.id,
82-
readState.effectiveTimestamp,
83-
);
84-
if (readAt != null && event.createdAt <= readAt) continue;
85-
if (!separateAttention || channel.isDm || event.channelCatchUp) {
86-
unread.add(channel.id);
87-
if (separateAttention &&
88-
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
89-
rowUnread.add(channel.id);
90-
}
91-
}
92-
if (separateAttention && (channel.isDm || !event.channelCatchUp)) {
93-
attention.add(channel.id);
113+
/// One channel's highlight flags. Stops reading events once no later event
114+
/// could change the outcome.
115+
int _channelHighlights({
116+
required Channel channel,
117+
required ReadStateState readState,
118+
required bool forced,
119+
required int? latestObserved,
120+
required Map<String, ObservedUnreadEvent>? observedEvents,
121+
required bool separateAttention,
122+
}) {
123+
var flags = 0;
124+
if (forced) {
125+
flags |= _unread;
126+
if (separateAttention) flags |= _rowUnread;
127+
}
128+
// Every flag an event could still set. Without separate attention only
129+
// `unread` exists; a DM's first unread event sets all three at once.
130+
final decided = separateAttention
131+
? _unread | _rowUnread | _attention
132+
: _unread;
133+
if (flags == decided) return flags;
134+
135+
if (latestObserved == null) return flags;
136+
final channelReadAt = readState.effectiveTimestamp(channel.id);
137+
if (channelReadAt != null && latestObserved <= channelReadAt) return flags;
138+
if (observedEvents == null) return flags;
139+
140+
final seenAt = separateAttention
141+
? readState.contexts['seen:${channel.id}']
142+
: null;
143+
for (final event in observedEvents.values) {
144+
final readAt = observedUnreadEventReadAt(
145+
event,
146+
channel.id,
147+
readState.effectiveTimestamp,
148+
);
149+
if (readAt != null && event.createdAt <= readAt) continue;
150+
if (!separateAttention || channel.isDm || event.channelCatchUp) {
151+
flags |= _unread;
152+
if (separateAttention &&
153+
(channel.isDm || seenAt == null || event.createdAt > seenAt)) {
154+
flags |= _rowUnread;
94155
}
95156
}
157+
if (separateAttention && (channel.isDm || !event.channelCatchUp)) {
158+
flags |= _attention;
159+
}
160+
if (flags == decided) break;
96161
}
162+
return flags;
163+
}
97164

98-
return highlights;
165+
typedef _MemoEntry = ({
166+
int revision,
167+
int? latestObserved,
168+
bool isDm,
169+
int flags,
170+
});
171+
172+
/// Per-notifier memo, so it ends with the notifier's community and identity.
173+
final _memos = Expando<_HighlightMemo>();
174+
175+
/// Channel outcomes for one read state, per `separateAttention` mode. Read
176+
/// state is immutable and replaced on every change, so identity is the key.
177+
class _HighlightMemo {
178+
ReadStateState? _readState;
179+
final _combined = <String, _MemoEntry>{};
180+
final _separate = <String, _MemoEntry>{};
181+
182+
Map<String, _MemoEntry> entriesFor(
183+
ReadStateState readState, {
184+
required bool separateAttention,
185+
}) {
186+
if (!identical(_readState, readState)) {
187+
_readState = readState;
188+
_combined.clear();
189+
_separate.clear();
190+
}
191+
return separateAttention ? _separate : _combined;
192+
}
99193
}

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ extension _UnreadDeletions on ChannelsNotifier {
3535
// The deleted event may have been the marker standing in for a full
3636
// window of quiet messages, which can hide older unread ones. Read the
3737
// channel's whole window again rather than only since the last read.
38-
if (observed?.length != before) _unreadCaughtUpByChannel.remove(id);
38+
if (observed?.length != before) {
39+
_unreadCaughtUpByChannel.remove(id);
40+
_observedUnreadRevisions.touch(id);
41+
}
3942
if (observed == null || observed.isEmpty) {
4043
_observedUnreadEventsByChannel.remove(id);
4144
_latestObservedByChannel.remove(id);

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import 'dart:async';
2+
import 'dart:collection';
23
import 'dart:convert';
34
import 'dart:math';
45

@@ -117,6 +118,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
117118
_unreadCaughtUpByChannel = {};
118119
final Map<String, Map<String, ObservedUnreadEvent>>
119120
_observedUnreadEventsByChannel = {};
121+
// Touched wherever the two maps above change; highlights memoize on it.
122+
final _observedUnreadRevisions = ObservedUnreadRevisions();
120123
final Map<String, Set<String>> _unreadDeletedIdsByChannel = {};
121124
final Set<String> _unscopedUnreadDeletedIds = {};
122125
Set<String> _participatedRootIds = {};
@@ -214,11 +217,10 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
214217
}
215218

216219
Map<String, Map<String, ObservedUnreadEvent>>
217-
get observedUnreadEventsByChannel =>
218-
Map<String, Map<String, ObservedUnreadEvent>>.unmodifiable({
219-
for (final entry in _observedUnreadEventsByChannel.entries)
220-
entry.key: Map<String, ObservedUnreadEvent>.unmodifiable(entry.value),
221-
});
220+
get observedUnreadEventsByChannel => ObservedUnreadSnapshot({
221+
for (final entry in _observedUnreadEventsByChannel.entries)
222+
entry.key: UnmodifiableMapView(entry.value),
223+
}, _observedUnreadRevisions.of);
222224

223225
@override
224226
Future<List<Channel>> build() async {
@@ -331,6 +333,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
331333
_latestObservedByChannel.clear();
332334
_activityRevisions.clear();
333335
_observedUnreadEventsByChannel.clear();
336+
_observedUnreadRevisions.touchAll();
334337
_unreadCaughtUpByChannel.clear();
335338
_unreadDeletedIdsByChannel.clear();
336339
_unscopedUnreadDeletedIds.clear();
@@ -993,7 +996,9 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
993996
void clearObservedUnreadForChannel(String channelId) {
994997
_latestObservedByChannel.remove(channelId);
995998
_activityRevisions.remove(channelId);
996-
_observedUnreadEventsByChannel.remove(channelId);
999+
if (_observedUnreadEventsByChannel.remove(channelId) != null) {
1000+
_observedUnreadRevisions.touch(channelId);
1001+
}
9971002
state = state.whenData((channels) => List<Channel>.of(channels));
9981003
}
9991004

‎mobile/lib/features/channels/unread_badge/observed_unread_event.dart‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:collection';
2+
13
import '../../../shared/read_state/read_state_format.dart';
24
import '../../../shared/relay/nostr_models.dart';
35

@@ -28,6 +30,36 @@ class ObservedUnreadEvent {
2830
});
2931
}
3032

33+
/// Per-channel change stamps for the observed unread registry. Every add,
34+
/// eviction, deletion or clear of a channel's events must [touch] it, so
35+
/// readers can reuse work derived from an unchanged channel.
36+
class ObservedUnreadRevisions {
37+
int _next = 0;
38+
int _floor = 0;
39+
final Map<String, int> _byChannel = {};
40+
41+
/// Changes whenever [channelId]'s observed events may have changed.
42+
int of(String channelId) => _byChannel[channelId] ?? _floor;
43+
44+
void touch(String channelId) => _byChannel[channelId] = ++_next;
45+
46+
void touchAll() {
47+
_byChannel.clear();
48+
_floor = ++_next;
49+
}
50+
}
51+
52+
/// Observed unread events by channel, with the stamp that says when a
53+
/// channel's events last changed. Only a view carrying stamps may be
54+
/// memoized against; a plain map is always read in full.
55+
class ObservedUnreadSnapshot
56+
extends UnmodifiableMapView<String, Map<String, ObservedUnreadEvent>> {
57+
ObservedUnreadSnapshot(super.map, this.revisionOf);
58+
59+
/// See [ObservedUnreadRevisions.of].
60+
final int Function(String channelId) revisionOf;
61+
}
62+
3163
ObservedUnreadEvent makeObservedUnreadEvent({
3264
required String id,
3365
required int createdAt,

0 commit comments

Comments
 (0)