Skip to content

perf(mobile): cut the relay reconnect critical path and admit dead sockets faster - #19236

Merged
Jinwoo-H merged 2 commits into
mainfrom
mobile/relay-connect-critical-path
Sep 7, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
mobile/relay-connect-critical-path

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​338 $\color{#cf222e}{\Huge{\mathbf{−}}}$​61 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​277
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​198 $\color{#cf222e}{\Huge{\mathbf{−}}}$​57 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​141

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: connected is 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

  • Connected at authentication. connected is published right after e2ee_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 a relayHostId mismatch after the desktop was rehomed) books backoff exactly as a failed dial did, and setActiveSession / recordMigration never run for a dying session. The confirm is bounded by a 12 s timeout, which restores the previous mutex bound.
  • Foreground liveness. 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.
  • Direct probe off the mutex. The 12 s direct dial runs outside 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 --check after rebase on main.
  • Independent adversarial review, two rounds. Round 1 found that a failed confirm was reported as an established dial (tight redial loop, no backoff) and that the 2 s single-miss profile would kill healthy sockets; both fixed and re-verified, including a supervisor-level test that fails on the pre-fix code.

Not for merge until the owner gives the go.

…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.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change updates relay session establishment so authentication publishes connected before resume confirmation, while persistence and migration await confirmation completion. It adds foreground-aware idle probes and urgent app-resume probes with separate watchdog profiles. Direct endpoint dialing no longer holds the supervisor mutex. Recovery intents are queued during cutover and replayed after the operation completes. Tests cover confirmation failures, liveness timing, direct probe recovery, backoff, and queued recovery replay.

Merge Risk: 🟡 Moderate · up to 37b12

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 … Add the required template sections. Provide a linked issue in the form Fixes #...; add visual proof or state N/A with a reason; complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections as…
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary changes: reducing relay reconnect latency and detecting dead sockets sooner.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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 Fixes #...; add visual proof or state N/A with a reason; complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections as applicable.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: bd97e823-5c22-45f5-9915-c32466afdb29

📥 Commits

Reviewing files that changed from the base of the PR and between 3f4793b and 37b124f.

📒 Files selected for processing (15)
  • mobile/src/transport/mobile-direct-return-probe.ts
  • mobile/src/transport/mobile-endpoint-lifecycle.ts
  • mobile/src/transport/mobile-endpoint-supervisor-contract.ts
  • mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
  • mobile/src/transport/mobile-endpoint-supervisor.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor.ts
  • mobile/src/transport/mobile-relay-credential-rotation.ts
  • mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts
  • mobile/src/transport/mobile-relay-rpc-session.test.ts
  • mobile/src/transport/mobile-relay-rpc-session.ts
  • mobile/src/transport/mobile-relay-runtime-failover.test.ts
  • mobile/src/transport/mobile-relay-session-establisher.ts
  • mobile/src/transport/relay-recovery-intent-queue.ts
  • mobile/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • connected at E2EE auth — mobile-relay-rpc-session.ts publishes connected in publishAuthenticated() 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 new whenResumeConfirmed() promise exposes confirm settlement, and the confirm is bounded to min(requestTimeoutMs, 12s).
  • Foreground liveness — RpcSessionLivenessWatchdog gains an urgent 2s/2-miss profile for app-resume probes (verdict at 4s instead of 8s), plus a 25s idle sweep gated by shouldIdleProbe so 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-latch RelayRecoveryIntentQueue and replayed on release.
  • Establisher waits for the confirm verdict — mobile-relay-session-establisher.ts awaits whenResumeConfirmed() 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 23df74d into main Sep 7, 2026
23 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 7, 2026
…ct for a separate mobile pass (#19265)

* Revert "feat(mobile): draw the last known tab strip while a session reconnects (#19258)"

This reverts commit 0ba7f8d.

* Revert "perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (#19236)"

This reverts commit 23df74d.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 7, 2026
…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.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 7, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant