Repository navigation
perf(mobile): cut the relay reconnect critical path and admit dead sockets faster - #19236
Conversation
…ckets faster
Phone medians put E2EE authentication at ~424ms but `connected` at ~630ms,
because the session serialized two RPC round trips behind it: the resume
confirm (`pairing.getEndpoints`) and the capability advisory. Both now ride
the authenticated socket concurrently and off the critical path, so the
session publishes `connected` as soon as E2EE authenticates. Peer identity
is already proven by then — the confirm carries credential/lease bookkeeping
and the cell assignment check, and it still fails the session on a bad answer
or a foreign relayHostId, only later. `persistResumeConfirmation` awaits the
new `whenResumeConfirmed()` instead of assuming the answer is present at
`connected`.
Foreground liveness on a retained relay: `notifyForeground('app-resume')`
now probes past the 10s voluntary minimum on urgent bounds (2s, one miss),
so a socket that died while the process was suspended is admitted in ~2s
instead of ~8s. Focus and network nudges keep the old minimum and bounds.
Relay sessions also gain a 25s idle sweep, gated on foreground so a
backgrounded app spends no probes.
Recovery is no longer blocked by the direct return probe. The probe's 12s
dial is a pure observation on its own socket, so it takes the supervisor's
operation mutex only for the cutover; a relay recovery landing during a
foreground return now starts immediately instead of waiting the budget out.
Requests that do land during the cutover are queued in a new
RelayRecoveryIntentQueue and replayed on release — an owning forced
replacement keeps its intent, everything else replays as a plain recovery.
Tests updated deliberately, for the new ordering:
- 'sends no periodic traffic while an authenticated relay is idle' asserted
the absence of any relay idle probe, which is exactly the gap D3 closes.
Replaced by a sweep test plus a backgrounded no-probe test.
- 'rate-limits foreground sequences without suppressing a retry' asserted
that app-resume was suppressed inside the 10s minimum. An app resume is
now the one nudge that must never be rate-limited.
- the session helpers waited for the confirm answer before `connected`;
they now authenticate, read both concurrent frames, and settle them.
… cutover Review round 1 on 352bfd2300. P1: publishing `connected` at E2EE authentication made `migrateTo` resolve before the resume confirm answered, so a confirm that failed afterwards — a `relayHostId` mismatch from a rehomed desktop is the live case — was still reported as an `established` dial. registerFailure was skipped, no cooldown was booked, recordMigration()/setActiveSession() ran for a dying session, and the queued-recovery replay redialled immediately: a tight loop with a connected→disconnected blip per pass. The establisher now awaits whenResumeConfirmed() after the cutover and, if the session is no longer connected, reports a failed dial (or an aborted one when direct won or the supervisor went inactive) exactly as a rejected migrateTo used to. The UI still connects early; only the supervisor's bookkeeping waits. The state check, rather than getFailure(), is the oracle: a live session can carry a latched failure without having failed yet, and "is this session still alive once the confirm settled" is precisely the question migrateTo used to answer. P2: the resume probe profile goes to two 2s misses instead of one. The first frame after a resume rides a cold radio and a possibly distant cell, so one slow answer is not proof of a dead link; the verdict still lands at 4s rather than the previous 8s. Nits: the direct probe's two early returns no longer close the candidate the finally also closes (the second shape pre-existed); RelayRecoveryIntentQueue is cleared in the supervisor's stop(). Mutex-hold note: persistResumeConfirmation, and now the establisher's own await, are bounded by the confirm's request timeout. That would have been the session's 30s default, so the confirm is pinned to RELAY_CONFIRM_TIMEOUT_MS (12s) — the same bound migrateTo's waitForAuthenticated applied before. Test: a supervisor-level case where every dial authenticates then fails the confirm must book 250/500/1000ms backoff with no immediate redial, and must never record a migration. It fails on the pre-fix establisher.
📝 WalkthroughWalkthroughThe change updates relay session establishment so authentication publishes Merge Risk: 🟡 Moderate · up to The change can leave redundant sockets running, allow premature confirmation bookkeeping, and disconnect relays after the app backgrounds. These reliability regressions should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the motivation, implementation, wire impact, and verification, but it omits required template content. The Linked Issue section has no issue number, the required Visual Proof section is missing, and the checklist and review sections are not completed. Resolution Add the required template sections. Provide a linked issue in the form
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: bd97e823-5c22-45f5-9915-c32466afdb29
📒 Files selected for processing (15)
mobile/src/transport/mobile-direct-return-probe.tsmobile/src/transport/mobile-endpoint-lifecycle.tsmobile/src/transport/mobile-endpoint-supervisor-contract.tsmobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.tsmobile/src/transport/mobile-endpoint-supervisor-test-fakes.tsmobile/src/transport/mobile-endpoint-supervisor.test.tsmobile/src/transport/mobile-endpoint-supervisor.tsmobile/src/transport/mobile-relay-credential-rotation.tsmobile/src/transport/mobile-relay-rpc-session-liveness.test.tsmobile/src/transport/mobile-relay-rpc-session.test.tsmobile/src/transport/mobile-relay-rpc-session.tsmobile/src/transport/mobile-relay-runtime-failover.test.tsmobile/src/transport/mobile-relay-session-establisher.tsmobile/src/transport/relay-recovery-intent-queue.tsmobile/src/transport/rpc-session-liveness-watchdog.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
connectedat E2EE auth —mobile-relay-rpc-session.tspublishesconnectedinpublishAuthenticated()and sends the resume confirm (pairing.getEndpoints) and the capability advisory (runtime.clientCapabilities.update) concurrently, removing two serialized round trips from every phone reconnect. A newwhenResumeConfirmed()promise exposes confirm settlement, and the confirm is bounded tomin(requestTimeoutMs, 12s).- Foreground liveness —
RpcSessionLivenessWatchdoggains an urgent2s/2-missprofile forapp-resumeprobes (verdict at 4s instead of 8s), plus a 25s idle sweep gated byshouldIdleProbeso a backgrounded app spends no probes. - Direct probe off the mutex — the 12s direct dial no longer holds the supervisor's
operationInFlight; only the cutover does. Recovery requests landing mid-operation are preserved in the new two-latchRelayRecoveryIntentQueueand replayed on release. - Establisher waits for the confirm verdict —
mobile-relay-session-establisher.tsawaitswhenResumeConfirmed()and returns a failed dial when the confirm fails after cutover, so a dying session books backoff instead of a tight redial.
I read the full diff and traced the concurrency the PR opens up. The intent queue never drops an intent (a dangling replacement latch is always consumed by clearReplacement() on established or takeReplacement() on the next recoverRelay), the single-timer watchdog correctly lets an urgent probe replace an in-flight ordinary one, and the confirm-failure-after-cutover path is pinned by the new supervisor-level test that asserts recordMigration is not booked. The new assertions are exact (timed misses, method arrays, recordMigration spy), not theater.
ℹ️ One coverage note (no action required)
RelayRecoveryIntentQueue has no dedicated unit test. The recovery latch's replay via the finally in recoverRelay (a plain recovery queued during a relay dial) is only exercised indirectly, unlike the direct-cutover afterProbe path which the 'replays a relay recovery that landed while the direct cutover owned the mutex' test covers directly. The logic is correct as written; worth a dedicated test only if this class grows.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…ckets faster (stablyai#19236) * perf(mobile): cut the relay reconnect critical path and admit dead sockets faster Phone medians put E2EE authentication at ~424ms but `connected` at ~630ms, because the session serialized two RPC round trips behind it: the resume confirm (`pairing.getEndpoints`) and the capability advisory. Both now ride the authenticated socket concurrently and off the critical path, so the session publishes `connected` as soon as E2EE authenticates. Peer identity is already proven by then — the confirm carries credential/lease bookkeeping and the cell assignment check, and it still fails the session on a bad answer or a foreign relayHostId, only later. `persistResumeConfirmation` awaits the new `whenResumeConfirmed()` instead of assuming the answer is present at `connected`. Foreground liveness on a retained relay: `notifyForeground('app-resume')` now probes past the 10s voluntary minimum on urgent bounds (2s, one miss), so a socket that died while the process was suspended is admitted in ~2s instead of ~8s. Focus and network nudges keep the old minimum and bounds. Relay sessions also gain a 25s idle sweep, gated on foreground so a backgrounded app spends no probes. Recovery is no longer blocked by the direct return probe. The probe's 12s dial is a pure observation on its own socket, so it takes the supervisor's operation mutex only for the cutover; a relay recovery landing during a foreground return now starts immediately instead of waiting the budget out. Requests that do land during the cutover are queued in a new RelayRecoveryIntentQueue and replayed on release — an owning forced replacement keeps its intent, everything else replays as a plain recovery. Tests updated deliberately, for the new ordering: - 'sends no periodic traffic while an authenticated relay is idle' asserted the absence of any relay idle probe, which is exactly the gap D3 closes. Replaced by a sweep test plus a backgrounded no-probe test. - 'rate-limits foreground sequences without suppressing a retry' asserted that app-resume was suppressed inside the 10s minimum. An app resume is now the one nudge that must never be rate-limited. - the session helpers waited for the confirm answer before `connected`; they now authenticate, read both concurrent frames, and settle them. * fix(mobile): book backoff when a relay resume confirm fails after the cutover Review round 1 on 352bfd2300. P1: publishing `connected` at E2EE authentication made `migrateTo` resolve before the resume confirm answered, so a confirm that failed afterwards — a `relayHostId` mismatch from a rehomed desktop is the live case — was still reported as an `established` dial. registerFailure was skipped, no cooldown was booked, recordMigration()/setActiveSession() ran for a dying session, and the queued-recovery replay redialled immediately: a tight loop with a connected→disconnected blip per pass. The establisher now awaits whenResumeConfirmed() after the cutover and, if the session is no longer connected, reports a failed dial (or an aborted one when direct won or the supervisor went inactive) exactly as a rejected migrateTo used to. The UI still connects early; only the supervisor's bookkeeping waits. The state check, rather than getFailure(), is the oracle: a live session can carry a latched failure without having failed yet, and "is this session still alive once the confirm settled" is precisely the question migrateTo used to answer. P2: the resume probe profile goes to two 2s misses instead of one. The first frame after a resume rides a cold radio and a possibly distant cell, so one slow answer is not proof of a dead link; the verdict still lands at 4s rather than the previous 8s. Nits: the direct probe's two early returns no longer close the candidate the finally also closes (the second shape pre-existed); RelayRecoveryIntentQueue is cleared in the supervisor's stop(). Mutex-hold note: persistResumeConfirmation, and now the establisher's own await, are bounded by the confirm's request timeout. That would have been the session's 30s default, so the confirm is pinned to RELAY_CONFIRM_TIMEOUT_MS (12s) — the same bound migrateTo's waitForAuthenticated applied before. Test: a supervisor-level case where every dial authenticates then fails the confirm must book 250/500/1000ms backoff with no immediate redial, and must never record a migration. It fails on the pre-fix establisher.
…ct for a separate mobile pass (stablyai#19265) * Revert "feat(mobile): draw the last known tab strip while a session reconnects (stablyai#19258)" This reverts commit 0ba7f8d. * Revert "perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (stablyai#19236)" This reverts commit 23df74d.

Why
After a phone comes to the foreground it can take many seconds to show a live desktop even when the relay path is healthy. Three things on the phone side stack up:
connectedis published only after two serialized RPCs, a retained relay session gets no liveness probe while idle and at most one probe per 10 s on foreground, and the foreground direct-return probe holds the supervisor mutex for up to 12 s so relay recovery queues behind it.What
connectedis published right aftere2ee_authenticated. The resume confirm and the capability advisory are still frames 0 and 1, but no longer gate the state. The supervisor still waits for the confirm before booking the dial as established, so a confirm that fails (for example arelayHostIdmismatch after the desktop was rehomed) books backoff exactly as a failed dial did, andsetActiveSession/recordMigrationnever run for a dying session. The confirm is bounded by a 12 s timeout, which restores the previous mutex bound.probeNow(identity, 'nudge' | 'resume'). A resume probe ignores the 10 s minimum and uses a 2 s / 2-miss profile (verdict at 4 s instead of 8 s, with one tolerated slow answer for a cold radio). Idle relay sessions get a 25 s sweep gated on foreground state.operationInFlight; only migrate/cutover take it. Recovery requests that arrive during the dial are preserved in a small intent queue and replayed.Wire
No change. Desktop and relay untouched.
Verification
mobile:tsc --noEmit,vitest run(516 files, 4213 tests),oxlint,oxfmt --checkafter rebase on main.Not for merge until the owner gives the go.