Skip to content

fix(relay): survivable mobile pairing recovery + desktop assign rate gate - #16659

Merged
Jinwoo-H merged 8 commits into
mainfrom
relay-root-cause-fable5
Aug 26, 2026
Merged

Jinwoo-H merged 8 commits into
mainfrom
relay-root-cause-fable5

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​498 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​481
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​310 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​281

Client-side fixes for the mobile Relay connection-failure influx (STA-5457). One incident, four fixes, one commit each.

Root cause being fixed

The director's only reply on /v1/connect is relay-moved with the stored epoch — it has no "you're already assigned there" verb, and sticky assignments reuse the same epoch indefinitely, so equal-epoch replies are the steady state. The phone treated any non-newer move as fatal, so every pairing recovery after a transient cell-dial failure (DRAINING, 1006/network) dead-ended in <3s on released Android 0.0.44. Off-LAN, the direct candidate can't reach the desktop's private IP either → "Couldn't connect within 25s".

Changes

  1. fix(mobile): retry the stored assignment on a non-newer director move. The move is never adopted or persisted — the anti-rollback contract (requireStrictlyNewerEpoch) is untouched; the candidate re-dials the assignment the director just confirmed, with a 250ms floor. 4429 (LIMIT_EXCEEDED) deliberately stays non-recoverable: cell dials burn invite attempts server-side (reserve-before-cap ordering) and a director hop can't relieve cell load; a test pins that 4429 never reaches the director.
  2. fix(mobile): honor Retry-After when pacing recovery. /v1/resolve non-OK responses now carry status + Retry-After (clamped 120s) via RelayDirectorHttpError, floored into the existing reconnect delays — no new timers. The parser is extracted to src/shared/relay-retry-after-header.ts and reused by the desktop client.
  3. fix(mobile): attribute pairing log lines Direct:/Relay:. The pairing pane interleaves both racing candidates; unlabeled direct-candidate retries against a private LAN IP repeatedly read as Relay failures (misled users and two investigations).
  4. fix(relay): gate desktop /v1/assign at the per-host 5s rate limit. Current main's effective floor is ~0ms: full jitter draws from [0, cap], drain-path first attempts are undelayed, 400-fallbacks issue up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After timer. Production shows livelocked hosts at ~100–200 rejects per success. A shared per-host gate at the single call site closes all four bypasses; Retry-After raises it persistently; fenced callers abort stale waits.

Verification

  • Mobile transport: 82 files, 611 passed. Desktop src/main/runtime/relay/: 91 passed; full src/main/runtime: 5376 passed.
  • pnpm tc / tc:node clean; changed-code quality + React Doctor: 0 findings; oxlint (incl. max-lines) exit 0; mobile formatted with oxfmt.
  • Independent adversarial safety review passed all conditions: anti-rollback intact, close-codes contract table unchanged and now honored (4429 → backoff, no director hop), 25s pairing budget arithmetic verified (≈16–17s worst case), retained recovery codes (4409/4503) are rejected server-side before invite-credential reservation so extra re-dials burn no attempts.
  • New tests mutation-checked (gate floor, Retry-After persistence, prune, staleness abort, fallback no-re-wait; non-newer retry + no-persist + no-director-on-4429).

Notes for reviewers

  • pre-profile-pairing-coordinator.ts and mobile-relay-reconnect-controller.ts sit ~4 effective lines under the 300 max-lines cap.
  • Follow-ups deliberately out of scope: threading the 25s pairing deadline into the recovery loop; cell request timeout (30s) exceeding the pairing budget; startup journal recovery never triggers director recovery (method-gated); protocol-level fix (phone sends epoch in relay-auth, director answers "assignment-current") tracked separately; server-side 4429 disambiguation + Retry-After on cell rejections.

@coderabbitai

coderabbitai Bot commented Aug 26, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 89b2d21a-4614-482d-a01a-c41652ee7215

📥 Commits

Reviewing files that changed from the base of the PR and between f584aa8 and df27dcd.

📒 Files selected for processing (2)
  • src/main/runtime/relay/relay-http-client.test.ts
  • src/main/runtime/relay/relay-http-client.ts

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


📝 Walkthrough

Walkthrough

The changes add shared Retry-After parsing and typed relay director errors. Mobile relay recovery applies bounded director retry delays while preserving local backoff. Runtime relay assignments use a shared per-director and per-host rate gate with staleness checks and retry-delay tracking. Pairing recovery retries stored assignments for non-newer responses and fails fast for code 4429. Pairing logs now identify direct and relay paths.

Merge Risk: ⚪ Minimal · up to df27d

The changes add mobile recovery and bounded desktop assignment pacing with stale-wait cancellation; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed root-cause context, change scope, rationale, verification results, and follow-up items. However, it omits required template sections and checklist items, including a … Update the description to follow the repository template. Add a formal issue reference such as Fixes #..., complete Visual Proof or state N/A with a reason, complete the applicable testing and checklist items, and address AI Disclosure,…
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 19 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 identifies both primary changes: mobile pairing recovery and the desktop relay assignment rate gate.
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 detailed root-cause context, change scope, rationale, verification results, and follow-up items. However, it omits required template sections and checklist items, including a formal Linked Issue entry, Visual Proof or an explicit N/A explanation, AI Disclosure, Review, Agent skill upstream boundary, and the final checklist.

Resolution

Update the description to follow the repository template. Add a formal issue reference such as Fixes #..., complete Visual Proof or state N/A with a reason, complete the applicable testing and checklist items, and address AI Disclosure, Review, Agent skill upstream boundary, and Notes 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.

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

🧹 Nitpick comments (1)
src/main/runtime/relay/relay-assign-rate-gate.ts (1)

56-62: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Make the throttle wait cancellable.

reserve checks isCurrent only after sleep resolves, and the sleep cannot be interrupted. relay-http-client.ts bounds Retry-After at 5 * 60_000, so noteRetryAfter can park the next reserve for up to 5 minutes. A superseded or closed caller stays pending for that whole window, and later callers for the same key queue behind the tail. Two small changes reduce the stall: check isCurrent before sleeping, and split the wait so it can end early.

♻️ Suggested change
-      const waitMs = (this.nextPermittedAt.get(key) ?? 0) - this.now()
-      if (waitMs > 0) {
-        await this.sleep(waitMs)
-      }
+      // A caller superseded before the wait must not hold the chain at all.
+      if (isCurrent && !isCurrent()) {
+        stale = true
+      }
+      while (!stale) {
+        const waitMs = (this.nextPermittedAt.get(key) ?? 0) - this.now()
+        if (waitMs <= 0) {
+          break
+        }
+        await this.sleep(Math.min(waitMs, ASSIGN_MIN_INTERVAL_MS))
+        stale = isCurrent ? !isCurrent() : false
+      }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4c149cde-67c9-4569-acfb-8d7560a0843c

📥 Commits

Reviewing files that changed from the base of the PR and between cda2280 and 4a4e28a27aeae0f79052d096d496b4c462ff28c8.

📒 Files selected for processing (18)
  • mobile/src/transport/mobile-relay-reconnect-controller.test.ts
  • mobile/src/transport/mobile-relay-reconnect-controller.ts
  • mobile/src/transport/mobile-relay-resume-director.test.ts
  • mobile/src/transport/mobile-relay-resume-director.ts
  • mobile/src/transport/mobile-relay-retry-delays.ts
  • mobile/src/transport/pairing-candidate-race.ts
  • mobile/src/transport/pairing-log-path.test.ts
  • mobile/src/transport/pairing-log-path.ts
  • mobile/src/transport/pairing-relay-candidate.test.ts
  • mobile/src/transport/pairing-relay-candidate.ts
  • mobile/src/transport/pre-profile-pairing-coordinator.test.ts
  • mobile/src/transport/pre-profile-pairing-coordinator.ts
  • src/main/runtime/relay/relay-assign-rate-gate.ts
  • src/main/runtime/relay/relay-http-client.test.ts
  • src/main/runtime/relay/relay-http-client.ts
  • src/main/runtime/relay/relay-origin-pool.ts
  • src/main/runtime/relay/relay-session-broker.ts
  • src/shared/relay-retry-after-header.ts

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

… newer move

A director answering /v1/connect can only reply relay-moved with the stored
assignment; it has no 'assignment unchanged' verb, and sticky assignments make
equal-epoch replies the steady state. Treating every non-newer move as fatal
made pairing recovery unwinnable for any transient cell dial failure (DRAINING,
1006), which bricked off-LAN pairing on Android 0.0.44.

A non-newer move now confirms the stored assignment: the candidate re-dials it
with a 250ms floor instead of abandoning the relay path. The move is never
adopted or persisted, so the anti-rollback contract (requireStrictlyNewerEpoch
for persisted moves) is unchanged. 4429 stays out of director recovery: each
cell dial burns an invite attempt server-side and a director hop cannot relieve
cell load.
Mobile /v1/resolve collapsed every non-OK status into a generic error and
discarded Retry-After, so overloaded windows produced hammering instead of
paced retries. RelayDirectorHttpError now carries status and retryAfterMs
(clamped to 120s), and the reconnect controller floors its existing transport
delay with it — no new timers or retry state. The Retry-After parser is
extracted from the desktop relay client into src/shared and reused by both.
The pairing race interleaves the direct LAN and relay candidates into one
PAIRING LOG pane; direct lines (WebSocket closed, Reconnecting 10.x.x.x:6768)
carried no path label and repeatedly read as Relay retrying a private IP —
misleading users and two investigations. The coordinator now wraps each
candidate's sink with an idempotent Direct:/Relay: prefix at the one seam
where both paths are known.
The director rate-limits /v1/assign per host at 5s, but every desktop retry
path could fire immediately: both schedulers draw full jitter from [0, cap]
(floor 0), first attempts after a drain are undelayed, the 400-fallbacks issue
up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After
timer from ~8 refreshDemand callers. Production shows hosts permanently
rejected at ~100-200 rejects per success.

A shared per-host gate now lives inside requestRelayAssignment — the single
assign call site — so every path books a >=5s (+jitter) slot. Retry-After
raises the gate persistently, surviving the coordinator's timer cancellation.
Concurrent callers serialize through a per-key chain. Callers with staleness
fencing pass isCurrent; a superseded caller aborts after the wait instead of
spending the host's slot. Internal 400-fallback retries stay one logical
attempt and do not re-enter the gate.
isCurrentAssignmentMove no longer gates control flow — every non-newer move
retries the stored assignment — so the name overstated its role.
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

CI note: the red typecheck/static-analysis/test-shard checks are pre-existing main breakage in src/renderer/src/components/automations/* (9 tc errors + AutomationsPage.test.tsx failures), introduced by #16532 (cda2280), whose own CI run on main shows action_required and never executed. No file in this PR overlaps. Branch is rebased onto current main; relay/transport suites pass (91 + 629).

@Jinwoo-H
Jinwoo-H force-pushed the relay-root-cause-fable5 branch from 4a4e28a to b19b5b4 Compare August 26, 2026 18:20
@coderabbitai

coderabbitai Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Review findings on the per-host assign gate: the deadline was read once
before sleeping, so a sibling's Retry-After landing mid-wait was ignored
(the exact storm the gate exists for), and the sleep was uncancellable —
a booked five-minute Retry-After could park pairing IPC, which awaits
reconcile inline, for its full duration.

The wait now runs in 1s slices, re-reading the deadline and the caller's
isCurrent fence each slice. Remaining waits beyond 15s fail fast as a
RelayHttpError 429 carrying the remainder, so the existing schedulers
pace with it while the gate keeps the deadline. Staleness aborts are
classified non-retryable. Also from review: the broker's isCurrent wiring
and the shared-gate default are now pinned by tests, the 4429 comment
states the reservation-order rationale precisely, the mobile Retry-After
ceiling is renamed to avoid colliding with the desktop's 5-minute one,
and a past-HTTP-date header case is covered.
Review polish: the synthesized 429 for a beyond-cap local wait now carries a
distinct message (relay_assignment_locally_paced_429) so log censuses can tell
it from a real director 429, with the comment stating the invariant that makes
the translation honest (local booking alone never exceeds ~5.5s). The gate's
sleep option documents that test fakes must advance the clock — the slice loop
re-reads it and never terminates against a frozen one.

@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)
src/main/runtime/relay/relay-http-client.ts (1)

138-163: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Recheck isCurrent before sending the assignment.

RelayAssignRateGate.reserve checks isCurrent before booking, but requestRelayAssignment unconditionally calls sendRelayAssignment after it resolves. If isCurrent becomes false at that handoff, a stale caller still posts /v1/assign. Add a final fence and regression test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 482b5af4-adb0-4b72-b8a4-6165e246cda1

📥 Commits

Reviewing files that changed from the base of the PR and between 6933412 and f584aa8.

📒 Files selected for processing (2)
  • src/main/runtime/relay/relay-assign-rate-gate.ts
  • src/main/runtime/relay/relay-http-client.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/relay/relay-assign-rate-gate.ts

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

reserve() checks staleness while waiting, but a caller superseded after
booking — or between the 400 field-fallback retries — could still spend
one to two requests on an assignment nobody consumes. Re-check
isCurrent at the top of sendRelayAssignment so the fallback recursion
is fenced too.
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Addressed review feedback: superseded callers are now re-fenced at the send boundary (sendRelayAssignment re-checks isCurrent before every request, which also fences the 400 field-fallback recursions). Two new tests: supersession after reservation (fetch never fires) and supersession between fallback retries (exactly one request). Relay suite 96/96 green, tc:node clean; CI failures remain the pre-existing automations breakage from #16532.

@Jinwoo-H
Jinwoo-H merged commit 8d61cb8 into main Aug 26, 2026
136 of 143 checks passed
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…gate (stablyai#16659)

* fix(mobile): retry the stored assignment when the director reports no newer move

A director answering /v1/connect can only reply relay-moved with the stored
assignment; it has no 'assignment unchanged' verb, and sticky assignments make
equal-epoch replies the steady state. Treating every non-newer move as fatal
made pairing recovery unwinnable for any transient cell dial failure (DRAINING,
1006), which bricked off-LAN pairing on Android 0.0.44.

A non-newer move now confirms the stored assignment: the candidate re-dials it
with a 250ms floor instead of abandoning the relay path. The move is never
adopted or persisted, so the anti-rollback contract (requireStrictlyNewerEpoch
for persisted moves) is unchanged. 4429 stays out of director recovery: each
cell dial burns an invite attempt server-side and a director hop cannot relieve
cell load.

* fix(mobile): honor relay director Retry-After when pacing recovery

Mobile /v1/resolve collapsed every non-OK status into a generic error and
discarded Retry-After, so overloaded windows produced hammering instead of
paced retries. RelayDirectorHttpError now carries status and retryAfterMs
(clamped to 120s), and the reconnect controller floors its existing transport
delay with it — no new timers or retry state. The Retry-After parser is
extracted from the desktop relay client into src/shared and reused by both.

* fix(mobile): attribute pairing log lines to their candidate path

The pairing race interleaves the direct LAN and relay candidates into one
PAIRING LOG pane; direct lines (WebSocket closed, Reconnecting 10.x.x.x:6768)
carried no path label and repeatedly read as Relay retrying a private IP —
misleading users and two investigations. The coordinator now wraps each
candidate's sink with an idempotent Direct:/Relay: prefix at the one seam
where both paths are known.

* fix(relay): gate desktop /v1/assign at the per-host rate limit

The director rate-limits /v1/assign per host at 5s, but every desktop retry
path could fire immediately: both schedulers draw full jitter from [0, cap]
(floor 0), first attempts after a drain are undelayed, the 400-fallbacks issue
up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After
timer from ~8 refreshDemand callers. Production shows hosts permanently
rejected at ~100-200 rejects per success.

A shared per-host gate now lives inside requestRelayAssignment — the single
assign call site — so every path books a >=5s (+jitter) slot. Retry-After
raises the gate persistently, surviving the coordinator's timer cancellation.
Concurrent callers serialize through a per-key chain. Callers with staleness
fencing pass isCurrent; a superseded caller aborts after the wait instead of
spending the host's slot. Internal 400-fallback retries stay one logical
attempt and do not re-enter the gate.

* refactor(mobile): rename the log-only assignment-echo predicate

isCurrentAssignmentMove no longer gates control flow — every non-newer move
retries the stored assignment — so the name overstated its role.

* fix(relay): honor mid-wait raises and cap the assign gate's inline wait

Review findings on the per-host assign gate: the deadline was read once
before sleeping, so a sibling's Retry-After landing mid-wait was ignored
(the exact storm the gate exists for), and the sleep was uncancellable —
a booked five-minute Retry-After could park pairing IPC, which awaits
reconcile inline, for its full duration.

The wait now runs in 1s slices, re-reading the deadline and the caller's
isCurrent fence each slice. Remaining waits beyond 15s fail fast as a
RelayHttpError 429 carrying the remainder, so the existing schedulers
pace with it while the gate keeps the deadline. Staleness aborts are
classified non-retryable. Also from review: the broker's isCurrent wiring
and the shared-gate default are now pinned by tests, the 4429 comment
states the reservation-order rationale precisely, the mobile Retry-After
ceiling is renamed to avoid colliding with the desktop's 5-minute one,
and a past-HTTP-date header case is covered.

* fix(relay): tag locally paced assigns and warn about frozen test clocks

Review polish: the synthesized 429 for a beyond-cap local wait now carries a
distinct message (relay_assignment_locally_paced_429) so log censuses can tell
it from a real director 429, with the comment stating the invariant that makes
the translation honest (local booking alone never exceeds ~5.5s). The gate's
sleep option documents that test fakes must advance the clock — the slice loop
re-reads it and never terminates against a frozen one.

* fix(relay): fence superseded callers at the assign send boundary

reserve() checks staleness while waiting, but a caller superseded after
booking — or between the 400 field-fallback retries — could still spend
one to two requests on an assignment nobody consumes. Re-check
isCurrent at the top of sendRelayAssignment so the fallback recursion
is fenced too.
rahuljangirworks pushed a commit to rahuljangirworks/veer that referenced this pull request Aug 27, 2026
…gate (stablyai#16659)

* fix(mobile): retry the stored assignment when the director reports no newer move

A director answering /v1/connect can only reply relay-moved with the stored
assignment; it has no 'assignment unchanged' verb, and sticky assignments make
equal-epoch replies the steady state. Treating every non-newer move as fatal
made pairing recovery unwinnable for any transient cell dial failure (DRAINING,
1006), which bricked off-LAN pairing on Android 0.0.44.

A non-newer move now confirms the stored assignment: the candidate re-dials it
with a 250ms floor instead of abandoning the relay path. The move is never
adopted or persisted, so the anti-rollback contract (requireStrictlyNewerEpoch
for persisted moves) is unchanged. 4429 stays out of director recovery: each
cell dial burns an invite attempt server-side and a director hop cannot relieve
cell load.

* fix(mobile): honor relay director Retry-After when pacing recovery

Mobile /v1/resolve collapsed every non-OK status into a generic error and
discarded Retry-After, so overloaded windows produced hammering instead of
paced retries. RelayDirectorHttpError now carries status and retryAfterMs
(clamped to 120s), and the reconnect controller floors its existing transport
delay with it — no new timers or retry state. The Retry-After parser is
extracted from the desktop relay client into src/shared and reused by both.

* fix(mobile): attribute pairing log lines to their candidate path

The pairing race interleaves the direct LAN and relay candidates into one
PAIRING LOG pane; direct lines (WebSocket closed, Reconnecting 10.x.x.x:6768)
carried no path label and repeatedly read as Relay retrying a private IP —
misleading users and two investigations. The coordinator now wraps each
candidate's sink with an idempotent Direct:/Relay: prefix at the one seam
where both paths are known.

* fix(relay): gate desktop /v1/assign at the per-host rate limit

The director rate-limits /v1/assign per host at 5s, but every desktop retry
path could fire immediately: both schedulers draw full jitter from [0, cap]
(floor 0), first attempts after a drain are undelayed, the 400-fallbacks issue
up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After
timer from ~8 refreshDemand callers. Production shows hosts permanently
rejected at ~100-200 rejects per success.

A shared per-host gate now lives inside requestRelayAssignment — the single
assign call site — so every path books a >=5s (+jitter) slot. Retry-After
raises the gate persistently, surviving the coordinator's timer cancellation.
Concurrent callers serialize through a per-key chain. Callers with staleness
fencing pass isCurrent; a superseded caller aborts after the wait instead of
spending the host's slot. Internal 400-fallback retries stay one logical
attempt and do not re-enter the gate.

* refactor(mobile): rename the log-only assignment-echo predicate

isCurrentAssignmentMove no longer gates control flow — every non-newer move
retries the stored assignment — so the name overstated its role.

* fix(relay): honor mid-wait raises and cap the assign gate's inline wait

Review findings on the per-host assign gate: the deadline was read once
before sleeping, so a sibling's Retry-After landing mid-wait was ignored
(the exact storm the gate exists for), and the sleep was uncancellable —
a booked five-minute Retry-After could park pairing IPC, which awaits
reconcile inline, for its full duration.

The wait now runs in 1s slices, re-reading the deadline and the caller's
isCurrent fence each slice. Remaining waits beyond 15s fail fast as a
RelayHttpError 429 carrying the remainder, so the existing schedulers
pace with it while the gate keeps the deadline. Staleness aborts are
classified non-retryable. Also from review: the broker's isCurrent wiring
and the shared-gate default are now pinned by tests, the 4429 comment
states the reservation-order rationale precisely, the mobile Retry-After
ceiling is renamed to avoid colliding with the desktop's 5-minute one,
and a past-HTTP-date header case is covered.

* fix(relay): tag locally paced assigns and warn about frozen test clocks

Review polish: the synthesized 429 for a beyond-cap local wait now carries a
distinct message (relay_assignment_locally_paced_429) so log censuses can tell
it from a real director 429, with the comment stating the invariant that makes
the translation honest (local booking alone never exceeds ~5.5s). The gate's
sleep option documents that test fakes must advance the clock — the slice loop
re-reads it and never terminates against a frozen one.

* fix(relay): fence superseded callers at the assign send boundary

reserve() checks staleness while waiting, but a caller superseded after
booking — or between the 400 field-fallback retries — could still spend
one to two requests on an assignment nobody consumes. Re-check
isCurrent at the top of sendRelayAssignment so the fallback recursion
is fenced too.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 28, 2026
…gate (stablyai#16659)

* fix(mobile): retry the stored assignment when the director reports no newer move

A director answering /v1/connect can only reply relay-moved with the stored
assignment; it has no 'assignment unchanged' verb, and sticky assignments make
equal-epoch replies the steady state. Treating every non-newer move as fatal
made pairing recovery unwinnable for any transient cell dial failure (DRAINING,
1006), which bricked off-LAN pairing on Android 0.0.44.

A non-newer move now confirms the stored assignment: the candidate re-dials it
with a 250ms floor instead of abandoning the relay path. The move is never
adopted or persisted, so the anti-rollback contract (requireStrictlyNewerEpoch
for persisted moves) is unchanged. 4429 stays out of director recovery: each
cell dial burns an invite attempt server-side and a director hop cannot relieve
cell load.

* fix(mobile): honor relay director Retry-After when pacing recovery

Mobile /v1/resolve collapsed every non-OK status into a generic error and
discarded Retry-After, so overloaded windows produced hammering instead of
paced retries. RelayDirectorHttpError now carries status and retryAfterMs
(clamped to 120s), and the reconnect controller floors its existing transport
delay with it — no new timers or retry state. The Retry-After parser is
extracted from the desktop relay client into src/shared and reused by both.

* fix(mobile): attribute pairing log lines to their candidate path

The pairing race interleaves the direct LAN and relay candidates into one
PAIRING LOG pane; direct lines (WebSocket closed, Reconnecting 10.x.x.x:6768)
carried no path label and repeatedly read as Relay retrying a private IP —
misleading users and two investigations. The coordinator now wraps each
candidate's sink with an idempotent Direct:/Relay: prefix at the one seam
where both paths are known.

* fix(relay): gate desktop /v1/assign at the per-host rate limit

The director rate-limits /v1/assign per host at 5s, but every desktop retry
path could fire immediately: both schedulers draw full jitter from [0, cap]
(floor 0), first attempts after a drain are undelayed, the 400-fallbacks issue
up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After
timer from ~8 refreshDemand callers. Production shows hosts permanently
rejected at ~100-200 rejects per success.

A shared per-host gate now lives inside requestRelayAssignment — the single
assign call site — so every path books a >=5s (+jitter) slot. Retry-After
raises the gate persistently, surviving the coordinator's timer cancellation.
Concurrent callers serialize through a per-key chain. Callers with staleness
fencing pass isCurrent; a superseded caller aborts after the wait instead of
spending the host's slot. Internal 400-fallback retries stay one logical
attempt and do not re-enter the gate.

* refactor(mobile): rename the log-only assignment-echo predicate

isCurrentAssignmentMove no longer gates control flow — every non-newer move
retries the stored assignment — so the name overstated its role.

* fix(relay): honor mid-wait raises and cap the assign gate's inline wait

Review findings on the per-host assign gate: the deadline was read once
before sleeping, so a sibling's Retry-After landing mid-wait was ignored
(the exact storm the gate exists for), and the sleep was uncancellable —
a booked five-minute Retry-After could park pairing IPC, which awaits
reconcile inline, for its full duration.

The wait now runs in 1s slices, re-reading the deadline and the caller's
isCurrent fence each slice. Remaining waits beyond 15s fail fast as a
RelayHttpError 429 carrying the remainder, so the existing schedulers
pace with it while the gate keeps the deadline. Staleness aborts are
classified non-retryable. Also from review: the broker's isCurrent wiring
and the shared-gate default are now pinned by tests, the 4429 comment
states the reservation-order rationale precisely, the mobile Retry-After
ceiling is renamed to avoid colliding with the desktop's 5-minute one,
and a past-HTTP-date header case is covered.

* fix(relay): tag locally paced assigns and warn about frozen test clocks

Review polish: the synthesized 429 for a beyond-cap local wait now carries a
distinct message (relay_assignment_locally_paced_429) so log censuses can tell
it from a real director 429, with the comment stating the invariant that makes
the translation honest (local booking alone never exceeds ~5.5s). The gate's
sleep option documents that test fakes must advance the clock — the slice loop
re-reads it and never terminates against a frozen one.

* fix(relay): fence superseded callers at the assign send boundary

reserve() checks staleness while waiting, but a caller superseded after
booking — or between the 400 field-fallback retries — could still spend
one to two requests on an assignment nobody consumes. Re-check
isCurrent at the top of sendRelayAssignment so the fallback recursion
is fenced too.

(cherry picked from commit 8d61cb8)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…gate (stablyai#16659)

* fix(mobile): retry the stored assignment when the director reports no newer move

A director answering /v1/connect can only reply relay-moved with the stored
assignment; it has no 'assignment unchanged' verb, and sticky assignments make
equal-epoch replies the steady state. Treating every non-newer move as fatal
made pairing recovery unwinnable for any transient cell dial failure (DRAINING,
1006), which bricked off-LAN pairing on Android 0.0.44.

A non-newer move now confirms the stored assignment: the candidate re-dials it
with a 250ms floor instead of abandoning the relay path. The move is never
adopted or persisted, so the anti-rollback contract (requireStrictlyNewerEpoch
for persisted moves) is unchanged. 4429 stays out of director recovery: each
cell dial burns an invite attempt server-side and a director hop cannot relieve
cell load.

* fix(mobile): honor relay director Retry-After when pacing recovery

Mobile /v1/resolve collapsed every non-OK status into a generic error and
discarded Retry-After, so overloaded windows produced hammering instead of
paced retries. RelayDirectorHttpError now carries status and retryAfterMs
(clamped to 120s), and the reconnect controller floors its existing transport
delay with it — no new timers or retry state. The Retry-After parser is
extracted from the desktop relay client into src/shared and reused by both.

* fix(mobile): attribute pairing log lines to their candidate path

The pairing race interleaves the direct LAN and relay candidates into one
PAIRING LOG pane; direct lines (WebSocket closed, Reconnecting 10.x.x.x:6768)
carried no path label and repeatedly read as Relay retrying a private IP —
misleading users and two investigations. The coordinator now wraps each
candidate's sink with an idempotent Direct:/Relay: prefix at the one seam
where both paths are known.

* fix(relay): gate desktop /v1/assign at the per-host rate limit

The director rate-limits /v1/assign per host at 5s, but every desktop retry
path could fire immediately: both schedulers draw full jitter from [0, cap]
(floor 0), first attempts after a drain are undelayed, the 400-fallbacks issue
up to 3 assigns per round trip, and reconcile() cancels the armed Retry-After
timer from ~8 refreshDemand callers. Production shows hosts permanently
rejected at ~100-200 rejects per success.

A shared per-host gate now lives inside requestRelayAssignment — the single
assign call site — so every path books a >=5s (+jitter) slot. Retry-After
raises the gate persistently, surviving the coordinator's timer cancellation.
Concurrent callers serialize through a per-key chain. Callers with staleness
fencing pass isCurrent; a superseded caller aborts after the wait instead of
spending the host's slot. Internal 400-fallback retries stay one logical
attempt and do not re-enter the gate.

* refactor(mobile): rename the log-only assignment-echo predicate

isCurrentAssignmentMove no longer gates control flow — every non-newer move
retries the stored assignment — so the name overstated its role.

* fix(relay): honor mid-wait raises and cap the assign gate's inline wait

Review findings on the per-host assign gate: the deadline was read once
before sleeping, so a sibling's Retry-After landing mid-wait was ignored
(the exact storm the gate exists for), and the sleep was uncancellable —
a booked five-minute Retry-After could park pairing IPC, which awaits
reconcile inline, for its full duration.

The wait now runs in 1s slices, re-reading the deadline and the caller's
isCurrent fence each slice. Remaining waits beyond 15s fail fast as a
RelayHttpError 429 carrying the remainder, so the existing schedulers
pace with it while the gate keeps the deadline. Staleness aborts are
classified non-retryable. Also from review: the broker's isCurrent wiring
and the shared-gate default are now pinned by tests, the 4429 comment
states the reservation-order rationale precisely, the mobile Retry-After
ceiling is renamed to avoid colliding with the desktop's 5-minute one,
and a past-HTTP-date header case is covered.

* fix(relay): tag locally paced assigns and warn about frozen test clocks

Review polish: the synthesized 429 for a beyond-cap local wait now carries a
distinct message (relay_assignment_locally_paced_429) so log censuses can tell
it from a real director 429, with the comment stating the invariant that makes
the translation honest (local booking alone never exceeds ~5.5s). The gate's
sleep option documents that test fakes must advance the clock — the slice loop
re-reads it and never terminates against a frozen one.

* fix(relay): fence superseded callers at the assign send boundary

reserve() checks staleness while waiting, but a caller superseded after
booking — or between the 400 field-fallback retries — could still spend
one to two requests on an assignment nobody consumes. Re-check
isCurrent at the top of sendRelayAssignment so the fallback recursion
is fenced too.
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