mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
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>
205 lines
7.0 KiB
Dart
205 lines
7.0 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:buzz/features/profile/presence_cache_provider.dart';
|
|
import 'package:buzz/shared/relay/relay.dart';
|
|
import 'package:fake_async/fake_async.dart';
|
|
import 'package:flutter/widgets.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
void main() {
|
|
void scenario(void Function(FakeAsync, ProviderContainer, _Relay) run) {
|
|
fakeAsync((time) {
|
|
final relay = _Relay();
|
|
final container = ProviderContainer(
|
|
overrides: [
|
|
relaySessionProvider.overrideWith(() => relay),
|
|
appLifecycleProvider.overrideWith(_Lifecycle.new),
|
|
],
|
|
);
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
time.elapse(Duration.zero);
|
|
try {
|
|
run(time, container, relay);
|
|
} finally {
|
|
container.dispose();
|
|
time.flushMicrotasks();
|
|
}
|
|
});
|
|
}
|
|
|
|
test('delayed pre-snapshot live event cannot regress a settled snapshot', () {
|
|
scenario((time, container, relay) {
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 20),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
// Delivered after the snapshot settled but signed ten seconds before
|
|
// the relay observed it: the observation already folded it in.
|
|
relay.emit(_event('alice', 'offline', timestamp: 10));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
time.elapse(Duration.zero);
|
|
expect(relay.queries, hasLength(2));
|
|
expect(relay.queries.last.authors, ['alice']);
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 22),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
});
|
|
});
|
|
|
|
test('live event from a lagging signer clock is confirmed, not dropped', () {
|
|
scenario((time, container, relay) {
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 200),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
// Signed behind the relay clock but ingested before fan-out, so the
|
|
// fresh observation must carry its effect instead of trusting either
|
|
// clock against the other.
|
|
relay.emit(_event('alice', 'offline', timestamp: 190));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
time.elapse(Duration.zero);
|
|
expect(relay.queries, hasLength(2));
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'offline', subject: 'alice', timestamp: 201),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(container.read(presenceCacheProvider)['alice'], 'offline');
|
|
});
|
|
});
|
|
|
|
for (final settled in ['online', 'offline']) {
|
|
for (final newer in [false, true]) {
|
|
test(
|
|
'equal-second $settled / newer=$newer requires fresh confirmation',
|
|
() {
|
|
scenario((time, container, relay) {
|
|
final transition = settled == 'online' ? 'offline' : 'online';
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 20),
|
|
]);
|
|
time.flushMicrotasks();
|
|
if (settled == 'offline') {
|
|
time.elapse(const Duration(seconds: 60));
|
|
relay.results.removeAt(0).complete([]);
|
|
time.flushMicrotasks();
|
|
}
|
|
expect(container.read(presenceCacheProvider)['alice'], settled);
|
|
relay.emit(_event('alice', transition, timestamp: 20));
|
|
expect(container.read(presenceCacheProvider)['alice'], settled);
|
|
time.elapse(Duration.zero);
|
|
expect(relay.queries, hasLength(settled == 'online' ? 2 : 3));
|
|
expect(relay.queries.last.authors, ['alice']);
|
|
expect(container.read(presenceCacheProvider)['alice'], settled);
|
|
// Same observation second, but this POST follows live delivery.
|
|
final confirmed = newer ? transition : settled;
|
|
relay.results.removeAt(0).complete([
|
|
if (confirmed == 'online')
|
|
_event('relay', 'online', subject: 'alice', timestamp: 20),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(
|
|
container.read(presenceCacheProvider)['alice'],
|
|
newer ? transition : settled,
|
|
);
|
|
});
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
test('redelivered ambiguous event arms one confirmation', () {
|
|
scenario((time, container, relay) {
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 20),
|
|
]);
|
|
time.flushMicrotasks();
|
|
final delayed = _event('alice', 'offline', timestamp: 10);
|
|
relay.emit(delayed);
|
|
time.elapse(Duration.zero);
|
|
relay.results.removeAt(0).complete([
|
|
_event('relay', 'online', subject: 'alice', timestamp: 22),
|
|
]);
|
|
time.flushMicrotasks();
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
// The same frame is redelivered after the confirmation settled; a
|
|
// bounded id memory must keep it from re-arming a refresh.
|
|
relay.emit(delayed);
|
|
time.elapse(Duration.zero);
|
|
expect(relay.queries, hasLength(2));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
});
|
|
});
|
|
}
|
|
|
|
NostrEvent _event(
|
|
String author,
|
|
String status, {
|
|
String? subject,
|
|
int timestamp = 10,
|
|
}) => NostrEvent(
|
|
id: '$author-$status-$timestamp',
|
|
pubkey: author,
|
|
createdAt: timestamp,
|
|
kind: EventKind.presenceUpdate,
|
|
tags: [
|
|
if (subject != null) ['p', subject],
|
|
],
|
|
content: status,
|
|
sig: 'sig',
|
|
);
|
|
|
|
class _Lifecycle extends AppLifecycleNotifier {
|
|
@override
|
|
AppLifecycleState build() => AppLifecycleState.resumed;
|
|
}
|
|
|
|
class _Relay extends RelaySessionNotifier {
|
|
final queries = <NostrFilter>[];
|
|
final results = <Completer<List<NostrEvent>>>[];
|
|
late void Function(NostrEvent) emit;
|
|
Completer<void>? ready;
|
|
bool failSubscribe = false;
|
|
int subscriptions = 0;
|
|
int unsubscribes = 0;
|
|
|
|
@override
|
|
SessionState build() => const SessionState(status: SessionStatus.connected);
|
|
|
|
@override
|
|
Future<void Function()> subscribeWithStatus(
|
|
NostrFilter filter,
|
|
void Function(NostrEvent) onEvent, {
|
|
void Function(String)? onClosed,
|
|
required void Function(RelaySubscriptionStatus) onStatusChanged,
|
|
bool resumeSince = true,
|
|
}) async {
|
|
subscriptions++;
|
|
if (failSubscribe) throw StateError('unavailable');
|
|
emit = onEvent;
|
|
onStatusChanged(RelaySubscriptionStatus.ready);
|
|
if (ready != null) await ready!.future;
|
|
return () => unsubscribes++;
|
|
}
|
|
|
|
@override
|
|
Future<List<NostrEvent>> queryRelay(
|
|
List<NostrFilter> filters, {
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) {
|
|
queries.addAll(filters);
|
|
final result = Completer<List<NostrEvent>>();
|
|
results.add(result);
|
|
return result.future;
|
|
}
|
|
}
|