Repository navigation
fix(mobile-relay): back off relay reconnects to stop cellular connect/disconnect churn - #9460
Conversation
…/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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRelay recovery now uses 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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.
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 winRecover the relay if it dropped while probing the direct link.
If the active relay connection drops while
probeDirectis running,onStateChangewill fire and invokerecoverRelay(). However, becausethis.operationInFlightistrue,recoverRelay()will return early and drop the event, meaning no backoff timer gets scheduled. OnceprobeDirectfinishes and releases the lock, the client remains disconnected and recovery stalls permanently until the next foreground event.Add a fallback check in the
finallyblock to triggerrecoverRelay()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
📒 Files selected for processing (4)
mobile/src/transport/mobile-endpoint-supervisor.test.tsmobile/src/transport/mobile-endpoint-supervisor.tsmobile/src/transport/mobile-relay-lease-rotation-timer.tsmobile/src/transport/mobile-relay-reconnect-backoff.ts
There was a problem hiding this comment.
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 winFix timer re-arming for fatal recovery states.
When
registerFailureprocesses a fatal error, it correctly callsclearTimer(). However, becausenextAttemptAtwas just updated to the future (now + delay), any subsequent call toshouldDefer()(e.g., from the supervisor'srecoverRelaymethod) will evaluatenow < nextAttemptAtas true and inadvertently callscheduleRetry(). This re-arms the timer and creates a retry loop, defeating the intended cancellation.Set
nextAttemptAttoInfinityfor fatal errors and explicitly preventscheduleRetryfrom 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 winVerify
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
📒 Files selected for processing (4)
mobile/src/transport/mobile-endpoint-supervisor.test.tsmobile/src/transport/mobile-endpoint-supervisor.tsmobile/src/transport/mobile-relay-reconnect-controller.test.tsmobile/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
Manual mobile / Electron QAValidated the final PR head
Backward-compatibility / performance review
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. ScreenshotsElectron exact-head instance after the phone paired (no QR/token shown): iOS exact-head build connected to the isolated Electron host after a full app relaunch: |
…/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


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
mobileRelayRecoveryForhad no production caller.This PR now:
PEER_DROPPED (4408)andLIMIT_EXCEEDED (4429);onclose;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.handshakingstate does not trigger relay failover;4429close waits for backoff before replacement;HOST_OFFLINEdoes not create a polling timer;tsc --noEmit, fulloxlint, and fulloxfmt --check: clean.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
handshakingstate 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 with4401.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
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.4408/4429closes, and relay drops racing direct probes or credential persistence.config/reliability-gates.jsonchas no dedicated mobile-relay recovery gate. The provider-level tests and full mobile suite are the PR gate.RelayOuterError, allowing recovery policy and tests to distinguish failure classes.Notes
The relay cell service that emits
4408/4429is outside this repository. Its behavior is represented by the shared close-code contract and deterministic client-side fault injection.