Files
buzz/mobile/test/features/profile/presence_shell_test.dart
Tom Brow 02535e1b53 perf(mobile): stop replaying stored read state on every resume (#9090)
Every time the mobile app reconnects (for example after more than 5
seconds in the background), the read-state live subscription asked the
relay for up to 500 stored read-state events. That re-downloaded every
read-state slot on the account, then the snapshot fetched the same
events again right after. On a heavy account (28 slots) that replay
alone was about 1.4 MB per resume.

The live subscription now uses `limit: 0`, so it only delivers changes.
It still opens before the snapshot, so the snapshot covers anything
published in between.

The subscription can also go live after `subscribe` has returned: on a
cold start with slow AUTH, `subscribe` returns on its 500 ms fallback
before the REQ is registered, after a transient CLOSED (rate limit,
capacity) the session reopens it on the same socket, and a reconnect
replays it. With `limit: 0` nothing replays marks published in that gap,
so the manager reads the snapshot every time the subscription reports
ready, as the channel list's `limit: 0` subscription already does.

The session keeps live subscriptions across reconnects and replays them
on the new socket, so a reconnect no longer resubscribes: the replay's
ready reads the snapshot, once per reconnect. The manager opens a new
subscription only after losing one (a terminal CLOSED or a failed
subscribe), on the next reconnect.

All snapshot reads outside a publish go through one sync loop.
Initialize and each ready ask that loop for a snapshot. A request made
before the current pass starts its read joins that read, and a request
made during the read runs one more pass, so a ready can't be swallowed
by a read already in flight. This needs no generation or
ready-transition checks, at the cost of an occasional extra read (for
example a cold start whose ready lands after the 500 ms fallback, when
the first read has already started).

Snapshot reads are numbered in start order, including a publish's own
read, and only a read newer than every settled one decides whether the
last snapshot succeeded. An older read finishing late cannot clear the
retry a newer failed read needs. A failed read waits for the next
trigger: the publish it schedules, which reads the snapshot in full
after a failure, or a later ready, resume or reconnect.

A publish with nothing to send skips its snapshot ([#9093 skip redundant
publish](https://github.com/block/buzz/pull/9093)) only when the last
snapshot succeeded, so after a failed resume snapshot the next publish
still retries it. A publish snapshot now notifies readers of the marks
it merged, since unchanged slots publish nothing whose echo would.

### Accepted gap

If the snapshot fails (timeout, discovery or HTTP error) on a device
with no local journal, read state stays local until the next successful
snapshot, which every resume, reconnect, subscription recovery and
publish retries. Falling back to a stored replay on failure would close
the gap, but it adds a late subscription path for a rare failure that
already heals on its own.

### Validation

- Added test: `live subscription replays nothing and opens before the
snapshot`. It fails without the change (`limit` 500).
- Added test: `a clean reconnect through the real session replays one
REQ and reads the snapshot once, and a lost subscription is reopened`
drives the real `RelaySessionNotifier` with a recording socket: the
connected listener runs, then the session's replay, then EOSE. It fails
against the previous revision of this PR (two `l-2` REQs and two
snapshot reads per reconnect). After a terminal CLOSED, the next
reconnect opens a new subscription and reads the snapshot.
- Added test: `readies during a held snapshot read share one more read`.
- Added test: `a mark published while the live subscription retries is
read once it recovers` puts the subscription into retry, lets another
device publish a mark, then reports it ready. It fails without the read
on ready.
- Added test: `a failed late-ready read is retried by the next publish`.
It fails without the retry.
- Added test: `a reconnect while the first snapshot downloads is not
swallowed by the cold-start connect` lets the cold-start connect queue
behind initialize, then reconnects while the first read is still
downloading and has a peer publish a mark. It fails against the previous
revision of this PR (the queued pass swallowed the reconnect) and passes
with the sync loop.
- Added test: `an older snapshot finishing late keeps a newer failed
read's retry` holds a publish's snapshot read, fails a newer read, then
lets the older one finish. It fails against the previous revision of
this PR (the older success cleared the retry) and passes with the read
ordering.
- Added test: `a mark published before a slow cold-start REQ goes live
is read then` lets `subscribe` return before ready, publishes a mark,
then reports ready. It fails without the read on ready.
- `a publish after a failed snapshot retries it, then skips again`
replaces the earlier skipped-publish test and fails without the snapshot
check. It also checks that the retried snapshot's new marks notify
readers, which fails without the notify.
- Read-state suite (95 tests), `flutter analyze` and the full mobile
suite pass.
- iPhone 12 mini, Profile build with [#9089 gzip
snapshot](https://github.com/block/buzz/pull/9089) applied, Home
backgrounded 12 s and resumed, websocket bytes received in the 15 s
after resume:

| | Websocket in | Read-state replay |
| --- | --- | --- |
| Before (gzip fix only) | 2,087 KB | 1,458 KB (28 events) |
| After (gzip fix + this) | 575 KB | none |

The table counts websocket bytes only. Each resume reads the read-state
snapshot once over HTTP, before and after this change.

Automated app run on the same phone: Home, a large channel and search
resumed after the reconnect grace period, with no read-state errors
logged. Read marks were not compared across devices.

🤖 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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:09:18 -07:00

128 lines
3.7 KiB
Dart

import 'package:buzz/app.dart';
import 'package:buzz/features/age_gate/age_signal_provider.dart';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/shared/auth/auth.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
void main() {
testWidgets('signed-in shell publishes presence without opening Settings', (
tester,
) async {
final keys = nostr.Keys.generate();
final session = _PublishingSession();
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final container = ProviderContainer(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
authProvider.overrideWith(_SignedIn.new),
ageSignalProvider.overrideWith(_Allowed.new),
relayConfigProvider.overrideWith(() => _Config(keys.nsec)),
myPubkeyProvider.overrideWithValue(keys.public),
appLifecycleProvider.overrideWith(_Resumed.new),
relaySessionProvider.overrideWith(() => session),
channelsProvider.overrideWith(_NoChannels.new),
],
);
addTearDown(container.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(container: container, child: const App()),
);
for (var i = 0; i < 20 && session.presence.isEmpty; i++) {
await tester.pump();
}
expect(session.presence, ['online']);
await tester.pumpWidget(const SizedBox.shrink());
container.dispose();
});
}
class _PublishingSession extends RelaySessionNotifier {
final presence = <String>[];
@override
SessionState build() => const SessionState(status: SessionStatus.connected);
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async => const [];
@override
Future<List<NostrEvent>> queryRelay(
List<NostrFilter> filters, {
Duration timeout = const Duration(seconds: 8),
}) async => const [];
@override
Future<void Function()> subscribe(
NostrFilter filter,
void Function(NostrEvent) onEvent, {
void Function(String message)? onClosed,
}) async => () {};
@override
Future<void Function()> subscribeWithStatus(
NostrFilter filter,
void Function(NostrEvent) onEvent, {
void Function(String message)? onClosed,
required void Function(RelaySubscriptionStatus status) onStatusChanged,
bool resumeSince = true,
}) async => () {};
@override
Future<NostrEvent> publish(
NostrEvent event, {
Duration timeout = const Duration(seconds: 8),
}) async {
if (event.kind == EventKind.presenceUpdate) presence.add(event.content);
return event;
}
}
class _SignedIn extends AuthNotifier {
@override
Future<AuthState> build() async =>
const AuthState(status: AuthStatus.authenticated);
}
class _Allowed extends AgeSignalNotifier {
@override
AgeSignalState build() => AgeSignalState.allowed;
@override
Future<void> request() async {}
}
class _Config extends RelayConfigNotifier {
_Config(this.nsec);
final String nsec;
@override
RelayConfig build() =>
RelayConfig(baseUrl: 'https://relay.example', nsec: nsec);
}
class _Resumed extends AppLifecycleNotifier {
@override
AppLifecycleState build() => AppLifecycleState.resumed;
}
class _NoChannels extends ChannelsNotifier {
@override
bool get hasLoaded => true;
@override
Future<List<Channel>> build() async => const [];
}