Repository navigation
perf(mobile): race the direct and relay dials from t=0 on every reconnect - #19308
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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 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
✨ 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 6010426d-4308-4e36-be93-48e50ec2d053
📒 Files selected for processing (13)
mobile/src/transport/mobile-direct-return-probe.test.tsmobile/src/transport/mobile-direct-return-probe.tsmobile/src/transport/mobile-endpoint-reconnect-race.test.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-background-grace.tsmobile/src/transport/mobile-relay-credential-refresh.tsmobile/src/transport/mobile-relay-direct-grace-timer.tsmobile/src/transport/mobile-relay-e2ee-link.test.tsmobile/src/transport/mobile-relay-lost-race-damper.tsmobile/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.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Reconnect races direct and relay from t=0 —
DirectReturnProbegainsprobeNow()/canDial/adoptsOutrightso a reconnect dials both paths immediately; the first socket to authenticate wins throughmigrateTo, and the loser closes without booking a relay step or touching the hysteresis streak. - Grace timer deleted, relay yields only to a live session —
MobileRelayDirectGraceTimeris removed andrelayDialAllowedadmits relay whenever the logical state isn'tconnected, so off-LAN phones no longer pay the fixed head start. - Lost-race damper added —
RelayLostRaceDamperpaces 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 —
withdrawWhenDirectWinscloses a losing relay socket before any E2EE frame, so the desktop never handshakes for a dial that will be discarded. - Credential rotation split out —
MobileRelayCredentialRefreshextracts the inline rotation; newmobile-endpoint-reconnect-race.test.tscovers 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…ad of waiting on direct
…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.

Stacked on #19280
Base is
mobile/relay-connect-critical-path. Retarget tomainafter #19280 merges.#19236 was merged and then reverted on
mainby #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 thecanDialandadoptsOutrighthooks this branch introduces; without it the fixture threw at the first dial. The earlier diff againstmainwas taken over amainthat 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
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.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.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:changed0 across 20 files.Not for merge until the owner gives the go.