Skip to content

fix(relay): abandon dead client accepts, jitter and lengthen the control lease, fail direct probes fast - #18959

Merged
Jinwoo-H merged 4 commits into
mainfrom
relay-reconnect-fleet-accept-v2
Sep 6, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
relay-reconnect-fleet-accept-v2

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​552 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​550
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​108 $\color{#cf222e}{\Huge{\mathbf{−}}}$​9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​99

ELI5

The phone asks the relay to connect it to the Mac; the relay checks a shared database first. Under the 2026-09-04 lock storm that check took longer than the phone waited, so the relay finished work for a phone that had already hung up (the already_bound log line). Separately, every Mac renewed its relay link on a fixed 55-minute clock, so hundreds of Macs that reconnected together after a cell restart renewed together forever and hit the same lock in waves. And the phone spent 3.5 s retrying a dead Wi-Fi path before trying the relay.

This PR: stops the relay working for phones that left, spreads the renewals out and makes them six times rarer, and lets the phone give up on dead Wi-Fi at once.

Changes

  • Relay accept abandonment: acceptClient checks the client socket after each serialized DB step and stops once the phone closed, releasing the capacity reservation and any activity lease it already took. New observability event orca_relay_client_accept_abandoned {stage, elapsedMs}.
  • Control lease 6 h ± 30 min (was flat 55 min). The lease bounds how long a host lingers on a cell after a missed drain and is the only passive rebalancing, so it stays finite; 6 h cuts control-activation traffic on the contended cell-inventory lock ~6x. The relay JWT (5 min) and the 75 s silence watchdog are enforced separately. Symmetric jitter walks same-minute reconnect cohorts apart. Wire-safe: the relay already sends leaseExpiresAt in the hello ack and desktops schedule from it; fix(desktop): never replay a refresh token after a timeout; jitter relay lease renewal #18719's proportional ±10 % desktop jitter scales with it.
  • Mobile direct-probe fail-fast: a dead direct path fails immediately instead of after 3.5 s of retries. The supervisor test moved to a sibling spec (mobile-endpoint-supervisor-direct-probe.test.ts) because the existing file is at the max-lines cap.

Supersedes #18565 (rebased onto main; the desktop rotation change there was dropped because #18719 shipped a proportional version). Ships in Roll 2 per cloud/docs/relay-roll2-plan-2026-09.md (#18958).

Verification

  • relay: 3 targeted specs 39/39; full relay app suite 508 passed, 87 skipped (Postgres suites, 55440 down); tsc --noEmit clean.
  • mobile: src/transport 683 passed; tsc --noEmit clean; oxfmt --check clean.
  • root src/main/runtime/relay 113 passed (untouched by this PR).
  • oxlint clean on changed dirs; check:code-quality:changed 0 findings.

…he control lease

The accept runs several serialized Postgres calls behind the contended
cell-inventory lock, and phones bound their dial. Finishing that work for a
phone that had already left acquired (and leaked for 90s) an activity lease and
then failed at bind with host_data_reservation_already_bound. Check the client
socket between the DB steps and unwind what was taken, reporting the stage on
orca_relay_client_accept_abandoned.

Jitter the control lease grant so a cohort that reconnected in the same minute
(a cell recreate dumps hundreds at once) walks apart instead of rebinding
together every cycle.

On the phone, treat a probe session that enters 'reconnecting' as a failed
probe: it is the direct client's own backoff after a dead-LAN 1006, and waiting
it out held the supervisor's operation mutex for the full 12s bound.
The lease bounds how long a host lingers on a cell after a missed drain, and
rebinding it is the only passive rebalancing we have, so it stays finite. 6h
keeps both properties while cutting control-activation traffic on the contended
cell-inventory lock ~6x. The relay JWT (5 min, refreshed by the desktop) and the
75s silence watchdog are enforced separately, so the longer grant authorizes
nothing extra. The jitter widens with it, to +/-30 min.
@coderabbitai

coderabbitai Bot commented Sep 6, 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: 8d0ba84b-0688-44ee-9fa7-6cd49526f7c0

📥 Commits

Reviewing files that changed from the base of the PR and between 32ff385 and 7ecb3d6.

📒 Files selected for processing (3)
  • cloud/apps/relay/src/host-session-client-accept.test.ts
  • mobile/src/transport/mobile-direct-endpoint-probe.test.ts
  • mobile/src/transport/mobile-direct-endpoint-probe.ts

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


📝 Walkthrough

Walkthrough

The relay now stops abandoned client accepts during assignment, credential, and activity stages, releases staged resources, and records abandonment metrics. Control leases now use six-hour durations with symmetric jitter and injectable randomness. Mobile direct probes now allow a two-second reconnect grace period, including one extension during handshaking, while relay recovery can proceed during direct redial. Tests cover cleanup, metrics, lease jitter, and mobile recovery.

Merge Risk: ⚪ Minimal · up to 7ecb3

The change releases abandoned relay accept resources, spreads control lease renewals, and improves mobile direct-path recovery while retaining bounded failure behavior. No current merge-blocking risk is identified.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a useful ELI5 summary, change rationale, implementation details, linked PR references, and verification results. It omits several required template sections, including an expl… Complete the required template sections. Add an explicit Fixes #<issue> entry, provide Visual Proof attachments or write N/A with a reason, complete the Testing checklist with platforms tested, and fill in Review, Agent skill upstream b…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 8 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 summarizes the three primary changes: relay accept abandonment, control lease jitter and extension, and faster direct-probe failure.
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 a useful ELI5 summary, change rationale, implementation details, linked PR references, and verification results. It omits several required template sections, including an explicit Linked Issue entry using Fixes #, Visual Proof or N/A, the Testing checklist, Review, Agent skill upstream boundary, Notes, and the final Checklist.

Resolution

Complete the required template sections. Add an explicit Fixes #&lt;issue&gt; entry, provide Visual Proof attachments or write N/A with a reason, complete the Testing checklist with platforms tested, and fill in Review, Agent skill upstream boundary, Notes, and the final Checklist. Rename or supplement Changes and Verification with the required What Changed and Testing 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 new issues found.

Reviewed changes

  • Relay accept abandonment — acceptClient now checks the client socket after each serialized Postgres step and bails out once the phone hung up, releasing the capacity reservation, failing the credential reservation, and releasing any activity lease already taken. Cleaned-up resource accounting is correct: capacityReservation.release() (connection ledger) and failReservation (credential) are distinct, abandonedByClient returns before the happy-path socket.once('close') handler is registered so nothing double-releases, and the best-effort cleanup matches the existing close-handler idiom with durable expiry fallback.
  • Control lease 6h ± 30min — controlLeaseExpiresAt() produces a uniform [mean-jitter, mean+jitter) grant at both the rebind and new-session paths. I confirmed the longer lease authorizes nothing extra: the heartbeat tick enforces the relay JWT expiry and the 75s silence watchdog independently of leaseExpiresAt, and the hello ack already ships leaseExpiresAt so desktops schedule from the server value (wire-safe, no opcode/field change).
  • Observability — optional recordClientAcceptAbandoned(stage, elapsedMs) feeds two new metric deltas (clientAcceptsAbandonedByStage, clientAcceptAbandonedMsMax) with a clean reset-on-flush, plus a structured orca_relay_client_accept_abandoned log line that deliberately omits relayHostId.
  • Mobile direct-probe fail-fast — waitForAuthenticatedSession now rejects on reconnecting, so a dead-LAN probe resolves null immediately instead of holding the supervisor mutex through the 12s bound. The new tests are meaningful (they fail against the old behavior, and the supervisor spec's expect(vi.getTimerCount()).toBe(0) pins no leaked 12s timer).

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

…indow

'reconnecting' is published on any socket close, so rejecting on it outright
turned a single access-point flap into a booked direct failure and a 60s
cooldown. Give the first 'reconnecting' a 2s grace in which a 'connected'
transition still resolves; a dead LAN still fails in ~2s rather than holding the
supervisor's operation mutex for the 12s bound.

The abandoned accept held its activity lease for the 10s attach deadline, not
90s -- the attach timer is armed before bind throws and already unwinds it.

Also cover the assignment-stage check that guards reserveCredential, and drop a
spread assertion the two exact-value assertions above already imply.

@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

  • Direct-probe reconnect grace window — waitForAuthenticatedSession now grants a one-shot 2s grace (RECONNECT_GRACE_MS) on the first reconnecting state instead of rejecting immediately, so a single access-point flap that the first redial recovers no longer books a direct failure; a second reconnecting (or disconnected/auth-failed) still fails fast, and a dead LAN settles in ~2s rather than the full 12s bound. Confirmed against direct-rpc-client.ts, which republishes reconnecting on each failed redial, so a genuinely dead path still rejects on the second dial.
  • Relay abandon coverage + comment correction — added the "slow same-cell assignment resolve" abandon test, corrected the leak-window comment (the activity lease is held for the 10s attach deadline, not 90s), and dropped a now-redundant jitter-band assertion. No production relay behavior changed in this delta.

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

… band top

The redial fires at 500ms but 'connected' waits on the Noise handshake and a
capability RPC, so one 2s window is too tight for real work. A 'handshaking'
transition is evidence the peer answered, so extend the grace once; a stalled
handshake still fails at ~3.5s, far inside the 12s bound.

The longest-lease case only had an upper bound, which a jitter clamped to one
side would satisfy. Pin it to the exact top of the band instead, and assert the
assignment resolve ran so the third-guard test cannot pass vacuously.

@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

  • Direct-probe handshake grace re-arm — waitForAuthenticatedSession now clears and re-arms its one-shot RECONNECT_GRACE_MS timer exactly once (graceExtended guard) when handshaking arrives, so a redial that opens TCP and then completes the Noise handshake plus capability RPC is no longer killed by the 2s grace. Verified handshaking is published from socket.onopen in rpc-client-socket-session.ts, i.e. proof the peer answered; a stalled handshake still fails at ~4s.
  • Jitter band top pinned exactly — the lease-jitter test now asserts the exact now + CONTROL_LEASE_MS + longestOffset top of the band instead of an upper bound, proving the jitter is symmetric rather than one-sided.
  • Accept-test guard clarified — the slow same-cell assignment test now asserts resolveAssignment was reached, proving the abandon fires at the post-resolve guard rather than the first one.
  • Two new handshake-grace tests — one confirms the grace extends exactly once past a handshake; the other confirms a restarted handshake does not buy a second extension and still fails at ~4s.

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

@Jinwoo-H
Jinwoo-H merged commit 61b09b7 into main Sep 6, 2026
25 checks passed
@Jinwoo-H
Jinwoo-H deleted the relay-reconnect-fleet-accept-v2 branch September 6, 2026 00:47
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…rol lease, fail direct probes fast (stablyai#18959)

* fix(relay): abandon a client accept once the phone hangs up; jitter the control lease

The accept runs several serialized Postgres calls behind the contended
cell-inventory lock, and phones bound their dial. Finishing that work for a
phone that had already left acquired (and leaked for 90s) an activity lease and
then failed at bind with host_data_reservation_already_bound. Check the client
socket between the DB steps and unwind what was taken, reporting the stage on
orca_relay_client_accept_abandoned.

Jitter the control lease grant so a cohort that reconnected in the same minute
(a cell recreate dumps hundreds at once) walks apart instead of rebinding
together every cycle.

On the phone, treat a probe session that enters 'reconnecting' as a failed
probe: it is the direct client's own backoff after a dead-LAN 1006, and waiting
it out held the supervisor's operation mutex for the full 12s bound.

* perf(relay): lengthen the control lease to 6h

The lease bounds how long a host lingers on a cell after a missed drain, and
rebinding it is the only passive rebalancing we have, so it stays finite. 6h
keeps both properties while cutting control-activation traffic on the contended
cell-inventory lock ~6x. The relay JWT (5 min, refreshed by the desktop) and the
75s silence watchdog are enforced separately, so the longer grant authorizes
nothing extra. The jitter widens with it, to +/-30 min.

* fix(relay): let one flap recover the direct probe; correct the leak window

'reconnecting' is published on any socket close, so rejecting on it outright
turned a single access-point flap into a booked direct failure and a 60s
cooldown. Give the first 'reconnecting' a 2s grace in which a 'connected'
transition still resolves; a dead LAN still fails in ~2s rather than holding the
supervisor's operation mutex for the 12s bound.

The abandoned accept held its activity lease for the 10s attach deadline, not
90s -- the attach timer is armed before bind throws and already unwinds it.

Also cover the assignment-stage check that guards reserveCredential, and drop a
spread assertion the two exact-value assertions above already imply.

* fix(relay): extend the probe grace once on a handshake; pin the lease band top

The redial fires at 500ms but 'connected' waits on the Noise handshake and a
capability RPC, so one 2s window is too tight for real work. A 'handshaking'
transition is evidence the peer answered, so extend the grace once; a stalled
handshake still fails at ~3.5s, far inside the 12s bound.

The longest-lease case only had an upper bound, which a jitter clamped to one
side would satisfy. Pin it to the exact top of the band instead, and assert the
assignment resolve ran so the third-guard test cannot pass vacuously.
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