Skip to content

fix(mobile): stage-aware relay dial bound so a slow cell is not hung up on - #18518

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-reconnect-auth-timeout
Sep 3, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-reconnect-auth-timeout

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​326 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​326
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​146 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​131

Incident

2026-09-03 18:49–18:52Z, Samsung phone (mobile-rearch @ 22574ed) paired to macOS 1.4.197-adhoc over the cloud relay. After foreground return the host dot stayed grey and the phone logged relay dial failed Error: replacement session authentication timed out five times in a row (18:50:08, :32, :58, 18:51:23, :47). The desktop's relay control was healthy the whole time (host 666077865f2e, one control 1006 at 18:41:54Z, sticky reassignment to production-gce-c27 at 18:42:10Z, no drain/moved/4404).

Root cause

The phone's dial stalled inside the cell's acceptClient DB phase, before conn-open was ever sent to the desktop.

  • Cell c27 logged first frame handler failed host_data_reservation_already_bound at 18:50:06 and 18:51:51. That error is thrown by PendingHostDataReservation.bind, which runs only after the four serialized Postgres calls (resolveResume → assignments.resolve → reserveCredential → acquireActivity) return, and the reservation is released by the phone socket's close. So the cell finished its DB phase 2–4 s after the phone had already hung up at its flat 12 s bound.
  • c27 metrics for that window: sqlLatencyMsMax 1.1–2.1 s per 30 s sample, sqlFailuresDelta 1–11 per sample, and a stream of orca_relay_postgres_transaction_retry events with Postgres 55P03 (lock not available), on top of the fleet-wide 4401 storm adding reconnect load to the same assignment tables.
  • pendingSplices on c27 stayed 0–1, so the desktop never had an unanswered conn-open. The desktop was not involved.
  • The phone's migrateTo/waitForAuthenticated bound was a flat 12 s from dial start with no stage awareness: ConnectionState stays connecting until relay-hello, so a socket that opened and was accepted (cell working slowly) looked identical to a black-holed socket.
  • Worse, each logged failure was actually two 12 s dials: the timeout Error counted as a director-class failure in isDirectorResolutionFailure, so the phone re-resolved the same cell and dialed again before logging. Every retry landed in the same contended window. The same pattern (3 timeouts, then success on attempt 4 at 18:46:43) shows it recovers as soon as the cell gets a fast window.

Ruled out: stale cell/session, epoch mismatch, desktop splice gating, E2EE (never started). PR #18400 fixes a different trigger of the same symptom (desktop 4401 self-close → orphan → 4404); it does not cover this path and is still worth landing.

Fix (phone-side only, no wire change)

  • MobileRelayE2eeLink gains an onOpen hook fired once relay-auth is on the wire. MobileRelayRpcSession exposes a dial stage: opening → awaiting-hello → handshaking → confirming.
  • waitForAuthenticated keeps the caller's 12 s bound until the socket opens, then re-arms a per-stage budget on each advance (30 s awaiting-hello, 12 s handshaking, 35 s confirming). Budgets track the relay's own limits: 10 s host-attach deadline on top of the observed 14–16 s contended accept; 30 s resume-confirmation deadline with slack so the session's own RPC error wins.
  • The timeout error (ReplacementAuthenticationTimeoutError) carries the stalled stage and lands in the relay dial failed log line, e.g. timed out (awaiting-hello, 30s).
  • A stall past the open socket no longer counts as a director-resolution failure, so the phone stops burning a director round plus a second full wait against the same cell.

Sessions that don't report stages (direct client, older fakes) keep the flat behavior.

Tests

  • replacement-session-authentication.test.ts (new): flat bound without stages; incident replay (stage advance after 11 s survives past 12 s; each later stage re-arms); stage-named timeout; opening-stage timeout; no timer leak after settle.
  • stable-logical-rpc-client.test.ts: migrateTo honors the replacement's stages through the shipping wiring.
  • mobile-relay-rpc-session.test.ts: stage sequence across open/hello/authenticated.
  • mobile-relay-e2ee-link.test.ts: onOpen fires only after relay-auth is written, not on a failed write.
  • mobile-endpoint-supervisor-stalled-cell.test.ts (new): an awaiting-hello timeout does not re-resolve the director and logs the stage; an opening timeout still does.

Gates: pnpm tc, cd mobile && npx vitest run src/transport (88 files / 657 passed), pnpm test src/main/runtime/relay (96 passed), oxlint on changed files, pnpm run check:code-quality:changed — all green. Mobile files formatted with oxfmt.

…up on

A phone returning to foreground on 2026-09-03 logged "replacement session
authentication timed out" five dials in a row while the desktop's relay
control was live. The cell (production-gce-c27) had taken relay-auth but
its assignment/reservation transactions were lock-contended (55P03 retries,
14–16s per accept); the phone's flat 12s migrateTo bound closed the socket
2–4s before the cell finished (cell logged host_data_reservation_already_bound),
and because the timeout counted as a director-class failure the phone
re-resolved the same cell and waited 12s again before logging — every
retry landed in the same contended window.

- MobileRelayE2eeLink reports onOpen once relay-auth is on the wire;
  MobileRelayRpcSession exposes a dial stage
  (opening → awaiting-hello → handshaking → confirming).
- waitForAuthenticated keeps the caller's bound until the socket opens, then
  re-arms a per-stage budget (30s awaiting-hello, 12s handshaking, 35s
  confirming) so a reachable, slow cell is not treated as a black hole.
- The timeout error carries the stalled stage and shows up in the
  "relay dial failed" log line; a stall past the open socket no longer
  triggers the director re-resolve round.

Phone-local only: no wire change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
@coderabbitai

coderabbitai Bot commented Sep 3, 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: 927856ad-51e1-4725-8208-608f8ce3ba88

📥 Commits

Reviewing files that changed from the base of the PR and between aa78d4a and 3fc5a4c.

📒 Files selected for processing (12)
  • mobile/src/transport/mobile-endpoint-supervisor-stalled-cell.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor-support.ts
  • mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
  • mobile/src/transport/mobile-relay-e2ee-link.test.ts
  • mobile/src/transport/mobile-relay-e2ee-link.ts
  • mobile/src/transport/mobile-relay-rpc-session.test.ts
  • mobile/src/transport/mobile-relay-rpc-session.ts
  • mobile/src/transport/mobile-relay-runtime-failover.test.ts
  • mobile/src/transport/relay-dial-stage.ts
  • mobile/src/transport/replacement-session-authentication.test.ts
  • mobile/src/transport/replacement-session-authentication.ts
  • mobile/src/transport/stable-logical-rpc-client.test.ts

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


📝 Walkthrough

Walkthrough

The change adds relay dial-stage tracking across relay links and RPC sessions. Authentication waits now re-arm timers for each dial stage and report staged timeout errors. Endpoint supervision distinguishes socket-opening timeouts from relay-authentication stalls when deciding whether to re-resolve the director. Tests cover stage transitions, timeout cleanup, migration timing, retry behavior, and timeout logging.

Merge Risk: ⚪ Minimal · up to 3fc5a

Relay authentication now uses connection-stage timeout budgets and avoids unnecessary director re-resolution after a relay has opened but stalls. The covered timeout, cleanup, stage-transition, and retry behaviors indicate no remaining merge-blocking risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the incident, root cause, fix, scope, and test results, but it does not follow the repository template. It omits the required Linked Issue, Visual Proof or an explicit N/A exp… Add the missing template sections. Include a linked issue after “Fixes #”, state “N/A” with a reason for visual proof if no visual change exists, complete the Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, a…
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 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: stage-aware relay dial timeouts that prevent slow relay cells from being terminated prematurely.
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 explains the incident, root cause, fix, scope, and test results, but it does not follow the repository template. It omits the required Linked Issue, Visual Proof or an explicit N/A explanation, checklist items, review notes, agent-skill boundary statement, and other template sections.

Resolution

Add the missing template sections. Include a linked issue after “Fixes #”, state “N/A” with a reason for visual proof if no visual change exists, complete the Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

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

@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 — the stage-aware re-arm logic is sound and well-covered by tests. One design consideration to confirm before merging, nothing blocking.

Reviewed changes

  • RelayDialStageTracker (new) — a four-stage dial tracker (opening → awaiting-hello → handshaking → confirming) plus a per-stage budget table, giving waitForAuthenticated a way to tell "socket never opened" from "cell accepted the dial and is slow".
  • waitForAuthenticated re-arm — re-arms a per-stage budget on each stage advance (30s / 12s / 35s), keeps the caller's 12s bound for opening and for sessions with no stage source, and reports the stalled stage in ReplacementAuthenticationTimeoutError.
  • MobileRelayE2eeLink.onOpen — fires once relay-auth is on the wire, marking the boundary where the cell owns the wait.
  • Director-fallback gating — a timeout at a later stage no longer counts as a director-resolution failure, so the phone stops re-resolving the same cell and burning a second full dial.
  • Tests — new replacement-session-authentication and mobile-endpoint-supervisor-stalled-cell suites, plus stage-sequence, onOpen, and migrateTo-wiring coverage. Each asserts exact outcomes (stage name, budget seconds, timer-count 0), so they would fall over without the feature.

ℹ️ Backgrounding or stop() doesn't promptly cancel an in-flight slow dial

The shouldAbort predicate that withdraws an in-flight dial when the app is backgrounded or stopped is only consulted after waitForAuthenticated resolves (stable-logical-rpc-client.ts:238). With the extended per-stage budgets, a dial stalled at awaiting-hello now keeps its socket open for the full 30s budget (up to ~42s including the 12s opening bound, longer if it progresses through later stages) before cancellation kicks in — where the prior flat 12s bound capped it. This is a plausible trade-off you've already weighed (iOS background suspension freezes the timers anyway), but worth confirming the socket doesn't outlive the app's background grace on Android.

Technical details
# Background/stop cancellation runs only post-authentication-wait

## Affected sites
- mobile/src/transport/stable-logical-rpc-client.ts:238 — `shouldAbort()` is checked only after `waitForAuthenticated` settles.
- mobile/src/transport/relay-dial-stage.ts:56-60 — `RELAY_DIAL_STAGE_BUDGET_MS` extends the wait to 30s/12s/35s per stage vs. the prior flat 12s.
- mobile/src/transport/mobile-relay-background-grace.ts:106-121 — `background()` does not close the in-flight replacement session (active path isn't `relay` yet, so `suspendRelay` returns early).

## Required outcome
- Confirm a backgrounded/stopped phone doesn't hold the socket (radio/battery) for the full stage budget before `migrateTo` aborts and closes `nextSession`.

## Open questions for the human
- Is the mutex (`operationInFlight`) + open socket being held through the full stage budget after background acceptable, or should cancellation be folded into the per-stage wait (e.g. abort on `!isActive()` between stage advances)?

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

@Jinwoo-H
Jinwoo-H merged commit 4d24fb3 into main Sep 3, 2026
23 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 3, 2026
Reconciles main's structured native Codex chat (#18074) and the stage-aware
relay dial bound (#18518) with the hybrid operations layer:

- native-chat controller keeps the operations/target/disconnect-retention
  seam and routes agent-session tabs through the structured hooks; the
  active-resolution and terminal-write hooks are extracted to stay under
  the line cap
- image attachments keep the hosted attachImage/pasteImages path and add
  main's structured (paste-free) send
- bare Codex launches take the structured path only on the native client;
  hosted adapter creates stay on the adapter
- file taps resolve against the source session tab when a structured chat
  has no backing terminal
- relay session advertises client capabilities after resume confirm
- package downloader contract split out to break the import cycle the
  native code-quality audit now rejects

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…up on (stablyai#18518)

A phone returning to foreground on 2026-09-03 logged "replacement session
authentication timed out" five dials in a row while the desktop's relay
control was live. The cell (production-gce-c27) had taken relay-auth but
its assignment/reservation transactions were lock-contended (55P03 retries,
14–16s per accept); the phone's flat 12s migrateTo bound closed the socket
2–4s before the cell finished (cell logged host_data_reservation_already_bound),
and because the timeout counted as a director-class failure the phone
re-resolved the same cell and waited 12s again before logging — every
retry landed in the same contended window.

- MobileRelayE2eeLink reports onOpen once relay-auth is on the wire;
  MobileRelayRpcSession exposes a dial stage
  (opening → awaiting-hello → handshaking → confirming).
- waitForAuthenticated keeps the caller's bound until the socket opens, then
  re-arms a per-stage budget (30s awaiting-hello, 12s handshaking, 35s
  confirming) so a reachable, slow cell is not treated as a black hole.
- The timeout error carries the stalled stage and shows up in the
  "relay dial failed" log line; a stall past the open socket no longer
  triggers the director re-resolve round.

Phone-local only: no wire change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
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