Skip to content

fix(runtime-rpc): answer over-limit local connections with runtime_busy instead of dropping them - #22351

Open
Jinwoo-H wants to merge 1 commit into
mainfrom
jinwoo/rpc-busy-reply
Open

Jinwoo-H wants to merge 1 commit into
mainfrom
jinwoo/rpc-busy-reply

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​355 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​355
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​195 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​187

ELI5

Orca's local command socket accepted at most 32 connections at once. When agents fired more orca commands than that in parallel, Orca hung up on the extras without saying anything. The orca command read that as "Orca is dead" and printed "Restart Orca… Orca is not running", even though Orca was running and those commands had never run. Now Orca answers the extras with "busy, try again". The command retries on its own, and if Orca is still busy it says so instead of telling you to restart.

What Changed

Before (35 parallel commands, each held for 2 s by the runtime):

  • 32 succeed. 3 fail within 4 ms with runtime_unavailable: The Orca runtime closed the connection before responding. Restart Orca and try again. / Orca is not running. Run 'orca open' first. The runtime never saw those 3 requests.
  • orca status while the socket is full: runtime.state: "starting", reachable: false, connectionState: "disconnected".

After:

  • All 35 succeed. The 3 extra requests get a busy reply, the CLI retries them, and each request runs exactly once.
  • If the socket stays full for the whole retry budget, the command fails with runtime_busy:
    Orca is busy (connection limit); retry shortly.
    Next step: Retry the command in a few seconds.
    
    It prints no restart advice.
  • orca status while the socket is full: runtime.state: "busy", reachable: true, connectionState: "connected", graph.state: "unknown", exit 0.

Mechanism.

  1. Server (unix-socket-transport.ts, new unix-socket-busy-reply.ts). The transport now counts admitted connections itself instead of relying on Node's server.maxConnections, which closes excess sockets without sending anything. A connection over the limit goes to a reject path. That path reads only far enough to learn the request id: a full line, or the first 64 KB, where the CLI always writes id first. It answers with an ordinary failure frame, {id, ok:false, error:{code:'runtime_busy', message, data:{retryable:true, reason:'connection_limit', dispatched:false, nextSteps}}}, then half-closes the socket and keeps discarding input so a client still sending doesn't get EPIPE before it reads the reply. The reject path never calls the message handler. If no id arrives within 2 s the socket is closed, and a replied socket is closed 2 s after the reply at the latest. server.maxConnections stays as a hard ceiling at twice the limit. Past that ceiling Node still drops sockets unread, so a flood can't make the runtime hold unbounded busy sockets. The worst case is 128 sockets × 64 KB, held for at most 4 s.
  2. Limit: 32 → 128. This matches the WebSocket transport's cap (MAX_WS_CONNECTIONS = 128). File descriptors aren't the constraint. Measured on macOS with Electron 43.7.0 launched from a shell with soft ulimit -n 256 (the launchd default), the main process runs with soft RLIMIT_NOFILE 1048575 because Chromium raises it at startup, and it opened 3000 socket pairs without EMFILE. Windows named pipes are created with unlimited instances, so the 256 hard ceiling is the binding bound there.
  3. Long-poll caps unchanged (LONG_POLL_CAP = 16, only the comment changed). The cap exists so long-polls can't starve short calls. At 16 of 128 that holds more strongly than before. Raising it would also change the ask, browser-host and per-device sub-caps, which are sized for paired-desktop overlap, and long-poll overflow already gets a clean runtime_busy.
  4. CLI (transport.ts). sendRequest resends only when the failure is runtime_busy and data.dispatched === false. It makes up to 3 resends with jittered 250/600/1200 ms backoff, all inside the caller's own timeout. A long-poll admission runtime_busy has no dispatched flag, so it is not retried: that request did reach the handler. status.ts treats a runtime_busy reply as proof the runtime is alive. CliRuntimeState gains 'busy', and graph.state gains 'unknown', because a busy reply says nothing about the graph.

Why

The runtime must not answer overload with silence. The client can't tell a silent close from a crash, so it gave crash advice for a runtime that was healthy. A typed reply tells the client the truth, and the dispatched:false flag makes retrying provably safe even for mutations. Alternatives considered:

  • Only raise the limit. This shrinks the window but keeps the misleading failure for whatever burst still overflows it.
  • Retry any runtime_unavailable on the client. An EPIPE or clean close can also mean the runtime crashed mid-request, and resending a mutation then could apply it twice.
  • Reply busy without reading the request. Every client checks the reply's id against its request. A frame without the right id reads as invalid_runtime_response on old and new CLIs alike.

Mixed versions. Old CLI + new runtime: the frame is a normal failure envelope with an optional _meta omitted, which RuntimeRpcEnvelopeSchema (unchanged since before this PR) accepts. Running origin/main's transport.ts + cli-error.ts against the new server gives runtime_busy and prints the message plus Next step: Retry the command in a few seconds., with no restart text and no retry. New CLI + old runtime: overflow is still a silent drop, as before. Nothing new is required from either side.

Linked Issue

Fixes #

Visual Proof

N/A. This changes CLI and socket behavior, not UI. The test output below shows the before and after.

Testing

Two test files, one per side of the wire:

  • Server, src/main/runtime/rpc/unix-socket-connection-limit.test.ts. This drives the real UnixSocketTransport with a small in-test client that writes one request line and reads frames.

    • A burst of 35 concurrent requests against a 32-connection limit: every request gets a frame that passes RuntimeRpcEnvelopeSchema. That is 32 real replies and 3 runtime_busy frames with dispatched:false. The handler ran exactly 32 times, and none of the busy ids reached it. On origin/main's transport this fails: request req-32 got nothing back, which is the silent close.
    • An over-limit socket gets the exact busy frame for its own id.
    • An over-long request line (200 KB) is still answered by its leading id.
    • Garbage and silent sockets are closed without a reply. The silent one closes within the deadline.
    • Sockets past the 2× ceiling are dropped unread within 500 ms and never dispatched.
  • CLI, src/cli/runtime/connection-limit-retry.test.ts. A fake socket server emits the busy frame.

    • A resend succeeds after two busy replies.
    • Resending is bounded: 4 attempts, after which the busy failure is returned.
    • No resend happens once the caller's timeout would run out.
    • A runtime_busy without dispatched:false (long-poll admission) is sent once.
    • orca status against a runtime that stays busy reports busy, reachable, connected.
    • The frame validates against RuntimeRpcEnvelopeSchema, and formatCliError prints the busy message and next step with no restart text.
    • On origin/main's transport.ts and status.ts, the resend, bounded-resend and status tests fail. The schema and formatting tests pass on origin/main as well, so an old CLI already handles the frame.
  • A scratch run of origin/main's transport.ts against the new server also returned runtime_busy and printed the retry step, with no restart text. That run was not committed.

  • macOS only. The socket tests are skipped on Windows, like the existing transport tests.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH / remote: the local socket always lives on the execution host. The remote path uses the WebSocket transport, which is unchanged and already sends 1013 over its cap.
  • Windows: named pipes go through the same connection callback. The busy path isn't exercised on Windows in CI.
  • Performance: the reject path does one JSON.parse of at most one line, or a regex over at most 64 KB.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…sy instead of dropping them

The local socket closed connections past its 32-slot limit unread, so the CLI
reported a dead runtime ("Restart Orca") for requests that never ran. Over-limit
sockets now get a runtime_busy reply marked dispatched:false, the CLI resends
those with short backoff, and orca status reports a busy runtime as reachable.
The limit rises to 128, matching the WS cap.
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The runtime connection limit now defaults to 128 and can be configured. When the limit is reached, the Unix-socket transport can return a structured runtime_busy response for the request. The CLI retries eligible undispatched busy responses within the original timeout budget and reports the runtime as busy in status output. The change also updates the long-poll capacity comment.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 855e7

A delayed retry can send a request after its timeout. This narrow timing issue should be fixed by rechecking the deadline.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: over-limit local connections receive a runtime_busy reply instead of being dropped.
Description check ✅ Passed The description covers the user impact, implementation, rationale, compatibility, and tests. It marks visual proof as N/A and addresses the template’s other sections. However, Fixes # has no issue n…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ffa8008e-d03e-43b7-af14-8205feb17c35

📥 Commits

Reviewing files that changed from the base of the PR and between 7cb4380 and 855e7be.

📒 Files selected for processing (9)
  • src/cli/runtime/connection-limit-retry.test.ts
  • src/cli/runtime/status.ts
  • src/cli/runtime/transport.ts
  • src/main/runtime/rpc/unix-socket-busy-reply.ts
  • src/main/runtime/rpc/unix-socket-connection-limit.test.ts
  • src/main/runtime/rpc/unix-socket-transport.ts
  • src/main/runtime/runtime-rpc/runtime-rpc-long-poll.ts
  • src/shared/runtime-rpc-connection-limit.ts
  • src/shared/runtime-session-contracts.ts

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

return response
}
const delayMs = Math.round(baseDelayMs * (0.5 + Math.random()))
attemptTimeoutMs = deadline - Date.now() - delayMs

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,185p' src/cli/runtime/transport.ts
sed -n '90,138p' src/cli/runtime/connection-limit-retry.test.ts

Repository: stablyai/orca

Length of output: 8627


🏁 Script executed:

sed -n '135,285p' src/cli/runtime/transport.ts
rg -n -C 3 "timeoutMs|sendRequest\\(" src/cli/runtime -g '*.ts' | head -180
sed -n '1,115p' src/cli/runtime/connection-limit-retry.test.ts

Repository: stablyai/orca

Length of output: 20317


Recheck the deadline after each backoff.

If the backoff timer fires after the deadline, attemptTimeoutMs still holds its pre-wait value. sendRequestOnce can then connect and send a state-changing request after the caller’s timeout. Recalculate the remaining budget after the wait and return the busy response if no time remains.

🐛 Suggested fix
     await new Promise<void>((resolve) => setTimeout(resolve, delayMs))
+    attemptTimeoutMs = deadline - Date.now()
+    if (attemptTimeoutMs <= 0) {
+      return response
+    }

@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

  • Over-limit connections now get a typed reply. UnixSocketTransport counts admitted connections itself and routes excess sockets to replyConnectionLimitBusy, which reads only the request id (one line, or the leading "id" within 64 KB) and answers with the same failure envelope every CLI decoder accepts — never dispatching. This removes the silent close that made the CLI blame a healthy runtime.
  • The limit moves 32 → 128 with Node's server.maxConnections kept at 2× as a hard ceiling, bounding rejected-socket memory and lifetime (128 × 64 KB, ≤ 4 s).
  • CLI resend is provably safe. sendRequest resends only a runtime_busy whose data.dispatched === false, with three jittered backoffs inside the caller's timeout; long-poll admission runtime_busy has no such flag and is sent once.
  • orca status reports a busy runtime as alive (state: 'busy', reachable: true, graph.state: 'unknown'), and CliRuntimeState/graph unions gain the new members.
  • Tests cover both sides of the wire with exact-frame assertions (burst past limit → 32 ok + 3 busy, none dispatched; over-long line named by its leading id; ceiling drop; CLI resend/bound/timeout/long-poll cases).

I traced the load-bearing safety claim end to end and independently confirmed it: the connection-limit reject is the only producer of runtime_busy with data.dispatched === false across src/main, src/shared, and src/cli; long-poll admission and the WebSocket path build their runtime_busy via errorResponse with no data, and mapRuntimeError flattens any handler-thrown runtime_busy to runtime_error. So an automatic resend cannot double-apply a mutation. I also checked the new activeSockets/busySockets accounting, the reply deadline timer, and stop() teardown; no leak, miscount, or unreplied reachable branch beyond the two documented cases (the 2× Node ceiling, and a frame whose id cannot be extracted). The new tests, the existing transport/status suites, and the wrapping recovery path all behave as described.

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

This branch has not been deployed

No deployments
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