Skip to content

Commit 8f6e19f

Browse files
committed
perf(mobile): avoid sorting live channel windows twice
Signed-off-by: Tom Brow <[email protected]>
1 parent 4cd82f5 commit 8f6e19f

4 files changed

Lines changed: 238 additions & 3 deletions

File tree

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,12 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
229229

230230
void _handleWindowLiveEvent(NostrEvent event) {
231231
if (!_mergeWindowEventIntoStore(event)) return;
232-
final flattened = _withDeepLinkEvents(
233-
flattenChannelWindowEvents(_windowStore),
234-
);
232+
final windowEvents = flattenChannelWindowEvents(_windowStore);
233+
// Flattening already orders the window. Only merge and sort again when
234+
// there are retained deep-link events to include.
235+
final flattened = _deepLinkEvents.isEmpty
236+
? windowEvents
237+
: _withDeepLinkEvents(windowEvents);
235238
_lastKnownMessages = flattened;
236239
state = AsyncData(flattened);
237240
}

‎mobile/test/benchmark/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Mobile performance diagnostics
2+
3+
With the repository's Hermit environment active, run from `mobile/`:
4+
5+
```sh
6+
flutter test --dart-define=BUZZ_RUN_BENCHMARKS=true test/benchmark/channel_live_burst_test.dart
7+
```
8+
9+
The diagnostic is skipped by default. It does not use a relay, credentials, or
10+
community content.
11+
12+
The buffered-channel diagnostic sends synthetic events through the real
13+
`RelaySessionNotifier` event buffer and `ChannelMessagesNotifier` live callback.
14+
Only connection state and history responses are replaced. It measures one
15+
synchronous flush and a zero-delay timer queued just before that flush. The timer
16+
shows how long other event-loop work waits behind the consumer callbacks.
17+
18+
It varies retained history (50, 500, 2000 events) and live burst size (50, 200,
19+
1000 events). Each case warms up twice before emitting four JSON measurement
20+
records in microseconds. Compare medians on the same host under similar load.
21+
No wall-clock threshold is asserted because debug/JIT compilation and host load
22+
make it unsuitable for a stable CI performance gate. Final event counts are
23+
asserted to ensure the measured work actually completes.
24+
25+
This is a bounded stress diagnostic, not a representative release benchmark.
26+
Retained history is modeled as one synthetic page instead of real pagination.
27+
It excludes widgets, media, network traffic, signature verification, and other
28+
subscriptions. It can identify synchronous consumer costs, but cannot establish
29+
that a measured burst occurred in a real community or predict release frame
30+
latency.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
// Opt-in synthetic diagnostic; see README.md for invocation and limitations.
2+
import 'dart:async';
3+
import 'dart:convert';
4+
5+
import 'package:buzz/features/channels/channel_messages_provider.dart';
6+
import 'package:buzz/shared/relay/relay.dart';
7+
import 'package:flutter/foundation.dart';
8+
import 'package:flutter_test/flutter_test.dart';
9+
import 'package:hooks_riverpod/hooks_riverpod.dart';
10+
11+
void main() {
12+
test(
13+
'buffered live channel delivery',
14+
() async {
15+
for (final historySize in [50, 500, 2000]) {
16+
for (final burstSize in [50, 200, 1000]) {
17+
// Discard the first two runs to reduce debug/JIT warm-up effects.
18+
for (var run = 0; run < 6; run++) {
19+
await _measureBurst(historySize, burstSize, run);
20+
}
21+
}
22+
}
23+
},
24+
skip: !const bool.fromEnvironment('BUZZ_RUN_BENCHMARKS'),
25+
timeout: const Timeout(Duration(minutes: 3)),
26+
);
27+
}
28+
29+
Future<void> _measureBurst(int historySize, int burstSize, int run) async {
30+
final session = _SyntheticSession(historySize);
31+
final container = ProviderContainer(
32+
overrides: [relaySessionProvider.overrideWith(() => session)],
33+
);
34+
try {
35+
final loaded = Completer<void>();
36+
container.listen(channelMessagesProvider(_channelId), (_, next) {
37+
if (!loaded.isCompleted && next.value?.length == historySize) {
38+
loaded.complete();
39+
}
40+
});
41+
await loaded.future.timeout(const Duration(seconds: 5));
42+
43+
for (var index = 0; index < burstSize; index++) {
44+
session.debugHandleMessage([
45+
'EVENT',
46+
'l-1',
47+
_event('live-$index', historySize + index).toJson(),
48+
]);
49+
}
50+
final tick = Completer<int>();
51+
final watch = Stopwatch()..start();
52+
Timer.run(() => tick.complete(watch.elapsedMicroseconds));
53+
session.debugFlushEventBuffer();
54+
final synchronousUs = watch.elapsedMicroseconds;
55+
final eventLoopDelayUs = await tick.future;
56+
57+
expect(
58+
container.read(channelMessagesProvider(_channelId)).value!.length,
59+
historySize + burstSize,
60+
);
61+
if (run >= 2) {
62+
debugPrint(
63+
jsonEncode({
64+
'history': historySize,
65+
'burst': burstSize,
66+
'run': run - 2,
67+
'synchronous_us': synchronousUs,
68+
'event_loop_delay_us': eventLoopDelayUs,
69+
}),
70+
);
71+
}
72+
} finally {
73+
container.dispose();
74+
// The original 16 ms buffer timer remains armed after a debug flush.
75+
await Future<void>.delayed(const Duration(milliseconds: 20));
76+
}
77+
}
78+
79+
const _channelId = '11111111-1111-4111-8111-111111111111';
80+
81+
NostrEvent _event(String id, int createdAt) => NostrEvent(
82+
id: id,
83+
pubkey: 'synthetic-author',
84+
createdAt: createdAt,
85+
kind: EventKind.streamMessageV2,
86+
tags: const [
87+
['h', _channelId],
88+
],
89+
content: 'Synthetic message',
90+
sig: 'synthetic-signature',
91+
);
92+
93+
class _SyntheticSession extends RelaySessionNotifier {
94+
final int historySize;
95+
96+
_SyntheticSession(this.historySize);
97+
98+
@override
99+
SessionState build() => const SessionState(status: SessionStatus.connected);
100+
101+
@override
102+
Future<void Function()> subscribe(
103+
NostrFilter filter,
104+
void Function(NostrEvent) onEvent, {
105+
void Function(String message)? onClosed,
106+
}) {
107+
// Preserve the real subscription and buffer delivery implementation. This
108+
// fixture creates exactly one subscription, whose generated id is l-1.
109+
final ready = super.subscribe(filter, onEvent, onClosed: onClosed);
110+
debugHandleMessage(['EOSE', 'l-1']);
111+
return ready;
112+
}
113+
114+
@override
115+
Future<List<NostrEvent>> queryRelay(
116+
List<NostrFilter> filters, {
117+
Duration timeout = const Duration(seconds: 8),
118+
}) async => [
119+
// Model retained history in one synthetic page; real windows page by 50.
120+
for (var index = historySize - 1; index >= 0; index--)
121+
_event('history-$index', index),
122+
NostrEvent(
123+
id: 'bounds',
124+
pubkey: 'synthetic-relay',
125+
createdAt: 0,
126+
kind: EventKind.channelWindowBounds,
127+
tags: const [
128+
['d', '$_channelId:head'],
129+
],
130+
content: jsonEncode({'has_more': false, 'next_cursor': null}),
131+
sig: 'synthetic-signature',
132+
),
133+
];
134+
}

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,74 @@ import 'package:buzz/features/channels/timeline_message.dart';
1111
import 'package:buzz/shared/relay/relay.dart';
1212

1313
void main() {
14+
for (final retainDeepLink in [false, true]) {
15+
test(
16+
'live window keeps chronological order with retained deep link: $retainDeepLink',
17+
() async {
18+
final relaySession = _RecordingRelaySessionNotifier(
19+
queryResults: [
20+
[
21+
_event(id: 'newer-history', createdAt: 20),
22+
_event(id: 'older-history', createdAt: 10),
23+
_bounds(),
24+
],
25+
],
26+
);
27+
final container = _buildContainer(relaySession);
28+
addTearDown(container.dispose);
29+
container.read(channelMessagesProvider(_channelId));
30+
await relaySession.subscribed;
31+
await _pumpEventQueue();
32+
final notifier = container.read(
33+
channelMessagesProvider(_channelId).notifier,
34+
);
35+
if (retainDeepLink) {
36+
final load = notifier.loadEventsById(['deep-link']);
37+
relaySession.completeTargetHistory([
38+
_event(id: 'deep-link', createdAt: 5),
39+
]);
40+
await load;
41+
}
42+
43+
// Older live rows must insert in order, including the descending-id
44+
// tie-break within a second, on both sides of the deep-link fast path.
45+
relaySession.emit(_event(id: 'a-live', createdAt: 15));
46+
relaySession.emit(_event(id: 'z-live', createdAt: 15));
47+
expect(
48+
container
49+
.read(channelMessagesProvider(_channelId))
50+
.value!
51+
.map((event) => event.id),
52+
[
53+
if (retainDeepLink) 'deep-link',
54+
'older-history',
55+
'z-live',
56+
'a-live',
57+
'newer-history',
58+
],
59+
);
60+
61+
if (retainDeepLink) {
62+
notifier.releaseDeepLinkEvents(['deep-link']);
63+
relaySession.emit(_event(id: 'newest-live', createdAt: 30));
64+
expect(
65+
container
66+
.read(channelMessagesProvider(_channelId))
67+
.value!
68+
.map((event) => event.id),
69+
[
70+
'older-history',
71+
'z-live',
72+
'a-live',
73+
'newer-history',
74+
'newest-live',
75+
],
76+
);
77+
}
78+
},
79+
);
80+
}
81+
1482
test(
1583
'keeps live events that arrive while initial history is loading',
1684
() async {

0 commit comments

Comments
 (0)