Skip to content

fix(remote-runtime): self-heal stale subscriptions after serve restarts - #10235

Closed
tomdebres wants to merge 8 commits into
stablyai:mainfrom
tomdebres:fix/self-heal-stale-subscriptions
Closed

tomdebres wants to merge 8 commits into
stablyai:mainfrom
tomdebres:fix/self-heal-stale-subscriptions

Conversation

@tomdebres

@tomdebres tomdebres commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes stale subscriptions after orca serve restarts behind a WS-terminating relay. The socket-level liveness monitor pings at the RFC 6455 control-frame layer, but such a relay answers those pings itself — so when the server process restarts, the client's E2EE session and the server's in-memory subscription registry are gone while the socket still looks alive, and worktrees created after the restart never reach the sidebar until an app reload. This PR adds an encrypted session probe (status.get every 15s while subscriptions are active): only the server holding this connection's session keys can answer, so a failed probe proves the session is dead and force-closes into the existing close → reconnect → subscription-replay machinery. Responsive connections stay on their socket; probing stops when no subscriptions are active.

Split out of #9614, which bundled this with the unrelated app-version-skew feature; #9614 will be rebased down once the split PRs land.

Tests: new cases in remote-runtime-shared-control-connection.test.ts, including a zombie-relay repro (server records requests but never answers while ws pings keep succeeding → probe forces reconnect and the subscription is re-established on a fresh connection), plus no-reconnect-while-probes-succeed and no-probes-without-subscriptions. pnpm typecheck and the test file green locally.

Review starting point: the header comment in src/shared/remote-runtime-shared-control-session-probe.ts.

cc @OrcaWin

ELI5

After orca serve restarts behind a relay that answers WebSocket pings, the client still looked connected but missed new worktrees. An encrypted session probe self-heals stale subscriptions without a full app reload.

@coderabbitai

coderabbitai Bot commented Jul 23, 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
📝 Walkthrough

Walkthrough

Adds encrypted session probes with configurable intervals and timeouts. The probes depend on connection readiness and active subscriptions, reschedule busy requests, and close stale sockets when appropriate. Connection handling now reconciles subscription lifecycle, propagates abort signals, cleans cancellation resources, and uses shared socket and reconnection helpers. Reusable encrypted test-server and zombie-relay helpers support unit and end-to-end recovery tests. Reliability-gate configuration records coverage, evidence, budgets, and promotion criteria.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change and tests, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and include checklist results, cross-platform review confirmation, security audit findings, and any platform-specific risks or follow-up work.
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 identifies the primary change: self-healing stale subscriptions after serve restarts.
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.

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.

@tomdebres

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. Both conflicts trace to the overnight revert of #10179 (#10255): the shared-control types file keeps only this PR's RemoteRuntimeSocketLivenessOptions import (the reverted RemoteRuntimePreparedRequest import is gone from main again), and closeSocket keeps main's restored separate null assignments plus this PR's sessionProbe.clear(). Typecheck and the connection suite (27 tests) pass.

@tomdebres
tomdebres force-pushed the fix/self-heal-stale-subscriptions branch from ba143a8 to 122e73c Compare July 24, 2026 06:42
@AmethystLiang
AmethystLiang requested a review from OrcaWin July 24, 2026 16:50
@tomdebres
tomdebres force-pushed the fix/self-heal-stale-subscriptions branch from 122e73c to b42173e Compare July 25, 2026 21:31
@tomdebres

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. The reworked OOM foundation (#10299) brought back RemoteRuntimePreparedRequest (now genuinely used by SharedControlPendingRequest) and reshaped the send/request plumbing — the types file keeps both its import and this PR's RemoteRuntimeSocketLivenessOptions, and closeSocket keeps main's compressed null assignment plus this PR's sessionProbe.clear(). The probe integrates cleanly with the new request path since it rides the public request() API. Typecheck and the connection suite (29 tests) pass.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@Jinwoo-H
Jinwoo-H force-pushed the fix/self-heal-stale-subscriptions branch from b42173e to 7aaeaf6 Compare July 31, 2026 15:12
@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR adds an encrypted session probe to the shared-control connection that fires a status.get RPC every 15 s while subscriptions are active. Because only the server that owns the current E2EE session can decrypt and answer the probe, a timeout proves the session is dead even when a WS-terminating relay is still answering RFC 6455 pings — triggering the existing close → reconnect → subscription-replay path to self-heal stale sidebar state after orca serve restarts.

  • New SharedControlSessionProbe class in session-probe.ts implements a non-sliding, single-inflight probe with generation fencing (probedSocket === getSocket() and currentGeneration() guards) so a recovered session is never killed by a stale probe completing after reconnect.
  • AbortSignal support is threaded through requestSharedControl (with releaseCancellation cleanup across all resolution paths in state.ts) so in-flight probes are cleanly cancelled when the last subscription ends or the socket is replaced.
  • Admission-saturation is handled gracefully: when all 256 request slots are full the probe reschedules without closing the healthy socket.
  • remote-runtime-shared-control-test-server.ts is extracted and extended with zombie-relay simulation; a full E2E ZombieRuntimeRelay helper validates headed and headless journeys.

Confidence Score: 4/5

Safe to merge; the self-heal path is isolated behind generation fencing and the existing close/reconnect/replay machinery.

The probe, abort-signal plumbing, and test server extraction are logically correct and tested across unit, integration, and E2E layers. The only open items are two missing comments: one explaining that schedule() aborts in-flight probes when conditions fail, and one preserving the backoff-bypass rationale in the extracted manual-reconnect helper.

Files Needing Attention: remote-runtime-shared-control-session-probe.ts and remote-runtime-shared-control-manual-reconnect.ts both merit a small clarifying comment added before merge.

Important Files Changed

Filename Overview
src/shared/remote-runtime-shared-control-session-probe.ts New core probe class; schedule/clear/runProbe logic is sound: non-sliding cadence, generation fencing, abort-aware error path, and admission-saturation reschedule all correctly modelled.
src/shared/remote-runtime-shared-control-connection.ts Probe integrated at all lifecycle touch-points; generation captured correctly at forceClose call time, not at lambda construction time.
src/shared/remote-runtime-shared-control-requests.ts AbortSignal support added correctly with early-abort fast-path, post-add re-check for the signal→listen race, and releaseCancellation cleanup.
src/shared/remote-runtime-shared-control-state.ts releasePendingRequestCancellation called in all three rejection/resolution paths — no listener leaks.
src/shared/remote-runtime-shared-control-manual-reconnect.ts Logically equivalent extraction but the original Why-comment about backoff bypass was not carried over.
tests/e2e/helpers/zombie-runtime-relay.ts preserveUpstream flag correctly prevents client-socket close after server-side termination; zombifyActiveSessions awaits close confirmation before returning.

Sequence Diagram

sequenceDiagram
    participant C as Client
    participant R as Relay (zombie)
    participant S as Server (restarted)

    C->>R: WS connect
    R->>S: WS connect
    Note over C,S: Normal session established
    C->>R: subscribe(runtime.clientEvents)
    R->>S: subscribe(runtime.clientEvents)
    S-->>R: "{type:ready}"
    R-->>C: "{type:ready}"

    Note over R,S: Server restarts — relay socket stays open
    R-xS: downstream severed (zombifyActiveSessions)
    Note over C,R: Relay still auto-answers RFC 6455 pings

    loop Every 15s probe interval
        C->>R: status.get (encrypted)
        R-xS: forwarded — S has no session
        Note over C: probe times out 10s → force-close
    end

    C->>R: WS close (generation fenced)
    R->>S: new WS connect
    Note over C,S: Fresh E2EE session + subscription replay
    C->>R: subscribe(runtime.clientEvents) replayed
    R->>S: subscribe(runtime.clientEvents)
    S-->>R: "{type:ready} + new worktree events"
    R-->>C: new worktree events
    Note over C: Sidebar updated
Loading

Reviews (1): Last reviewed commit: "fix(remote-runtime): bound session probe..." | Re-trigger Greptile

Comment on lines +4 to +14
export function reconnectSharedControlNow(
unavailable: boolean,
closeSocket: (error: RemoteRuntimeClientError) => void,
open: () => void
): void {
if (!unavailable) {
return
}
closeSocket(remoteRuntimeUnavailableError('Refreshing remote runtime control transport.'))
open()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The original reconnectNow inline code carried a Why comment explaining that the caller should replace even a stuck CONNECTING/awaiting-ready socket rather than wait behind stale backoff when the endpoint is known to be reachable. That rationale is lost here, so the function now reads as a plain guard without signalling its intent to future readers.

Suggested change
export function reconnectSharedControlNow(
unavailable: boolean,
closeSocket: (error: RemoteRuntimeClientError) => void,
open: () => void
): void {
if (!unavailable) {
return
}
closeSocket(remoteRuntimeUnavailableError('Refreshing remote runtime control transport.'))
open()
}
export function reconnectSharedControlNow(
unavailable: boolean,
closeSocket: (error: RemoteRuntimeClientError) => void,
open: () => void
): void {
if (!unavailable) {
return
}
// Why: replace even a stuck CONNECTING/awaiting-ready socket instead of
// waiting behind stale backoff when the caller has proof the endpoint is reachable.
closeSocket(remoteRuntimeUnavailableError('Refreshing remote runtime control transport.'))
open()
}

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restored the Why comment on the replace-stuck-socket path in 4c324295a8.

Comment on lines +28 to +36
schedule(): void {
if (
this.hooks.isIntentionallyClosed() ||
!this.hooks.hasSubscriptions() ||
!this.hooks.isReady()
) {
this.clear()
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 schedule() is side-effectful in the negative case: when any of the three guard conditions fails it calls clear(), which cancels the timer and aborts any in-flight probe. This is intentional and tested (the "in-flight probe retirement" case relies on it), but the method name alone implies a purely-additive operation. A Why comment here would help the next reader who calls schedule() expecting it never tears down an existing probe.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a Why comment noting that schedule() doubles as teardown when its guards fail (4c324295a8).

@tomdebres
tomdebres force-pushed the fix/self-heal-stale-subscriptions branch 2 times, most recently from 8181d68 to 4c32429 Compare August 7, 2026 17:18
@coderabbitai

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

@tomdebres

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (resolved the reliability-gates.jsonc conflict by keeping both gate entries) and addressed both review threads. Also pinned the shared-control test server to 127.0.0.1: on macOS a concurrent process binding the same ephemeral port on loopback shadows a wildcard listener, which intermittently hijacked the test connections on a machine running the Orca app. Focused shared-control tests pass 8/8 consecutive runs; typecheck and lint clean.

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

🧹 Nitpick comments (3)
src/shared/remote-runtime-shared-control-session-probe.test.ts (1)

55-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the positive forceClose case.

Both tests assert the negative path: the probe must not force a close after the subscription ends. No test asserts that forceClose runs when a probe fails while the socket is unchanged and subscriptions remain active. That branch is the core failure behavior of SharedControlSessionProbe. Add a test that rejects the probe without calling probe.clear() and asserts forceClose receives the mapped error.

tests/e2e/helpers/zombie-runtime-relay.ts (1)

91-110: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the destructured connection instead of an index lookup.

Line 104 reaches back into active[index] to set preserveUpstream on the element the callback already receives. Destructure the connection itself. The flag must still be set before terminate(), which the rewrite preserves.

♻️ Proposed refactor
       await Promise.all(
         active.map(
-          ({ downstream }, index) =>
+          (connection) =>
             new Promise<void>((resolve) => {
-              active[index].preserveUpstream = true
-              downstream.once('close', resolve)
-              downstream.terminate()
+              connection.preserveUpstream = true
+              connection.downstream.once('close', resolve)
+              connection.downstream.terminate()
             })
         )
       )
tests/e2e/pr10235-stale-subscription-restart.spec.ts (1)

72-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename readSharedControlGeneration to match the value it reads.

The function reads remoteControl?.lastConnectedAt, which is a timestamp, not a generation counter. The name and the sharedControlGenerationBeforeFault variable at line 122 suggest a monotonic generation identifier. Rename both to reference lastConnectedAt so a later reader does not assume generation semantics.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c08386da-b0da-4c06-a8f4-08fc057a081a

📥 Commits

Reviewing files that changed from the base of the PR and between bc1e049 and 4c324295a81f57c0625483dd992b2bd15540ad57.

📒 Files selected for processing (16)
  • config/reliability-gates.jsonc
  • src/shared/remote-runtime-shared-control-connection.test.ts
  • src/shared/remote-runtime-shared-control-connection.ts
  • src/shared/remote-runtime-shared-control-frame-dispatch.ts
  • src/shared/remote-runtime-shared-control-frame-handler.ts
  • src/shared/remote-runtime-shared-control-manual-reconnect.ts
  • src/shared/remote-runtime-shared-control-ready.ts
  • src/shared/remote-runtime-shared-control-requests.ts
  • src/shared/remote-runtime-shared-control-session-probe.test.ts
  • src/shared/remote-runtime-shared-control-session-probe.ts
  • src/shared/remote-runtime-shared-control-socket-generation.ts
  • src/shared/remote-runtime-shared-control-state.ts
  • src/shared/remote-runtime-shared-control-test-server.ts
  • src/shared/remote-runtime-shared-control-types.ts
  • tests/e2e/helpers/zombie-runtime-relay.ts
  • tests/e2e/pr10235-stale-subscription-restart.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/shared/remote-runtime-shared-control-socket-generation.ts
  • src/shared/remote-runtime-shared-control-ready.ts
  • config/reliability-gates.jsonc

tomdebres and others added 6 commits August 9, 2026 09:30
Add an encrypted session probe to the shared control connection: a
WS-terminating relay answers protocol pings itself, so a restarted
orca serve behind it looks alive while its subscription registry is
gone. A failed probe force-closes into the existing reconnect+replay
machinery.

Split out of stablyai#9614.
…st server to loopback

- Restore the "Why" comment on reconnectSharedControlNow's replace-stuck-socket path
- Document that schedule() doubles as teardown when its guards fail
- Bind the shared-control test server to 127.0.0.1 explicitly: on macOS a
  concurrent process binding the same ephemeral port on loopback shadows a
  wildcard listener and hijacks the tests' connections

Co-Authored-By: Claude Fable 5 <[email protected]>
@tomdebres
tomdebres force-pushed the fix/self-heal-stale-subscriptions branch from 4c32429 to a01f38f Compare August 9, 2026 08:36
@coderabbitai

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

…den tests

- requireSessionProbeSuccess throws on an ok:false status.get response so lost
  session authority triggers recovery instead of a reschedule (+ failMethods
  coverage)
- createSharedControlSessionProbe rejects zero/negative/non-finite timing
  overrides with a RangeError (+ test)
- Probe connection tests close their connection in finally
- Test server captures a per-connection index for ready-frame suppression and
  consumes the one-shot close-after-streaming flag when the response is sent,
  so delayed paths still observe the close
- E2E seed commit disables gpgsign; the stale-surface check is a single
  immediate read instead of a 2s negative poll

Co-Authored-By: Claude Fable 5 <[email protected]>
@tomdebres

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (kept both new upstream gates plus this branch's session-authority gate in reliability-gates.jsonc) and addressed all seven review findings — both majors (ok:false probe responses now trigger recovery via requireSessionProbeSuccess; probe timing overrides are validated) and the five minors. 40 focused shared-control tests pass 3/3 runs, the headless pr10235 e2e journey passes (32s), and typecheck is clean. Note: pnpm lint currently warns on src/renderer/src/components/WorktreeJumpPalette.tsx (react-hooks exhaustive-deps) — that file is byte-identical to upstream main and untouched by this branch.

@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/shared/remote-runtime-shared-control-session-probe.test.ts (2)

55-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Drain microtasks with a timer advance instead of counting await Promise.resolve().

Lines 90-91 assume runProbe needs exactly two microtask turns after the rejection before it can reach forceClose. Line 70 makes the same assumption. If a future change adds an await inside runProbe, these tests pass even when the guard is removed, because forceClose has not run yet at assertion time. vi.advanceTimersByTimeAsync(0) drains the microtask queue without depending on the turn count.

♻️ Proposed change
     rejectProbe(new Error('session lost'))
-    await Promise.resolve()
-    await Promise.resolve()
+    await vi.advanceTimersByTimeAsync(0)
 
     expect(forceClose).not.toHaveBeenCalled()

Apply the same change at line 70:

     await pendingProbe
-    await Promise.resolve()
+    await vi.advanceTimersByTimeAsync(0)

104-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the socket-replacement guard.

state.socket and state.intentionallyClosed are never mutated by any test in this file. Two guards in runProbe stay uncovered: the getSocket() === probedSocket check that stops a stale probe from force-closing a replacement socket, and the isIntentionallyClosed() check. The socket-replacement guard is the one that protects a recovered session, so a regression there is expensive.

Add a test that reassigns state.socket to a second object while a probe is pending, rejects the probe, and asserts forceClose is not called.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fbf55052-b353-4768-b63b-ee6d14976eb0

📥 Commits

Reviewing files that changed from the base of the PR and between 9f7522d and a01f38f.

📒 Files selected for processing (16)
  • config/reliability-gates.jsonc
  • src/shared/remote-runtime-shared-control-connection.test.ts
  • src/shared/remote-runtime-shared-control-connection.ts
  • src/shared/remote-runtime-shared-control-frame-dispatch.ts
  • src/shared/remote-runtime-shared-control-frame-handler.ts
  • src/shared/remote-runtime-shared-control-manual-reconnect.ts
  • src/shared/remote-runtime-shared-control-ready.ts
  • src/shared/remote-runtime-shared-control-requests.ts
  • src/shared/remote-runtime-shared-control-session-probe.test.ts
  • src/shared/remote-runtime-shared-control-session-probe.ts
  • src/shared/remote-runtime-shared-control-socket-generation.ts
  • src/shared/remote-runtime-shared-control-state.ts
  • src/shared/remote-runtime-shared-control-test-server.ts
  • src/shared/remote-runtime-shared-control-types.ts
  • tests/e2e/helpers/zombie-runtime-relay.ts
  • tests/e2e/pr10235-stale-subscription-restart.spec.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • src/shared/remote-runtime-shared-control-frame-dispatch.ts
  • src/shared/remote-runtime-shared-control-manual-reconnect.ts
  • src/shared/remote-runtime-shared-control-types.ts
  • src/shared/remote-runtime-shared-control-ready.ts
  • src/shared/remote-runtime-shared-control-socket-generation.ts
  • src/shared/remote-runtime-shared-control-frame-handler.ts
  • src/shared/remote-runtime-shared-control-state.ts
  • src/shared/remote-runtime-shared-control-requests.ts
  • tests/e2e/helpers/zombie-runtime-relay.ts
  • src/shared/remote-runtime-shared-control-test-server.ts
  • src/shared/remote-runtime-shared-control-session-probe.ts
  • config/reliability-gates.jsonc

JustShinobi added a commit to JustShinobi/orca that referenced this pull request Aug 10, 2026
createGitRepo removes its temp directory when a git step throws, repo creation
happens inside the oracle's try so the client/relay always dispose, and each
teardown step catches its own rejection so cleanup completes and the original
test error propagates.

Co-Authored-By: Claude Fable 5 <[email protected]>
@tomdebres tomdebres closed this Aug 18, 2026
@tomdebres
tomdebres deleted the fix/self-heal-stale-subscriptions branch August 18, 2026 22:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants