Skip to content

fix(relay): desktop control lifecycle — truthful registration, skew tolerance, silence watchdog - #12060

Closed
Jinwoo-H wants to merge 5 commits into
mainfrom
relay-issue-2
Closed

Jinwoo-H wants to merge 5 commits into
mainfrom
relay-issue-2

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Fixes the desktop half of the sustained Relay-only HOST_OFFLINE incident.

Defects fixed

  • Dead-control promotion (D1): a socket delivering hello-ack and close in the same ws parser turn fired onClose before activate(); the dead control was then promoted to activeControl with no recovery path. RelayControlOrigin.activate now rejects controls that closed before activation; open/rebind fail into existing retry paths.
  • No liveness detection (D2): the control client never required inbound traffic. New 75s silence watchdog mirrors the relay's 15s ping contract; silent/zombie sockets terminate and trigger origin recovery.
  • Registered-without-proof (D3): RelayAuthCoordinator republished registered from ownership validity alone on every reconcile. It now requires broker.isLive() (plumbed client → origin → pool → broker) and replaces dead brokers.
  • Zero-tolerance clock check: host-challenge freshness rejected any challenge stamped even 1ms in the future. A cell (~+100ms NTP drift) deterministically failed every activation. Now 2s leeway on both edges; challenges stay single-use and nonce-bound.
  • Silent failures: broker reconcile failures and challenge-validation failures now log the failing operation/check by name (never values).

Evidence

  • Red-before/green-after tests at each seam (broker-level dead-control connect, watchdog, coordinator dead-broker republish, skew tolerance): 58 relay tests pass.
  • Live repro restored: Relay-only iOS simulator with invalid direct endpoint went from a sustained relay_outer_4404 loop + desktop claiming registered with zero sockets, to truthful registered with a live control and real terminal round-trips over the relay.

Cloud-side counterpart: stablyai/orca-cloud#207 (activation fence, merged) + #208 (C9 canary image).

OrcaWin added 3 commits July 27, 2026 01:57
- RelayControlOrigin.activate rejects controls whose socket closed before
  activation (hello-ack and close in one ws parser turn previously published
  a dead control with no recovery path)
- RelayControlClient gains a 75s inbound-silence watchdog mirroring the
  relay's ping contract, so dead or server-side-unindexed sockets terminate
  and trigger origin recovery
- RelayAuthCoordinator only republishes 'registered' when the owned broker
  proves a live control; dead brokers are replaced instead
- isLive() plumbed client -> origin -> pool -> broker
- Host-challenge freshness gets a 2s leeway on both edges: a cell whose
  clock ran ~100ms ahead deterministically failed every control activation
  under the zero-tolerance issuedAt check (challenges stay single-use and
  nonce-bound, so replay protection is intact)
- answerRelayHostChallenge reports the failing check by name (never values)
  and the control client includes it plus the cell origin in the close reason
- RelayAuthCoordinator warns on broker reconcile failures instead of
  swallowing them; silent failures made a dead relay look like standby
@coderabbitai

coderabbitai Bot commented Aug 2, 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: Pro Plus

Run ID: 758b7264-b7eb-414f-aaeb-6a9cbd7b20e5

📥 Commits

Reviewing files that changed from the base of the PR and between e19fdfc and 6879766.

📒 Files selected for processing (1)
  • src/main/runtime/relay/relay-origin-pool.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/relay/relay-origin-pool.ts

📝 Walkthrough

Walkthrough

The relay runtime adds control URL validation, silence monitoring, liveness reporting, and detailed host-proof failure reasons. It adds bounded HTTP Retry-After parsing and exponential drain retry scheduling. Broker reconciliation replaces dead brokers and honors server retry delays. Tests cover control lifecycle, proof timing, retry behavior, drain recovery, and broker replacement. The reliability configuration adds the experimental assignment-backpressure gate.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the defects and evidence, but omits the required Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Add all required template sections, including visual-change status, test checklist, cross-platform AI review, security audit, and follow-up notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. 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 main relay control lifecycle, registration, clock-skew, and silence watchdog changes.
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.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch relay-issue-2

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/main/runtime/relay/relay-control-silence-watchdog.ts (1)

1-37: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard start() against a double start.

start() overwrites this.timer without clearing an existing interval. The current client calls start() once per socket, so no leak occurs today. A future second call would orphan a timer that later terminates a live socket.

♻️ Proposed guard
   start(): void {
+    this.stop()
     this.lastInboundAt = Date.now()
src/main/runtime/relay/relay-drain-retry-schedule.ts (1)

14-29: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a minimum delay floor to the jitter.

jitterMs is floor(random() * (capMs + 1)), so the delay can be 0 when the server sends no Retry-After. On the first attempts the cap is small (1s, 2s, 4s), so a low random value produces near-immediate retries against the director. Apply a floor, for example half the cap or a fixed minimum.

♻️ Proposed change
-    const jitterMs = Math.floor(this.random() * (capMs + 1))
+    // Full jitter with a floor keeps early retries from hammering the director.
+    const jitterMs = Math.floor(capMs / 2 + this.random() * (capMs / 2 + 1))

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c0c4c087-9fe1-4cb7-9be4-f2d9c6565eb5

📥 Commits

Reviewing files that changed from the base of the PR and between f820f40 and e19fdfc.

📒 Files selected for processing (16)
  • config/reliability-gates.jsonc
  • src/main/runtime/relay/relay-auth-coordinator-recovery.test.ts
  • src/main/runtime/relay/relay-auth-coordinator.test.ts
  • src/main/runtime/relay/relay-auth-coordinator.ts
  • src/main/runtime/relay/relay-control-client.test.ts
  • src/main/runtime/relay/relay-control-client.ts
  • src/main/runtime/relay/relay-control-origin.ts
  • src/main/runtime/relay/relay-control-silence-watchdog.ts
  • src/main/runtime/relay/relay-control-url.ts
  • src/main/runtime/relay/relay-drain-retry-schedule.ts
  • src/main/runtime/relay/relay-host-proof.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.test.ts
  • src/main/runtime/relay/relay-session-broker.ts

Comment on lines +34 to +35
/** Reports the failing check by name only; never receives field values. */
onInvalid?: (reason: string) => void

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Align the onInvalid contract text with the emitted reasons.

The doc comment states the callback never receives field values. The reason strings embed computed values: d=<delta>ms and w=<window>ms. These are relative offsets, not absolute timestamps, so the privacy risk is low. Update the doc comment so the contract matches the emitted content, because relay-control-client.ts logs the reason verbatim in failProtocol.

♻️ Proposed doc change
-  /** Reports the failing check by name only; never receives field values. */
+  /** Reports failing check names plus relative time offsets; never absolute timestamps or field values. */
   onInvalid?: (reason: string) => void

Also applies to: 111-125

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a sustained HOST_OFFLINE incident caused by three defects in the desktop Relay control lifecycle: dead controls being promoted to activeControl when the WebSocket close event landed in the same parser turn as the hello-ack (D1), the coordinator falsely reporting registered while holding a dead broker (D3), and no inbound-traffic watchdog allowing zombie sockets to stay "active" indefinitely (D2). A clock-skew naming improvement and named-check diagnostics for challenge validation failures round out the change.

  • D1 (dead-control promotion): RelayControlOrigin.activate() now guards against controls that are no longer in the tracked set or no longer live, throwing relay_control_closed_before_activation so callers fall into existing retry paths rather than publishing a dead control with no recovery path.
  • D2 (silence watchdog): New RelayControlSilenceWatchdog terminates any control socket that receives no inbound traffic within 75 s, matching the relay's own ping interval; the watchdog is started on activation and stopped on any close path.
  • D3 (truthful registration): RelayAuthCoordinator.reconcileEpoch() now calls broker.isLive?.() before emitting registered, replacing dead brokers instead of republishing stale status; isLive is threaded through RelaySessionBroker → RelayOriginPool → RelayControlOrigin → RelayControlClient.isLive().

Confidence Score: 5/5

Safe to merge — the three concurrency defects are each fixed with tight, well-tested guards and no new error paths are left unhandled.

All three named defects are addressed with before/after tests at each seam. The D1 guard correctly feeds into the existing retry loop, the silence watchdog start/stop is correctly paired with state transitions and unref'd, and the isLive chain threads cleanly from client to coordinator with optional-chaining backward compatibility. No correctness issues were found.

Files Needing Attention: No files require special attention. The relay-host-proof.ts early-exit path still omits onInvalid for key/nonce decode failures (flagged in a prior review comment) but that is a pre-existing diagnostic gap, not a correctness regression from this PR.

Important Files Changed

Filename Overview
src/main/runtime/relay/relay-control-origin.ts Adds hasLiveControl() delegation and the D1 guard in activate() that throws when the control closed before promotion; resource cleanup via this.controls and close() is correct for all error paths.
src/main/runtime/relay/relay-control-client.ts Adds isLive(), wires the silence watchdog into connect/close lifecycle, and improves challenge-failure logging with onInvalid; watchdog start/stop is correctly paired with state transitions.
src/main/runtime/relay/relay-auth-coordinator.ts D3 fix gates registered on broker.isLive?.() ?? true; optional chaining preserves backward compatibility with brokers that don't implement isLive; retry logging added for silent failures.
src/main/runtime/relay/relay-control-silence-watchdog.ts New 75s watchdog mirrors relay's ping contract; unref() called on the interval so it doesn't block the Node process; stop() is idempotent and safe to call multiple times.
src/main/runtime/relay/relay-host-proof.ts Replaces single boolean AND with named-check array for better diagnostics; onInvalid is called for transcript-structure, each named failing field, and challenge-box-open; early-exit path for decode failures still lacks onInvalid (pre-existing, covered in prior review comment).
src/main/runtime/relay/relay-session-broker.ts Adds isLive() delegating through originPool.hasLiveControl(); included in CoordinatedRelayBroker contract via the coordinator type.
src/main/runtime/relay/relay-origin-pool.ts Adds hasLiveControl() passthrough and a console.warn for silent retry-loop failures discovered during incident triage.
src/main/runtime/relay/relay-control-url.ts Pure extraction of controlWebSocketUrl into its own module; logic is unchanged from original location in relay-control-client.ts.
src/main/runtime/relay/relay-control-client.test.ts New scripted-socket test suite covers D1 (close-in-ack-turn), clock skew tolerance, silence watchdog timeout, and watchdog keepalive via pings; good coverage of the new lifecycle paths.
src/main/runtime/relay/relay-session-broker.test.ts Adds isLive mock and a test confirming relay_control_closed_before_activation propagates correctly to the broker layer with the expected status sequence.
src/main/runtime/relay/relay-auth-coordinator.test.ts New test verifies that a dead broker triggers replacement rather than a repeated registered emission, and that two connecting transitions are emitted during the swap.
src/main/ssh/ssh-connection.ts Formatting-only change: reformatted a multi-line conditional to fit on a single line; no behavioral change.
src/relay/git-handler.ts Two indentation/comment-alignment fixes only; no logic changes.

Sequence Diagram

sequenceDiagram
    participant Coord as RelayAuthCoordinator
    participant Broker as RelaySessionBroker
    participant Pool as RelayOriginPool
    participant Origin as RelayControlOrigin
    participant Client as RelayControlClient
    participant WD as SilenceWatchdog
    participant WS as WebSocket

    Coord->>Broker: openBroker()
    Broker->>Pool: openInitial()
    Pool->>Origin: open()
    Origin->>Client: connect()
    Client->>WS: createSocket()
    WS-->>Client: open
    Client->>WS: send host-hello
    WS-->>Client: host-challenge
    Client->>WS: send host-challenge-ack
    WS-->>Client: host-hello-ack + (maybe close, same parser turn)
    Note over Client: state → active, WD.start()
    Client-->>Origin: connectResolve(ack)

    alt D1: close fired in same parser turn
        WS-->>Client: close(1006)
        Note over Client: state → closed, WD.stop()
        Client->>Origin: onClose(1006)
        Origin->>Origin: activate() throws relay_control_closed_before_activation
        Origin-->>Pool: throw
        Pool-->>Broker: throw
        Broker-->>Coord: throw
        Coord->>Coord: scheduleRetry()
    else Normal activation
        Origin->>Origin: activate() sets activeControl
        Origin-->>Pool: open() resolves
        Pool-->>Broker: openInitial() resolves
        Broker-->>Coord: registered

        loop D2: every 15s watchdog check
            WD->>WD: "Date.now() - lastInboundAt > 75s?"
            alt Silent for 75s
                WD->>WS: terminate()
                WS-->>Client: close(1006)
                Client->>Origin: onClose
                Origin->>Pool: onClose
                Pool->>Pool: handleDrain recovery
            else Ping received
                WS-->>Client: ping message
                Client->>WD: noteInbound()
            end
        end

        Note over Coord: D3: on next reconcile
        Coord->>Broker: isLive()?
        Broker->>Pool: hasLiveControl()
        Pool->>Origin: hasLiveControl()
        Origin->>Client: isLive()
        Client-->>Coord: true/false
        alt broker not live
            Coord->>Broker: closeNow()
            Coord->>Coord: open new broker
        else broker live
            Coord->>Coord: emit registered
        end
    end
Loading

Reviews (3): Last reviewed commit: "Merge origin/main: adopt 30s host-proof ..." | Re-trigger Greptile

OrcaWin added 2 commits August 1, 2026 23:48
The pool's drain-retry loop ran silently during the 2026-08 incident while
Director 503 throttling stretched recovery to minutes.
@Jinwoo-H

Jinwoo-H commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by the clean relay-only branch (see the replacement PR): this branch's inherited history deleted/reverted ~1.8k lines of unrelated main files, and merging it would have reverted that work. The relay changes are identical in the replacement.

@Jinwoo-H Jinwoo-H closed this Aug 2, 2026
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.

2 participants