Files
buzz/mobile/lib/shared/read_state/read_state_retry.dart
Will Pfleger 890824f072 feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices
now sync across a person's installations. This PR specifies the rules in
NIP-RS and implements them in the mobile app.

## Spec (`docs/nips/NIP-RS.md`)

- Defines *catch-up* and *displayed*.
- A catch-up advances the channel's own frontier (top-level messages) or
`thread:<root>`. `activity:` and `thread-activity:` become read-only
legacy keys.
- Explicit mark read is synchronized state. A first explicit read of a
message with no override group writes only its `msg:` frontier. Display,
dwell, scroll, catch-up and mention visibility create no `msg:` entries.
- Only whole-channel override groups are published, merged and cleared
with the counter. Readers ignore peer `msg:` and `thread:` groups.
- Single-message and thread mark unread stay on the device. They end
once the merged frontier covering them passes their baseline, from any
installation, or on display, catch-up or explicit read. The section also
states clearing scope, the accepted concurrency limitation and capacity.
- When the merged override union no longer fits the primary, the client
rewrites the primary compactly from the groups its last published
primary carried, each canonical against current frontiers. It never
omits merged groups or tombstone floors that primary carried, and
override actions fail visibly.
- Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates,
validation, three-state verdict, last-writer merge with ties going to
unfollow, publication and recovery, legacy import at `at = 0`, and
capacity.

## Mobile

- Catch-up writes the main frontier. A flat timeline reads up to the
newest top-level message it reached.
- Explicit mark read publishes. Passive `msg:` marks stay on the device.
- Whole-channel mark unread publishes an override group and merges peer
groups. An explicit read or catch-up clears it, even when no frontier
moves. The action fails visibly at the uint32 limit or when the primary
is full. A synced clear the primary can't carry is rolled back, and the
channel view reports it once while the failure stands.
- Device-local message and Inbox unread overrides record a baseline and
clear when a covering frontier passes it, including one merged from a
peer.
- Thread follows move from local storage to the synced `thread-follows:`
slots. They share the read-state `client_id`, journal, `created_at`
sequence, snapshot and live subscription, and spill across up to 16
slots with stable placement. An unreadable coordinate marks follow state
incomplete and blocks this installation's follow publication.
- Follow and unfollow are refused on every cold start of the writer
until its first complete recovery of its own state succeeds and every
owned follow head is readable. Cached follows show at once. A refused
tap changes nothing and shows "Follow choices are not ready. Connect and
try again." Reads, catch-up and both kinds of mark unread are not gated.
- A follow tap is accepted only once journaled. The accepted own head,
pending edits and the exact in-flight packet are kept apart, so a retry
or restore never drops or re-attributes an edit.
- Pre-sync local follows are imported at `at = 0` after a complete
merge, once their channel is known from a relay event. An imported key
is settled, and its legacy copy retired, only when the journal write the
import awaited covered it and that entry is still current.
- An explicit unfollow suppresses ordinary replies at live and catch-up
admission. A change in follow choices drops the unread replies already
counted for an unfollowed thread. A newly followed thread re-runs
catch-up only for its own channel.
- A reading clear refused because the view hasn't completely loaded is
retried after the next complete snapshot, including when publishing was
shut off at the time. The view also counts as not completely loaded
while the live subscription is reconnecting, so a read made while the
phone is offline can't erase a newer unread mark set on another device.
Offline, whole-channel mark unread is still refused, with a message.
- Read-state events, including live ones, are verified with native
libsecp256k1 before they are used.
- A pending unread packet is counted as published only when no newer own
head outranks it. When a newer head supersedes it, a successor is built
above that head from the saved intent, and a late echo of a replaced
packet doesn't overwrite what was published.
- When the merged unread state overfills the primary and the compact
fallback can't carry a pending mark, the packet stays pending and the
"read state full" error shows. Other queued reads and follows in the
same flush still publish.
- When this installation's own unread record can't be decoded, only the
unread step is held: that record isn't overwritten, its pending marks
stay queued and the sync error shows. Other queued reads and follows in
the same flush still publish.
- The sync notice stays up after an unsupported refusal until a new
session. Offline, it can't be tapped and says it will retry when back
online.
- Two-device fixtures against an in-memory relay cover channel
round-trips and clears, stray message groups, the first explicit message
read, the primary cap, follow propagation, same-second and
backward-clock follow publication, legacy import, retry after a failed
publish, unreadable coordinates and slot packing. Recovery fixtures
cover the startup gate, journal failures during flush, interleaved
legacy imports, and restore of an older journal.

## Relay

- Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment:
a replaced record is purged, and a stale resend of an older one is
refused. Records with a mismatched `t` tag keep ordinary
replaceable-event behavior.

## Known gap

- An unread packet held for capacity can age past the relay's timestamp
window. The relay then refuses it, and the refusal path retires it
without the capacity check, so the error clears and other installations
don't get that mark. The mark stays on the device.

Related:
[block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552)

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Will Pfleger <wpfleger@squareup.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-19 17:02:58 -05:00

175 lines
6.8 KiB
Dart

part of 'read_state_manager.dart';
/// The relay refused a pending update for its timestamp, but the update is
/// not old by this device's clock, so the device clock is off from the
/// relay's. Signing a newer update would be refused the same way, so the
/// exact update is kept for retry.
class ReadStateClockSkewError implements Exception {
const ReadStateClockSkewError();
@override
String toString() =>
'ReadStateClockSkewError: the device clock differs from the relay clock';
}
/// The relay's accepted distance between an event's `created_at` and its own
/// clock (`MAX_TIMESTAMP_DRIFT_SECS` in the relay's ingest).
const readStateRelayTimestampWindowSeconds = 15 * 60;
/// Backoff between snapshot retries after a failed sync: doubling from
/// [_snapshotRetryBase], at most [_snapshotRetryMax].
const _snapshotRetryBase = Duration(seconds: 5);
const _snapshotRetryMax = Duration(minutes: 5);
/// Failed-sync retry, unpublished-state checks, refused-publish recovery
/// and acknowledgement.
extension ReadStateRetry on ReadStateManager {
/// Retry now after a failed sync: the remote snapshot again if the last one
/// failed, else any unpublished state. Does nothing while in sync.
Future<void> retrySync() async {
if (_disposed ||
!_remoteEnabled ||
!_initialized ||
syncError == null ||
!_isConnected()) {
return;
}
if (!_lastSnapshotSucceeded) {
_snapshotRetryTimer?.cancel();
_snapshotRetryTimer = null;
// A successful read hands any unpublished marks to publication.
await _requestSync();
return;
}
await flush();
}
void _scheduleSnapshotRetry() {
if (_disposed || _snapshotRetryTimer != null) return;
final seconds =
_snapshotRetryBase.inSeconds << min(_snapshotRetryAttempt, 6);
_snapshotRetryAttempt++;
_snapshotRetryTimer = Timer(
Duration(seconds: min(seconds, _snapshotRetryMax.inSeconds)),
() {
_snapshotRetryTimer = null;
unawaited(retrySync());
},
);
}
bool _isTimestampRefusal(Exception error) =>
error.toString().contains('timestamp too far from server time');
/// Retires [pending] after the relay refused it for its timestamp. The
/// outcome is known, the relay did not store it, so NIP-RS allows a
/// strictly newer successor in place of exact retry. Its marks were planned
/// from the journaled local state, which still holds them, so the next plan
/// reads a fresh snapshot and sends a successor, journaled before it is
/// sent, unless the relay already holds this update or an own update
/// covering it. An update that is not old by this device's clock means the
/// device clock is off, so it is kept for exact retry.
Future<void> _recoverRefusedPending(String slot, NostrEvent pending) async {
if (pending.createdAt >= _now() - readStateRelayTimestampWindowSeconds) {
throw const ReadStateClockSkewError();
}
if (identical(_pending[slot], pending)) _pending.remove(slot);
_maxFetchedCreatedAt = max(_maxFetchedCreatedAt, pending.createdAt);
await _persistLocalState();
}
void _acknowledge(String slot, NostrEvent event) {
if (slot.startsWith(threadFollowsDTagPrefix)) {
// An OK is evidence about this exact packet only. A later packet or a
// newer head may already have replaced it.
final index = _followSlots.indexOf(
slot.substring(threadFollowsDTagPrefix.length),
);
if (_pending[slot]?.id != event.id || index < 0) return;
final blob = decodeThreadFollowsBlob(_crypto.decrypt(event.content));
if (blob == null) throw StateError('Invalid pending thread follow event');
_applyOwnFollowHead(index, event, blob);
_maxFetchedCreatedAt = max(_maxFetchedCreatedAt, event.createdAt);
return;
}
final unread = slot.startsWith(readStateUnreadDTagPrefix);
final blob = decodeReadStateBlob(
_crypto.decrypt(event.content),
version: unread ? 2 : 1,
);
if (blob == null) throw StateError('Invalid pending read-state event');
if (unread) {
final head = _unreadHead;
// A newer own head that lacks this packet is what the relay holds; the
// successor is rebuilt above it from the saved intent.
if (slot == _unreadCoordinate &&
(head == null || !_outranks(head, event))) {
_unreadPublished = Map.of(blob.contexts);
} else if (!_primaryFits()) {
// The overfull fallback keeps the head's groups; keep the packet
// and fail visibly unless that successor still carries it.
final plan = _planUnread();
for (final MapEntry(:key, :value) in blob.contexts.entries) {
if ((plan[key] ?? -1) < value) {
throw StateError(readStateFullMessage);
}
}
}
} else {
_published[slot] = Map.of(blob.contexts);
}
_pending.remove(slot);
_maxFetchedCreatedAt = max(_maxFetchedCreatedAt, event.createdAt);
}
/// [_acknowledge], except that a packet held for capacity stays pending
/// and its error is returned, so the rest of the flush still goes out.
StateError? _acknowledgeOrHold(String slot, NostrEvent event) {
try {
_acknowledge(slot, event);
} on StateError catch (error) {
if (error.message != readStateFullMessage) rethrow;
return error;
}
return null;
}
bool _isPermanentReadStateRemoteError(Object error) {
// Relay rejections come back as `Exception("<message>")` from the
// websocket OK handler. Pattern-match on the message text since we no
// longer have HTTP status codes.
final msg = error.toString().toLowerCase();
return msg.contains('unknown event kind') ||
msg.contains('missing users:write') ||
msg.contains('insufficient scope') ||
msg.contains('restricted: unknown');
}
/// Whether a publish would send anything: a pending event to retry, or a
/// slot whose packed contexts differ from what was last published. Mirrors
/// the packing in [_publishOnce] without changing any state.
bool _hasUnpublishedState() {
if (_pending.isNotEmpty) return true;
for (final MapEntry(key: slot, value: plaintext)
in _plannedFollowSlots().entries) {
if (_followPublished[slot] != plaintext) return true;
}
final List<Map<String, int>> placement;
try {
placement = _planSlots();
} on StateError {
// Let the real publish surface the capacity error.
return true;
}
if (placement.length > _slots.length) return true;
if (_unreadPublishable && !mapEquals(_unreadPublished, _planUnread())) {
return true;
}
for (var index = 0; index < placement.length; index++) {
final published = _published[_slots[index]] ?? const <String, int>{};
if (!mapEquals(published, placement[index])) return true;
}
return false;
}
}