Skip to content

perf(mobile): race the direct and relay dials from t=0 on every reconnect - #19308

Merged
Jinwoo-H merged 5 commits into
mainfrom
mobile/race-direct-and-relay
Sep 7, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
mobile/race-direct-and-relay

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

Re-opened against main after #19280 merged and its branch deletion auto-closed #19256. Same four commits rebased onto the squash.

Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​423 $\color{#cf222e}{\Huge{\mathbf{−}}}$​87 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​336
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​345 $\color{#cf222e}{\Huge{\mathbf{−}}}$​141 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​204

Stacked on #19280

Base is mobile/relay-connect-critical-path. Retarget to main after #19280 merges.

#19236 was merged and then reverted on main by #19265, so phase 1 was re-opened as #19280 for the separate mobile review pass. This branch was rebased onto that new phase-1 head, which carries phase 1's review fixes. One extra commit here (e7087173d9) gives phase 1's direct-probe test fixture the canDial and adoptsOutright hooks this branch introduces; without it the fixture threw at the first dial. The earlier diff against main was taken over a main that still contained phase 1 and no longer applies.

Held: do not merge without the owner's mobile-pass go.

Why

On every reconnect the phone gave the direct (LAN) path a fixed 2.5 s head start and blocked relay recovery while direct was connecting or handshaking. Off-LAN users paid that head start on every reconnect for nothing.

What

  • Both dials start at t=0. The first to reach the point the establisher declares established is adopted through the existing migrateTo; the loser closes cleanly and books nothing. The grace timer module is deleted; relay yields only to a live session (relayDialAllowed). When relay owns the client, the direct-return probe adopts an authenticated direct socket outright when no live session exists and no longer waits on the operation mutex.
  • Kept: the 30 s background grace and foreground gate (a backgrounded phone opens no relay splice), the shared relay failure cooldown, and hysteresis dwell for promotions against a live relay.
  • Pre-handshake withdraw: when direct authenticates first, the establisher closes the cell socket immediately, so the relay sees one outer frame and the desktop never runs an E2EE handshake for a dial that will be discarded.
  • Lost-race damper (mobile-relay-lost-race-damper.ts): after a relay dial loses to direct, the next unforced race is suppressed for 2 s, doubling per consecutive loss to a 30 s cap. Separate from the failure backoff. A relay win or a foreground resume clears it. If the direct path is then lost, the wait collapses to a 250 ms floor with the remaining window set aside and restored only if direct returns within the floor, so a flapping LAN cannot drive unbounded relay dials and a dead LAN never leaves the user waiting out the window.
  • Failure semantics: only when both lose is the reconnect a failure, booking one relay step and one direct failure. Credential rotation moved to mobile-relay-credential-refresh.ts; the rotation logic is unchanged, but its recovery trigger now follows the race rule (relay yields only to a live session) instead of the old needsRecovery gate.

Wire

No change.

Verification

  • mobile: tsc --noEmit, vitest run (517 files, 4222 tests), oxlint, oxfmt --check; check:code-quality:changed 0 across 20 files.
  • Independent adversarial review, three rounds. Round 1 proved single-winner atomicity and no authorization bypass and required the pre-handshake withdraw and the damper. Round 2 found the damper could strand a user for up to 30 s after the LAN died. Round 3 verified the clamp/restore edge cases (stop, background, cap, double blip). Mutation checks split the clamp and restore responsibilities.

Not for merge until the owner gives the go.

…nect

A foreground reconnect gave the direct dial a fixed 2.5s head start, and while
that dial sat in 'connecting'/'handshaking' the supervisor refused to open a
relay socket at all. A phone that is off the LAN paid the full head start on
every reconnect and got nothing for it, and a phone whose relay dropped could
only return to the LAN through three hysteresis probes.

Both dials now start together and the first authenticated socket is adopted
through the existing migrateTo cutover. Nothing about the migration machinery
changes: only who is allowed to start a dial.

- The relay dial now yields to a live session and to nothing else. An unfinished
  direct dial is progress on the other runner, not a reason to stand still.
- The direct return probe grows a second adoption policy. Against a live relay
  hysteresis still has to prove direct stable; during a reconnect there is no
  session to protect, so an authenticated direct socket wins outright. probeNow
  pre-empts a pending 15s tick so that dial starts with the relay dial, not
  after it, and the dial itself no longer waits for the operation mutex — a
  relay dial holding it is exactly the case the race exists for.
- A loser closes and books nothing. The relay dial withdraws inside migrateTo
  and returns 'aborted', so no backoff is booked against it; a direct socket
  that loses leaves the promotion streak untouched. Only a reconnect that both
  paths lose books a failure, once, on the relay cadence.

Kept: the 30s background grace and the foreground gate, because a backgrounded
phone must not open a billed relay splice; the shared failure cooldown, because
a genuine relay failure still has to be paced; the hysteresis dwell after a
migration, because it is what stops a marginal LAN flapping a healthy session.

The accepted cost is one relay socket per reconnect for a phone that is on its
LAN. It closes as soon as the direct path authenticates, before the resume
confirm, because migrateTo only checks the abort predicate after E2EE auth.

Tests that encoded the removed rules:
- 'fails over when the direct retry loop publishes reconnecting' asserted no
  relay dial while direct was handshaking. The failover now precedes the direct
  client giving up, so it asserts the dial instead of its absence.
- 'does not spend a queued relay retry while direct authentication is
  progressing' encoded the block outright; it now asserts the retry runs on the
  failure cadence while a handshake drags on.
- The four grace-race cases move to mobile-endpoint-reconnect-race.test.ts as
  t=0, direct-wins, background/resume and both-lose cases.
- Five relay-bookkeeping cases now state their premise with unreachableDirect.
  They describe a phone with no LAN, which used to be implicit and is now
  load-bearing: with a reachable LAN the direct socket wins those reconnects.
…aces

Review follow-up to 4e31130471. Racing both paths from t=0 was correct but
charged the LAN case twice: once per reconnect in cell work, and again whenever
the LAN flapped.

Withdraw before the handshake. migrateTo only consults its abort predicate after
E2EE authentication, so a dial that had already lost still made the cell reserve
a splice and the desktop finish a key exchange. The establisher now watches the
logical client across the dial and closes the cell socket the moment direct
authenticates. In the common window, after relay-auth is on the wire and before
the hello lands, nothing of the key exchange has started, so the withdrawal
costs the desktop nothing. The dial still reports itself aborted and still books
nothing. The watch is dropped once migrateTo returns, because past the cutover
this session is the active path and a later direct promotion must not read as a
reason to close the client's own socket.

Damp races that a blip started. relayDialAllowed yields only to a live session
and a lost race books nothing, so a flapping LAN drove one cell socket per blip
with only the relay's per-host rate limiter as a backstop, and reaching that
limiter would have converted a benign race into a booked relay failure. After a
race is lost to direct, the next unforced race is suppressed for 2s, doubling
per consecutive loss to a 30s cap. This is not backoff and is kept separate from
it: a forced replacement is never damped, a relay dial that wins clears the
streak, and a foreground resume clears it too, so the path the user is watching
never waits. The window arms its own lapse timer, so a LAN that dies inside the
window still reaches relay without a new trigger.

A superseded cutover no longer escapes probe() as an unhandled rejection. Only
the probe timer calls it, and it discards the promise, so the routine end of a
lost race would have surfaced as one.

Credential rotation moves to MobileRelayCredentialRefresh. The supervisor
crossed the 300-line cap; rotation is a self-contained responsibility that only
runs over a live direct connection, so it splits cleanly instead of taking a
max-lines bump.
… gone

Round-2 review follow-up to 9a21da4326. The damper armed its window when direct
won the race, and nothing shortened it. A LAN that died inside that window left
the phone waiting out the whole thing, up to 30s at the cap, with only a log
line to show for it. My previous commit body claimed the path the user watches
never waits; that was true only of a foreground resume, and it is corrected
here.

Losing the direct path now collapses the wait to a 250ms floor, so the next
recovery races almost at once. The floor is not zero because the reason the
damper exists is a LAN that drops and comes straight back, and a disconnect is
how such a blip begins. So the rest of the window is kept aside rather than
spent: if direct returns inside the floor it was a blip and the window resumes,
and if the floor lapses with direct still gone it was an outage and the held
window is void. Without the second half, one blip would have bought a flapping
LAN a free pass on every race that followed, which is the case the damper was
added for.

The streak itself is untouched by the clamp. A LAN that flaps all afternoon
still escalates toward the cap; only the current wait is cut short.

record() now takes the same forceReplacement guard as suppresses(), so a forced
replacement that stands down cannot grow the streak or be read as a loss to
direct. A lease rotation or a reconsidered network change is not a LAN that
flapped.

Also documents that a genuine relay failure deliberately does not reset the
streak, and that the damper and the failure backoff serialize rather than stack:
a damped attempt never reaches the dial that would book a cooldown.
The phase-1 probe test predates canDial and adoptsOutright, so its hooks
literal threw at the first dial. These cases model a live relay session.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 61c07402-4f47-4bb4-8371-dfe562470298

📥 Commits

Reviewing files that changed from the base of the PR and between d59fc30 and 77224ac.

📒 Files selected for processing (1)
  • mobile/src/transport/mobile-endpoint-supervisor.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/transport/mobile-endpoint-supervisor.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The mobile transport now races direct and relay connections from t=0 during reconnects. Direct authentication can win outright, while hysteresis remains active when a relay session exists. Losing relay sessions withdraw during migration. Repeated relay losses use capped damping with direct recovery handling. Credential rotation uses a dedicated refresh collaborator. Background and foreground transitions use immediate direct probing. Tests cover races, cleanup, backoff, damping, endpoint failures, and E2EE-link withdrawal.

Merge Risk: ⚪ Minimal · up to 77224

Mobile reconnects now race direct and relay paths immediately, adopting the first established connection while cleaning up the loser. No concrete merge-blocking risk is established by the supplied change context.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the rationale, implementation, behavior, testing, linked issues, and merge constraints, but it omits most required template sections and checklist confirmations. It does not i… Reformat the description to include all required template sections. Add an explicit Linked Issue section with the applicable issue reference, add Visual Proof with N/A and a reason if no visual change exists, complete the Testing checklis…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses the objectives in issue [#19256]. It races direct and relay dials from t=0, adopts the first established path, withdraws losing relay sessions, preserves required gates an…
Out of Scope Changes check ✅ Passed The changes remain within the linked issue scope. The credential-refresh extraction, damper, session withdrawal logic, test fakes, and regression tests directly support the reconnect race behavior and…
Title check ✅ Passed The title clearly and concisely summarizes the primary change: racing direct and relay dials from t=0 on mobile reconnects.
Full details: Description check

Explanation

The description explains the rationale, implementation, behavior, testing, linked issues, and merge constraints, but it omits most required template sections and checklist confirmations. It does not include the required Visual Proof section with N/A and a reason, explicit Testing checklist entries, or the remaining required headings.

Resolution

Reformat the description to include all required template sections. Add an explicit Linked Issue section with the applicable issue reference, add Visual Proof with N/A and a reason if no visual change exists, complete the Testing checklist, address AI Disclosure as applicable, complete Review, Agent skill upstream boundary, Notes, and Checklist sections, and retain the existing technical details.

  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 6010426d-4308-4e36-be93-48e50ec2d053

📥 Commits

Reviewing files that changed from the base of the PR and between e628090 and d59fc30.

📒 Files selected for processing (13)
  • mobile/src/transport/mobile-direct-return-probe.test.ts
  • mobile/src/transport/mobile-direct-return-probe.ts
  • mobile/src/transport/mobile-endpoint-reconnect-race.test.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-background-grace.ts
  • mobile/src/transport/mobile-relay-credential-refresh.ts
  • mobile/src/transport/mobile-relay-direct-grace-timer.ts
  • mobile/src/transport/mobile-relay-e2ee-link.test.ts
  • mobile/src/transport/mobile-relay-lost-race-damper.ts
  • mobile/src/transport/mobile-relay-session-establisher.ts
💤 Files with no reviewable changes (1)
  • mobile/src/transport/mobile-relay-direct-grace-timer.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 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 critical issues — one minor suggestion inline.

Reviewed changes

  • Reconnect races direct and relay from t=0 — DirectReturnProbe gains probeNow()/canDial/adoptsOutright so a reconnect dials both paths immediately; the first socket to authenticate wins through migrateTo, and the loser closes without booking a relay step or touching the hysteresis streak.
  • Grace timer deleted, relay yields only to a live session — MobileRelayDirectGraceTimer is removed and relayDialAllowed admits relay whenever the logical state isn't connected, so off-LAN phones no longer pay the fixed head start.
  • Lost-race damper added — RelayLostRaceDamper paces the relay half of the race after losses (2 s doubling to a 30 s cap) with a 250 ms floor when the winning direct path drops, so a flapping LAN opens one cell socket per race and a dead LAN never waits out the window.
  • Pre-handshake withdraw — withdrawWhenDirectWins closes a losing relay socket before any E2EE frame, so the desktop never handshakes for a dial that will be discarded.
  • Credential rotation split out — MobileRelayCredentialRefresh extracts the inline rotation; new mobile-endpoint-reconnect-race.test.ts covers single-winner adoption, damper clamp/restore, foreground resume, and the single-booking failure case.

I traced the single-winner invariant (migrateTo performs its shouldAbort check and swap synchronously), the damper clamp/restore state machine, and the out-of-band direct cutover that skips the operation mutex; all held up. Ran the changed test files (61 passed) and tsc --noEmit clean.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit ceafdca into main Sep 7, 2026
22 checks passed
@Jinwoo-H
Jinwoo-H deleted the mobile/race-direct-and-relay branch September 7, 2026 17:45
Jinwoo-H added a commit that referenced this pull request Sep 7, 2026
…aller, verified re-land (#19348)

* Revert "feat(mobile): time relay dial stages so diagnostics say where a slow connect went (#19245)"

This reverts commit 83b1558.

* Revert "perf(mobile): race the direct and relay dials from t=0 on every reconnect (#19308)"

This reverts commit ceafdca.

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

This reverts commit 643571d.

* Revert "perf(mobile): open a session with parallel startup RPCs and a pre-warmed terminal engine (#19260)"

This reverts commit c374132.

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

This reverts commit e628090.

* chore: keep the react-doctor suppression for the startup timers

The pattern it covers (a variable number of timers cleared through one cleanup)
predates #19260 and is unchanged by the revert; dropping the entry only re-exposed
a pre-existing finding to the changed-code gate.
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