Skip to content

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

Closed
Jinwoo-H wants to merge 4 commits into
mobile/relay-connect-critical-pathfrom
mobile/race-direct-and-relay
Closed

Jinwoo-H wants to merge 4 commits into
mobile/relay-connect-critical-pathfrom
mobile/race-direct-and-relay

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{+}}}$​423 $\color{#cf222e}{\Huge{\mathbf{−}}}$​87 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​336
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​342 $\color{#cf222e}{\Huge{\mathbf{−}}}$​141 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​201

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 (behaviour-preserving split).

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.

@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

This PR replaces the fixed 2.5s direct head start with a first-authenticated-wins race between the direct and relay dials on every mobile reconnect. I read the full 12-file diff end-to-end, traced the cutover against migrateTo, verified the test and typecheck suites, and found the design sound.

  • Race-from-t=0 recovery — relayDialAllowed yields only to a live session, and recoverRelay kicks directProbe.probeNow() when nothing is connected, so an unfinished direct dial no longer blocks relay recovery.
  • Outright direct adoption — DirectReturnProbe.adoptsOutright lets a reconnecting direct socket win without hysteresis or the operation mutex, while hysteresis still arbitrates promotions against a live relay.
  • Lost-race damper — new RelayLostRaceDamper paces relay dials that lose to direct (2s doubling to a 30s cap) with a 250ms floor that collapses the window when direct is genuinely gone, so a dead LAN never waits out the window.
  • Pre-handshake withdraw — withdrawWhenDirectWins closes the cell socket the moment direct wins, so the desktop never finishes an E2EE handshake for a doomed dial.
  • Credential refresh split — rotation extracted to MobileRelayCredentialRefresh, behavior-preserving; mobile-relay-direct-grace-timer.ts deleted with no dead references.

I confirmed single-winner atomicity holds in migrateTo (the post-auth shouldAbort re-check and the synchronous cutover block run without an intervening await), close() is idempotent so the withdraw + abort double-close is safe, and the operation mutex is always released via finally. Ran the four changed test files (58 tests) and tsc --noEmit — all green.

ℹ️ noteDirectRestored fires on relay wins too

The onStateChange handler calls lostRace.noteDirectRestored() on every connected transition, including a relay win, but the damper's contract for that method is "direct came back inside the floor." It is correct today only because every relay connected transition flows through recordMigration → lostRace.reset(), which clears the transiently-restored window; a relay that fails resume-confirm after cutover never reaches recordMigration, but in that case the restored window is re-clamped by the following non-connected state change. Flagging for awareness rather than change — a future edit that skips or reorders recordMigration against the state listener would silently keep a stale damper window alive.

Note the PR is stacked on mobile/relay-connect-critical-path (#19236) and needs retargeting to main, and is gated on owner sign-off as stated in the description.

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

@Jinwoo-H
Jinwoo-H changed the base branch from mobile/relay-connect-critical-path to main September 7, 2026 08:41
@Jinwoo-H
Jinwoo-H force-pushed the mobile/race-direct-and-relay branch from 88551ac to 7817d86 Compare September 7, 2026 08:42
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The mobile transport now races direct and relay connections from reconnect start. Direct winners can adopt immediately, while losing relay sessions are withdrawn without extra backoff. A damping component controls repeated lost races and adapts when direct connectivity returns. Credential rotation uses a dedicated collaborator. Foreground and background transitions invoke immediate direct probes. Relay-session withdrawal and E2EE close behavior receive additional coverage.

Merge Risk: 🟡 Moderate · up to e7087

A failed relay-host save after credential rotation can leave recovery dialing an outdated relay endpoint. Resolve this partial-success path before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides strong technical context and verification details, but it omits most required template sections, including ELI5, Linked Issue with a Fixes reference, Visual Proof or N/A, Test… Update the description to include every required template section. Add an explicit Linked Issue entry using Fixes #..., provide Visual Proof or state N/A with a reason, complete the Testing section and platform details, address AI Discl…
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.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: direct and relay dials now race from t=0 on reconnect.
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 provides strong technical context and verification details, but it omits most required template sections, including ELI5, Linked Issue with a Fixes reference, Visual Proof or N/A, Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist confirmations.

Resolution

Update the description to include every required template section. Add an explicit Linked Issue entry using Fixes #..., provide Visual Proof or state N/A with a reason, complete the Testing section and platform details, address AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist items, and retain the existing technical explanation and verification results.

  • 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.

@Jinwoo-H
Jinwoo-H force-pushed the mobile/race-direct-and-relay branch from 7817d86 to e708717 Compare September 7, 2026 10:06
@Jinwoo-H
Jinwoo-H changed the base branch from main to mobile/relay-connect-critical-path September 7, 2026 10:06

@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

The delta since the prior review is a rebase onto the reopened phase-1 head (mobile/relay-connect-critical-path, which carries #19280's review fixes) plus one new commit that reconciles the direct-probe test fixture with the race-era hooks. The transport code is otherwise unchanged from the previously reviewed version.

  • Rebased onto the phase-1 head — the base moved from main back to mobile/relay-connect-critical-path; DirectReturnProbe's production code is byte-identical apart from the clear() change below.
  • Direct-probe fixture reconciled — e7087173d9 supplies the canDial and adoptsOutright hooks the race introduces, with adoptsOutright: () => false keeping these tests on the hysteresis (live-relay) path, so the fixture no longer throws at the first dial.
  • clear() also resets the deferred re-arm — DirectReturnProbe.clear() now nulls deferredDelayMs alongside the timer, so a cleared probe cannot resurrect a stale deferred schedule. In every current call path this is defensive: probeNow() only reaches clear() when no probe is in flight (the deferral is already consumed), and the external callers (background(), stop()) run with canSchedule() already false.

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

@Jinwoo-H

Jinwoo-H commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: a47e8eb4-9d00-410d-8d34-61a61b9b9179

📥 Commits

Reviewing files that changed from the base of the PR and between d9073cf and e708717.

📒 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; 3 remain after this review.

Comment on lines +56 to +57
refreshed = true
await args.persistResolvedRelay(result.relay)

@coderabbitai coderabbitai Bot Sep 7, 2026 •

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep relay-host persistence in the refresh success path.

run adopts the new bundle and sets refreshed before persistResolvedRelay() completes. If saveHost rejects, finally still clears the fresh-credential gate. The durable bundle is fresh, but this.host.relay remains stale. A later run(false) can skip rotation, so recovery can dial the stale endpoint. Set success only after host persistence succeeds, and retain and retry the resolved relay before releasing the gate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The read of the code is correct, but this is pre-existing behaviour that this PR moved rather than introduced, so I am not changing it here.

mobile-relay-credential-refresh.ts is a verbatim extraction of rotateCredentialIfNeeded from the supervisor. The same ordering is on main today at mobile/src/transport/mobile-endpoint-supervisor.ts:325-328:

      this.bundle = result.bundle
      // Why: a scheduled rotation can finish after the old credential enters the rejection gate.
      credentialRefreshed = true
      this.host = await persistRelayHost(this.host, result.relay, this.dependencies.saveHost)

Same catch, same finally, same gate lift. The extraction changes where the code lives, not when refreshed is set relative to the persist. A git show origin/main:mobile/src/transport/mobile-endpoint-supervisor.ts diffed against the new class shows the body unchanged apart from the dependency injection.

On the substance: the flagged window needs saveHost to reject after a successful rotation, which leaves host.relay stale while the bundle is durable, and mobileRelayCredentialNeedsRotation then short-circuits later unforced runs. That is worth fixing, and it is worth fixing on its own so the change is reviewable against the rotation and rehome tests rather than buried in a reconnect-latency PR. This branch is a stacked, held perf change, so widening it to alter credential-persistence semantics is the wrong place.

Flagging it for the owner's mobile pass as a separate item rather than silently folding it in.

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.

@Jinwoo-H, thanks for the detailed verification.

The ordering is pre-existing behavior, and this PR only extracts it into MobileRelayCredentialRefresh. The persistence failure case remains valid, but it is out of scope for this reconnect-latency change.

Would you like me to open a GitHub follow-up issue for the mobile owner? The issue can cover retrying persistResolvedRelay() before completeRefresh() releases the fresh-credential gate.

🐇


✏️ Learnings added
Learnt from: Jinwoo-H
Repo: stablyai/orca PR: 19256
File: mobile/src/transport/mobile-relay-credential-refresh.ts:56-57
Timestamp: 2026-09-07T10:50:30.213Z
Learning: In `mobile/src/transport/mobile-relay-credential-refresh.ts`, `MobileRelayCredentialRefresh.run()` preserves the pre-existing ordering from `rotateCredentialIfNeeded` in `mobile/src/transport/mobile-endpoint-supervisor.ts`: it adopts the rotated credential bundle and marks the refresh successful before `persistResolvedRelay()` completes. A failure to persist the resolved relay can leave the stored relay endpoint stale while the new bundle is durable. This behavior should be fixed in a separate credential-persistence change, not in PR `#19256`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, please do not open an issue. This whole stack is held for the owner's mobile review pass, and the follow-up is theirs to schedule. It is recorded in the handoff notes on this thread, which is enough to pick it up.

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.

@Jinwoo-H, understood. I will not open a follow-up issue.

The handoff notes on this thread identify the credential-persistence follow-up for the mobile owner’s review pass. The finding remains deferred outside PR #19256.


🧠 Learnings used
Learnt from: Jinwoo-H
Repo: stablyai/orca PR: 19256
File: mobile/src/transport/mobile-relay-credential-refresh.ts:56-57
Timestamp: 2026-09-07T10:50:32.287Z
Learning: In `mobile/src/transport/mobile-relay-credential-refresh.ts`, `MobileRelayCredentialRefresh.run()` preserves the pre-existing ordering from `rotateCredentialIfNeeded` in `mobile/src/transport/mobile-endpoint-supervisor.ts`: it adopts the rotated credential bundle and marks the refresh successful before `persistResolvedRelay()` completes. A failure to persist the resolved relay can leave the stored relay endpoint stale while the new bundle is durable. This behavior should be fixed in a separate credential-persistence change, not in PR `#19256`.

You are interacting with an AI system.

…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.
@Jinwoo-H
Jinwoo-H force-pushed the mobile/race-direct-and-relay branch from e708717 to 310915d Compare September 7, 2026 11:08
@Jinwoo-H
Jinwoo-H deleted the branch mobile/relay-connect-critical-path September 7, 2026 17:12
@Jinwoo-H Jinwoo-H closed this Sep 7, 2026
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