fix(mobile): make relay publish recovery durable
Summary
Draft checkpoint for the Buzz Mobile reliability incident reported in Buzz.
Related upstream reports: #3224, #4404, and #3591. This draft combines the resume/liveness repair with send durability and direct-message pickup; it does not replace the narrower reviewed input in #4372.
This checkpoint improves relay recovery and mobile send durability:
- queues event-ID-deduplicated publishes across reconnects
- performs explicit reconnect cleanup for pending history and buffered events
- reconnects after a real long background pause while leaving short transient pauses alone
- detects silent WebSocket peers with native ping/pong
- adds cached direct-message participants as implicit recipients without waiting for a global channel refresh
- surfaces in-progress send state in channel and thread views
Root cause
The released mobile path could trust a stale connected socket after iOS suspension, silently drop publishes while disconnected or reconnecting, and omit recipient tags for plain direct messages. Those paths explain delayed refresh and messages that never reach an agent.
Validation at 170ce2fb8049e1e37e4b7f5552857a619d5c68c8
flutter testfrommobile— passedcargo test -p buzz-acp— passed- focused relay, liveness, and send tests — 37 passed before the full suites
- required contribution trailers verified
Draft blockers before review/merge
- [x] add ACP direct-message exemption compatibility from the reviewed #4185 path
- [x] add a persistent visible failed/retry delivery state, not only in-progress state
- [x] rerun the full mobile and ACP package suites at the final exact head
- [ ] obtain independent review of the final exact head
- [ ] preserve separate signed-build, TestFlight, and real-iPhone acceptance gates
No release tag, signed build, deployment, or mobile install is authorized or claimed by this draft.
Independent closure: ROLLBACK at 5d2cf8a52162fc21a8b109ead3f20b70cc158c37
Fresh independent review found no P0, but this head is not release-qualified. Four P1 clusters remain:
- Full mobile suite does not compile.
compose_bar_test.dartretains avoid RelaySocket.sendoverride after production changed the method tobool; two exact-head full-suite runs reached 965 passes and one load failure. - Queued publishes can expire before recovery. The default eight-second pending timeout is shorter than reconnect backoff plus authentication, and long-background cleanup rejects pending sends. The immediate-reconnect test does not exercise the real incident window.
- Replay dedup clears all keys at rollover. Reconnect replay after the 5,000-key clear can redeliver prior events; no rollover/replay negative is committed.
- Unresolved channel metadata can widen a group as a DM. DM classification currently fails open when metadata resolution is unavailable, allowing owner/sibling plain group messages to bypass the mention requirement.
Required remediation at one descendant head:
- update the stale socket test override and prove the full mobile suite
- retain queued events through reconnect/background, or implement a persisted retry contract that cannot expire before recovery
- replace clear-all dedup with bounded eviction that preserves recent IDs
- require confirmed DM metadata before removing the dynamic subscription mention filter or bypassing the local mention gate
- add fail-before/pass-after coverage for same-tick resume/send, duration beyond eight seconds, in-flight history cancel/retry, mixed-age buffered events, dedup rollover/replay, relay-accepted-but-OK-lost, and explicit non-DM caller independence
- rerun full mobile and
env -u BUZZ_ACP_LAZY_POOL cargo test -p buzz-acp
The PR remains draft. No merge, tag, signed build, install, deployment, or runtime change is authorized or implied.
Second independent verdict: ROLLBACK at exact head 170ce2fb8049e1e37e4b7f5552857a619d5c68c8.
Four prior blockers are closed and both full suites pass independently. One P1 remains: an event already dispatched on the old socket can retain dispatched=true and its active ACK timer across intentional long-background disconnect/reconnect. Because disconnect() cancels the stream subscription before close, _handleDisconnected is not guaranteed to reset it. The replacement socket then skips same-ID replay and the old timer may remove the event.
Remediation floor:
- Before intentional background disconnect or reconnect, cancel pending ACK timers and reset dispatched-but-unacknowledged events for automatic same-ID replay only after the replacement socket is authenticated.
- Add incident negatives for both same-tick resume/send orderings; dispatched ACK loss across long background and beyond eight seconds; reconnect during in-flight history with cancel-and-retry or completion; mixed-age buffered events across disconnect; and explicit non-DM caller independence during loading/error.
- Format
mobile/test/shared/relay/relay_session_test.dartand provedart format --output=none --set-exit-if-changed. - Rerun the full mobile suite and
env -u BUZZ_ACP_LAZY_POOL cargo test -p buzz-acpat one exact descendant head.
Keep the PR draft. No merge, tag, signed build, install, deployment, or runtime mutation.
Integrator preflight on exact head 03c9f25105b4bd7f18817b61ba74c8b20fc652a0: do not start independent re-review yet.
The descendant delta correctly adds _resetPendingDispatches() before intentional reconnect/background teardown, improves the already-dispatched ACK-loss test, formats the test file, and remains limited to relay session code/tests. However, compared with rejected head 170ce2fb…, it adds no committed coverage for the other explicitly required matrix cases:
- both orderings of same-tick resume/send;
- reconnect during an in-flight history request with cancel-and-retry or completion;
- disconnect mid-buffer with mixed-age events;
- explicit non-DM caller independence while channel state is loading or errored.
The writer checkpoint is therefore incomplete against the prior remediation floor. Add those fail-before/pass-after negatives, rerun format plus both full suites at one new descendant head, and keep the PR draft. No merge, tag, build, install, deployment, or runtime mutation.
Integrator preflight on exact head ff902f688d64eef0e36e4a205ee9bbcc653d31ff: still not ready for Sol.
Published facts:
- PR head, local HEAD, and clean worktree match.
- Delta adds the history cancel/retry case and an explicit-mentioned non-DM send when member lookup throws.
- No test exists for either same-tick ordering (
resumethensend, andsendthenresume). - The ACK-loss regression does not advance beyond the eight-second acknowledgement timeout.
flushes mixed-age buffered events before a disconnectcallsdebugFlushEventBuffer()beforedebugHandleDisconnected(), so it does not prove that a disconnect mid-buffer preserves/delivers the buffered events.
Required executable closure before another handoff:
- Add two separately named same-tick tests, one for each ordering, asserting one signed event ID and no loss/duplicate after the replacement socket authenticates.
- Make the dispatched/ACK-lost background test advance past eight seconds before replacement-socket ACK, proving the stale timer cannot fail/remove the event.
- Replace the mixed-age test with a real mid-buffer disconnect: enqueue old and new events, do not manually flush, trigger disconnect, and prove each expected event is delivered exactly once through the recovery path.
- Rerun format plus both full suites at one new descendant head and enumerate each required test by exact name in the handoff.
Keep draft; no merge, tag, build, install, deployment, or runtime mutation.
Integrator preflight ACCEPT for review entry only at exact head 8faa7276af81c72fb9e50557ae131f4b999ef23a.
Verified:
- PR head and local clean HEAD match; PR remains draft and blocked.
- All eight required incident test names are committed.
- Both same-tick orderings assert one replacement event with the original ID.
- Dispatched ACK-loss crosses nine seconds before replacement-socket acknowledgement.
- Mixed-age events are buffered and flushed by the real disconnect callback with no manual pre-flush.
- Repo-pinned format check passed with zero changes.
- Focused relay-session and send-message-provider suites passed at the same head; HEAD remained unchanged and worktree clean.
This admits the candidate to fresh independent review only. It is not merge, release, signed-build, install, deployment, or real-device acceptance.
Third independent verdict: ROLLBACK at exact head 8faa7276af81c72fb9e50557ae131f4b999ef23a.
The full mobile/ACP suites, formatting, confirmed-DM fail-closed behavior, bounded dedup, and authenticated replacement drain are independently green. One production P1 remains: a silent connected socket can accept sink.add, then the eight-second ACK timeout removes the pending event before the 30-second liveness horizon can produce disconnect/replay.
Production remediation contract:
- Distinguish explicit relay rejection from missing acknowledgement.
OK falseand terminal auth rejection may becomefailed; missing ACK must not delete the exact signed event. - On missing ACK, retain the same event ID, expose a distinct user-visible
unconfirmedstate on both channel and thread surfaces, and initiate bounded transport recovery/probe. Reset it for exactly-once replay only after an authenticated replacement socket; no infinite reconnect/replay loop. - A later
OK truefor that ID becomessent; explicit rejection becomesfailed; manual Retry must reuse the original signed ID.
Required incident-shaped tests:
- silent socket reports send success, eight seconds elapse, event remains pending/unconfirmed, recovery opens/authenticates a replacement, same ID is replayed once, and one ACK completes it;
- both same-tick resume/send orderings begin while the old session still reports connected, not after
debugHandleDisconnected(); - in-flight history is cancelled through actual
reconnect(), then retry completes on the replacement generation; - mixed-age buffered events use genuinely different
createdAtvalues spanning beyond replay skew and recover exactly once through disconnect; - channel and thread UI render
Unconfirmeddistinctly fromFailedand retain Retry behavior.
Rerun format, both full suites, and focused incident/UI tests at one descendant head. Keep draft; no merge, tag, build, install, deployment, or runtime mutation.
Integrator decision after current-main and PR #4372 overlap review
Exact inputs:
- Current
origin/main:a5dbdf5e61e4c512acd99c219c79c154ddb57295 - PR #4372:
71dbcdb8b1ddc3541910ed80854bbdde568ae6a1(green, review required) - PR #4443 committed head:
8faa7276af81c72fb9e50557ae131f4b999ef23a(draft, rejected, dirty against main) - Preserved local missing-ACK remediation: 10 files, +133/-11, uncommitted
Scope ownership is now explicit:
- PR #4372 owns stale-socket detection, background/resume liveness, and its liveness tests.
- PR #4443 owns durable pending sends, ambiguous missing-ACK/unconfirmed delivery state, same-ID recovery, direct-message recipient tagging and ACP pickup compatibility, and channel/thread delivery UI.
Safe integration sequence:
- Preserve the dirty missing-ACK remediation first: run formatting, the focused incident tests, full mobile suite, and full
buzz-acppackage suite at the current exact head; then create a local checkpoint commit using the repo-configured human identity trailers. Do not push yet. - Merge the freshly verified current
origin/maininto the branch. Do not rebase or force-push. The read-only merge simulation reports content conflicts only inmobile/lib/shared/relay/relay_session.dartandmobile/test/shared/relay/relay_session_test.dart. - Resolve those conflicts by retaining #4443's queue/missing-ACK work and current-main subscription recovery, while removing #4443's duplicate #4372-owned resume/liveness behavior. Restore
relay_socket.dart,relay_socket_liveness_test.dart, and any liveness-only dependency changes to current-main state. Keep incident tests only for #4443-owned send/DM behavior. - Rerun formatting,
git diff --check, the full mobile suite, andenv -u BUZZ_ACP_LAZY_POOL cargo test -p buzz-acpat one exact descendant head. Push normally to the existing fork branch and return exact base/head and results for fresh Sol review.
No ready mark, merge, tag, build, install, deployment, or runtime mutation is authorized by this integration decision. PR #4372 remains the independent freeze candidate; PR #4443 remains draft until its own fresh acceptance.
Reviewing this draft against the thread-cache finding I posted in #3224 (comment): the resume half looks addressed here — replacing the if (state.status == SessionStatus.connected) return; early-return in onAppResumed() is exactly the sixth gap named earlier in that thread. Two notes on what still looks open, offered as review input rather than a change request.
Inbound recovery has no equivalent to the outbound durability
The draft is thorough on the outbound path — queued publishes, delivery states, retry. For inbound events that landed on the relay while the socket was silently dead, I don't see a matching recovery:
_init()re-opens the live subscription withsince: _currentUnixSeconds(), so events from the stall window are never delivered as live events on the replacement connection.ChannelMessagesNotifier.build()refetches the channel window onSessionStatus.connected, which repairs the channel timeline.threadRepliesProvideris not covered by that refetch. It is aFutureProvider.familywithout.autoDispose, and its only invalidation is in_mergeWindowEventIntoStore— which runs only on a live threaded event. No live event for the missed replies means no invalidation, so the thread stays at its pre-stall state.
thread_detail_page.dart is touched in this draft, but for delivery-state UI; I don't see a refresh path added there.
Grepping this diff for threadRepliesProvider, invalidate, autoDispose and since: returns nothing, which matches that reading — happy to be corrected if the recovery lives somewhere I missed.
Observed shape
On the App Store build against a self-hosted relay: a thread showed 16 replies on iOS while desktop showed 19 at the same moment. It stayed at 16 across closing and reopening the thread, and only a full app kill restored it. So the failure survives a healthy connection — it is not gated on the socket being bad at the time you look.
Suggestion
Invalidating threadRepliesProvider for open roots when the session reaches connected (or making it .autoDispose so re-entering a thread refetches) would close this without touching the socket work. A regression test in the shape already proposed for #3231 would cover it directly: kill the socket without a close frame, land a threaded reply on the relay during the stall, reconnect, then assert the thread shows it without a restart.
Without that, better stall detection reduces how often a thread is truncated, but any stall that does slip through still leaves a silently short thread with no in-app way to correct it.