Skip to content

fix(mobile-relay): back off relay reconnects to stop cellular connect/disconnect churn - #9460

Merged
brennanb2025 merged 13 commits into
mainfrom
brennanb2025/cellular-relay-session-disconnect
Jul 22, 2026
Merged

brennanb2025 merged 13 commits into
mainfrom
brennanb2025/cellular-relay-session-disconnect

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A phone using the relay on cellular could repeatedly connect and disconnect after a carrier NAT rebind or Wi-Fi/cellular handoff. Relay recovery had no backoff, and the close-code recovery contract in mobileRelayRecoveryFor had no production caller.

This PR now:

  • uses a full-jitter exponential cooldown (250 ms floor, 30 s ceiling) for relay resume failures, including PEER_DROPPED (4408) and LIMIT_EXCEEDED (4429);
  • treats a network revival nudge as authority to replace an apparently connected relay, covering half-open sockets that never publish onclose;
  • records close codes from the active relay before opening a replacement, not only failures from the replacement dial;
  • preserves recovery when a relay drops while a direct probe or post-migration credential persistence owns the operation mutex;
  • cancels stale retry timers when direct connectivity wins or recovery requires host revival/fresh credentials;
  • keeps fatal recovery states event-gated and forces rejected-credential rotation only after direct connectivity returns;
  • prevents revival nudges from bypassing failed lease-rotation cooldowns or async cleanup races from recreating timers; and
  • keeps lease rotation and reconnect backoff in separate single-timer controllers.

Screenshots

Not applicable; this is a transport lifecycle change with no UI changes.

Testing

  • mobile: 287 test files passed; 2,078 tests passed and 2 skipped.
  • Deterministic regression coverage proves:
    • a half-open connected relay is replaced on a network handoff;
    • a direct handshaking state does not trigger relay failover;
    • five repeated revival nudges open zero additional sockets during cooldown;
    • current/grace bundles open one socket per cooldown for capacity failures;
    • a rejected current credential is skipped on grace cooldown retries and rotated after direct connectivity returns;
    • a fatal lease-replacement gate survives a later close from the still-active old relay;
    • generic transport/director failures do not spend a second attempt on the grace credential;
    • lease rotation cannot bypass an active relay failure cooldown;
    • post-auth credential persistence failures do not reopen healthy relays or poison backoff;
    • an active 4429 close waits for backoff before replacement;
    • rapid authenticated relay drops preserve the 250 → 500 → 1,000 ms exponential progression;
    • relay drops during both direct probing and post-migration persistence recover after the mutex is released;
    • HOST_OFFLINE does not create a polling timer;
    • retry state owns at most one timer and is cleared after direct connectivity wins;
    • host-offline and rejected-credential outcomes cannot re-arm from ordinary state checks or forced lease retries;
    • background/stop races leave zero reconnect or lease timers; and
    • revival nudges stay inside a failed forced-rotation cooldown.
  • Shared mobile relay close-code contract: 4 tests passed.
  • Mobile tsc --noEmit, full oxlint, and full oxfmt --check: clean.
  • Earlier PR smoke evidence: the iOS simulator bundled and loaded the change. A simulator cannot reproduce a physical cellular NAT rebind.

AI Review Report

The review found and fixed additional gaps beyond the original backoff implementation: the reported half-open socket path was not exercised, active relay close codes bypassed backoff, a relay drop during post-migration persistence could be lost behind the operation mutex, a transient direct handshaking state could be misclassified as a failover signal, and short-lived authenticated relay sessions reset the exponential streak before proving stability. It also removed stale timer wakes after direct recovery and non-retryable relay outcomes, kept fatal gates sticky across old-session closes, and stopped redialing credentials already rejected with 4401.

Security Audit

No credential format, storage, trust boundary, encryption, logging payload, or server API changed. Resume credentials remain in the existing secure-store path. The change only controls client-side connection lifecycle and timers.

Reliability / performance

  • Invariant — mobile-relay.recovery-liveness: while foregrounded and disconnected, relay recovery is in flight, cooldown-scheduled, waiting for an explicit external signal required by policy, or handed off when a competing operation releases the mutex.
  • Failure source: cellular NAT/network handoffs, active relay 4408/4429 closes, and relay drops racing direct probes or credential persistence.
  • Oracle: deterministic injected-clock tests assert exact socket-open counts and timer counts at the cooldown boundary.
  • Gate: accepted manifest gap; config/reliability-gates.jsonc has no dedicated mobile-relay recovery gate. The provider-level tests and full mobile suite are the PR gate.
  • Provider/platform coverage: mobile/relay is covered by injected-session tests. Local/daemon PTY, SSH/remote, WSL, and desktop macOS/Linux/Windows paths are unaffected; no filesystem, process, shell, or platform-specific path behavior changed.
  • Performance budget: no polling, scans, subprocesses, provider fanout, persistent caches, or unbounded buffers were added. Repeated nudges reuse one bounded retry timer; direct success and non-retryable policy outcomes cancel it. Capacity/session and generic transport/director failures do not spend a second immediate socket attempt on the grace credential. A rejected current version is retained only for the bounded current/grace credential set, skipped on later cooldown attempts, and cleared after durable direct rotation. Lease rotation also honors an existing recovery cooldown. Rapid authenticated drops retain their failure streak; an authenticated relay that survives the ceiling-length stability window resets it without adding a timer.
  • Diagnostics: relay close codes remain available as RelayOuterError, allowing recovery policy and tests to distinguish failure classes.
  • Residual gap: physical cellular NAT rebinding and Wi-Fi/cellular handoff behavior remains unproved by an emulator.

Notes

The relay cell service that emits 4408/4429 is outside this repository. Its behavior is represented by the shared close-code contract and deterministic client-side fault injection.

…/disconnect churn

On cellular, the relay path re-dialed instantly on every network flap: a
NAT rebind / Wi-Fi<->cellular handoff silently kills the socket, the
revival trigger treats it as 'link came back' and calls recoverRelay(),
and the relay cell answers the overlapping resume with PEER_DROPPED (4408)
or LIMIT_EXCEEDED (4429). The session collapsed every close to a plain
'disconnected' and re-dialed with no delay, so the phone ping-ponged
connect/disconnect. The documented recovery contract (mobileRelayRecoveryFor,
which prescribes fullJitter backoff) had no callers.

- Add RelayReconnectBackoff: full-jitter exponential backoff (250ms floor,
  30s ceiling) that debounces re-dials via a cooldown window and wires up
  mobileRelayRecoveryFor. Reset on a successful migrate and on a genuine
  background->foreground transition (not on repeat foreground nudges).
- Extract the lease-rotation timer into RelayLeaseRotationTimer so the
  supervisor stays under max-lines (the direct-probe path can't be split
  out — it shares the operationInFlight mutex with recoverRelay).
- Add a deterministic test: repeated network-flap nudges re-dial instantly
  before the fix and are suppressed by the backoff window after.
@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Relay recovery now uses RelayReconnectController for failure classification, cooldowns, jittered retries, and lifecycle handling. RelayLeaseRotationTimer schedules proactive lease replacement and short recovery retries. MobileEndpointSupervisor integrates both utilities across startup, foreground transitions, credential recovery, direct probing, relay migration, and shutdown. Tests cover mutex-held relay drops, half-open relay replacement, close failures, host-offline relays, backoff timing, and foreground recovery.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly summarizes the main change: adding relay reconnect backoff to reduce cellular churn.
Description check ✅ Passed The description covers all required sections and provides detailed summary, testing, review, security, and notes.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
mobile/src/transport/mobile-endpoint-supervisor.ts (1)

293-300: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Recover the relay if it dropped while probing the direct link.

If the active relay connection drops while probeDirect is running, onStateChange will fire and invoke recoverRelay(). However, because this.operationInFlight is true, recoverRelay() will return early and drop the event, meaning no backoff timer gets scheduled. Once probeDirect finishes and releases the lock, the client remains disconnected and recovery stalls permanently until the next foreground event.

Add a fallback check in the finally block to trigger recoverRelay() if the endpoint is left disconnected, ensuring the recovery loop can resume.

🛠️ Proposed fix to prevent stalled recovery
     finally {
       successful?.client.close()
       this.operationInFlight = false
       if (this.relayRotationPending) {
         void this.recoverRelay(true)
+      } else if (this.logical.getState() !== 'connected') {
+        void this.recoverRelay()
       }
       this.scheduleDirectProbe()
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3b8ce29f-caa0-4ed9-b8ff-e23991389b35

📥 Commits

Reviewing files that changed from the base of the PR and between b19dccd and adfc938.

📒 Files selected for processing (4)
  • mobile/src/transport/mobile-endpoint-supervisor.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor.ts
  • mobile/src/transport/mobile-relay-lease-rotation-timer.ts
  • mobile/src/transport/mobile-relay-reconnect-backoff.ts

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
mobile/src/transport/mobile-relay-reconnect-controller.ts (1)

109-147: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Fix timer re-arming for fatal recovery states.

When registerFailure processes a fatal error, it correctly calls clearTimer(). However, because nextAttemptAt was just updated to the future (now + delay), any subsequent call to shouldDefer() (e.g., from the supervisor's recoverRelay method) will evaluate now < nextAttemptAt as true and inadvertently call scheduleRetry(). This re-arms the timer and creates a retry loop, defeating the intended cancellation.

Set nextAttemptAt to Infinity for fatal errors and explicitly prevent scheduleRetry from setting timers for infinite delays.

🔒️ Proposed fix to prevent re-arming
     // Why: these failures require host revival or fresh credentials, not a retry loop.
     if (
       recovery?.kind === 'wait-for-host-revival' ||
       recovery?.kind === 'disable-relay-credential'
     ) {
+      this.nextAttemptAt = Infinity
       this.clearTimer()
       return
     }
     this.scheduleRetry(delay)
   }

   reset(): void {
     this.consecutiveFailures = 0
     this.nextAttemptAt = 0
     this.clearTimer()
   }

   clear(): void {
     this.clearTimer()
     this.activeSession = null
   }

   private clearTimer(): void {
     if (this.timer) {
       this.dependencies.clearTimer(this.timer)
       this.timer = null
     }
   }

   private scheduleRetry(delayMs?: number): void {
-    if (this.timer) {
+    if (this.timer || this.nextAttemptAt === Infinity) {
       return
     }
     const delay = delayMs ?? Math.max(0, this.nextAttemptAt - this.dependencies.now())
🧹 Nitpick comments (1)
mobile/src/transport/mobile-relay-reconnect-controller.test.ts (1)

25-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verify shouldDefer() does not re-arm timers after a fatal failure.

To ensure that the timer cancellation for fatal errors is not accidentally bypassed by a subsequent check, assert that shouldDefer() correctly suppresses the redial without scheduling a new timer. This prevents regressions related to the re-arming bug in the controller.

🧪 Proposed test assertions
     reconnect.registerFailure(new RelayOuterError(4404))
     expect(vi.getTimerCount()).toBe(0)
+
+    // Verify that subsequent state checks do not accidentally re-arm the timer
+    expect(reconnect.shouldDefer()).toBe(true)
+    expect(vi.getTimerCount()).toBe(0)
+
     vi.runAllTimers()
     expect(onRetry).not.toHaveBeenCalled()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 26204b7b-83cc-4d78-850e-80aeb32e6cf4

📥 Commits

Reviewing files that changed from the base of the PR and between d36eb43 and 17e29cc.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Manual mobile / Electron QA

Validated the final PR head cdb7d6620c with an iPhone 17 Pro simulator (iOS 26.5) and an isolated Electron instance launched from this exact worktree.

  • Paired the PR mobile build to the PR Electron build over an explicit LAN interface and confirmed the direct WebSocket/E2EE path connected.
  • Fully terminated and relaunched the mobile app; the saved host reconnected and remained usable, exercising persisted pairing and cold-start recovery.
  • Exercised background/foreground navigation and verified the app remained responsive with no redbox or renderer console errors.
  • Confirmed the Electron Mobile settings surface records the paired device. The QR/pairing credential is intentionally omitted from screenshots.

Backward-compatibility / performance review

  • Compatibility verdict: clean. The diff is mobile-client-only; it changes no desktop/shared wire contract, persisted schema, route/deep-link shape, native project, package manifest, or SSH/provider behavior. New mobile + old desktop and old mobile + new desktop therefore retain the existing protocol surface.
  • Reconnect behavior is event-driven for terminal host/auth states and uses one bounded backoff timer; the latest change resets the failure streak only after an authenticated relay survives the stability window, avoiding both hot-loop polling and false backoff resets after slow failed dials.
  • Full mobile suite: 287 files passed; 2,078 tests passed, 2 skipped. Targeted reconnect/supervisor suite: 38 passed. Typecheck, lint, formatting, diff checks, and max-lines ratchet all pass.
  • Latest GitHub verify job passed, including lint, typecheck, Git compatibility, tests, unpacked build, and packaged CLI smoke.

The isolated Electron profile was deliberately unsigned-in, and the iOS simulator cannot reproduce a physical cellular NAT rebind, so this run does not claim an end-to-end production relay/cellular test. The relay state machine and timer behavior are covered by the regression suite.

Screenshots

Electron exact-head instance after the phone paired (no QR/token shown):

Electron Mobile settings with paired device

iOS exact-head build connected to the isolated Electron host after a full app relaunch:

iOS app connected to Host 2 over Direct LAN

@brennanb2025
brennanb2025 merged commit 261a7b7 into main Jul 22, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…/disconnect churn (stablyai#9460)

* fix(mobile-relay): back off relay reconnects to stop cellular connect/disconnect churn

On cellular, the relay path re-dialed instantly on every network flap: a
NAT rebind / Wi-Fi<->cellular handoff silently kills the socket, the
revival trigger treats it as 'link came back' and calls recoverRelay(),
and the relay cell answers the overlapping resume with PEER_DROPPED (4408)
or LIMIT_EXCEEDED (4429). The session collapsed every close to a plain
'disconnected' and re-dialed with no delay, so the phone ping-ponged
connect/disconnect. The documented recovery contract (mobileRelayRecoveryFor,
which prescribes fullJitter backoff) had no callers.

- Add RelayReconnectBackoff: full-jitter exponential backoff (250ms floor,
  30s ceiling) that debounces re-dials via a cooldown window and wires up
  mobileRelayRecoveryFor. Reset on a successful migrate and on a genuine
  background->foreground transition (not on repeat foreground nudges).
- Extract the lease-rotation timer into RelayLeaseRotationTimer so the
  supervisor stays under max-lines (the direct-probe path can't be split
  out — it shares the operationInFlight mutex with recoverRelay).
- Add a deterministic test: repeated network-flap nudges re-dial instantly
  before the fix and are suppressed by the backoff window after.

* fix(mobile-relay): recover drops during direct probes

* fix(mobile-relay): recover half-open relay sessions

* fix(mobile-relay): preserve direct handshakes

* fix(mobile-relay): keep recovery retries bounded

* fix(mobile-relay): avoid redundant recovery dials

* fix(mobile-relay): keep all retries inside cooldown

* fix(mobile-relay): close recovery lifecycle races

* fix(mobile-relay): preserve in-progress direct auth

* fix(mobile-relay): preserve fatal recovery gates

* fix(mobile-relay): preserve backoff across unstable resumes

* fix(mobile-relay): close remaining recovery lifecycle gaps

* fix(mobile-relay): reset backoff only after stable relay
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