Repository navigation
perf(cli): construct the runtime client only when a command needs it - #10919
Conversation
|
Warning Review limit reached
Next review available in: 9 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (15)
📝 WalkthroughWalkthroughThe CLI now loads 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
src/cli/handlers/computer-action-validation.test.ts (1)
12-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCondense the explanatory test comments.
src/cli/handlers/computer-action-validation.test.ts#L12-L15: replace with one concise identity rationale.src/cli/handlers/computer.test.ts#L12-L14: replace with one concise identity rationale.src/cli/handlers/emulator.test.ts#L21-L23: replace with one concise identity rationale.src/cli/handlers/linear.test.ts#L22-L24: replace with one concise identity rationale.src/cli/index.test.ts#L26-L29: replace with one concise identity rationale.src/cli/runtime-client-deferral.test.ts#L11-L13: condense to the mock-boundary purpose.src/cli/runtime-client-deferral.test.ts#L51-L53: condense or remove the implementation walkthrough.src/cli/runtime-client-deferral.test.ts#L86-L97: reduce to the non-obvious safety rationale.src/cli/runtime-client-deferral.test.ts#L124-L127: condense to the dispatch-stubbing purpose.src/cli/runtime-client-deferral.test.ts#L150-L152: condense to the non-suppressed fallback purpose.src/cli/runtime-client-deferral.test.ts#L169-L171: remove as duplicate rationale.src/cli/runtime-client-deferral.test.ts#L196-L197: condense to the memoization purpose.As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”
Source: Coding guidelines
config/scripts/cli-runtime-client-deferral-benchmark.mjs (3)
125-139: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd the same spawn timeout the equivalence script uses.
With
ROUNDS=30andWARMUP=3each case spawns ~66 processes; a single hung invocation stalls the benchmark forever instead of failing.♻️ Bound each sample
+const RUN_TIMEOUT_MS = 30_000 + function run(entry, argv, env) { const result = spawnSync(process.execPath, [entry, ...argv], { cwd: REPO, env: { ...process.env, ...env }, - encoding: 'buffer' + encoding: 'buffer', + timeout: RUN_TIMEOUT_MS, + killSignal: 'SIGKILL' })
82-123: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftThe two scripts duplicate the whole build harness, so every fix has to be applied twice.
TOUCHED, the baseline-restore-in-finallypattern, thenpx tscinvocation, and most ofassertMarkersFreshare copy-pasted; the signal-safety and Windows-portability gaps already flagged exist identically in both copies.
config/scripts/cli-runtime-client-deferral-benchmark.mjs#L82-L123: extractbuildArmplusTOUCHEDand the marker checks into a shared module with a concrete domain name (e.g.config/scripts/cli-deferral-build-arms.mjs) and import it here; apply the signal-safe restore and the portable tsc invocation in that single place.config/scripts/cli-runtime-client-deferral-equivalence.mjs#L65-L104: replace the localbuildTree/TOUCHEDcopies with imports from that module.As per coding guidelines, avoid vague names such as
helpers,utils,common,misc, orshared-stufffor the extracted module.Source: Coding guidelines
143-164: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winVerify the CLI entrypoint before relying on this probe.
The CLI source dispatches from
require.main === moduleand callsmain()directly, so loading the built entry can execute side effects. Either have only the probe entrypoint import the exportedmainand call it behind an explicit flag/condition for counting, or keep the entrypoint out of the measured module graph.config/scripts/cli-runtime-client-deferral-equivalence.mjs (1)
438-439: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the unused
emptysubdirectory and add repo ignore entries for the script’s temp directories.
isolatedUserDatais only used to setORCA_USER_DATA_PATH;mkdtempSync(...)/mkdirSync(..., 'empty')is unnecessary. The script can still leave.equiv-userdata-*and.equiv-out-*inside the repo after a kill, and.gitignorehas no coverage for them, so add gitignore entries for these temporary directories.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 34f66a9a-84a6-4f29-8fe1-ceeb51fe4441
📒 Files selected for processing (15)
config/scripts/cli-runtime-client-deferral-benchmark.mjsconfig/scripts/cli-runtime-client-deferral-equivalence.mjssrc/cli/args.tssrc/cli/dispatch.tssrc/cli/flags.tssrc/cli/format.tssrc/cli/handlers/computer-action-validation.test.tssrc/cli/handlers/computer.test.tssrc/cli/handlers/emulator.test.tssrc/cli/handlers/linear.test.tssrc/cli/index.test.tssrc/cli/index.tssrc/cli/runtime-client-deferral.test.tssrc/cli/runtime/client.tssrc/cli/selectors.ts
| const baselineIndex = process.argv.indexOf('--baseline') | ||
| const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Baseline defaults to HEAD, so the "eager" arm is not the pre-deferral code.
Same defect as in config/scripts/cli-runtime-client-deferral-equivalence.mjs: once the branch is committed, HEAD already contains the deferral, both arms compile identically, and the run dies at the Line 190 module-count guard rather than benchmarking anything. --baseline with no value also yields undefined, silently skipping the restore.
| const restored = [] | ||
| try { | ||
| if (baselineRev) { | ||
| for (const file of TOUCHED) { | ||
| const path = join(REPO, file) | ||
| restored.push([path, readFileSync(path)]) | ||
| const old = execFileSync('git', ['show', `${baselineRev}:${file}`], { | ||
| cwd: REPO, | ||
| maxBuffer: 64 * 1024 * 1024 | ||
| }) | ||
| writeFileSync(path, old) | ||
| } | ||
| } | ||
| execFileSync( | ||
| 'npx', | ||
| [ | ||
| 'tsc', | ||
| '-p', | ||
| 'config/tsconfig.cli.json', | ||
| '--outDir', | ||
| outDir, | ||
| '--composite', | ||
| 'false', | ||
| '--incremental', | ||
| 'false' | ||
| ], | ||
| { cwd: REPO, stdio: 'inherit' } | ||
| ) | ||
| } finally { | ||
| for (const [path, contents] of restored) { | ||
| writeFileSync(path, contents) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Ctrl+C during the baseline build leaves the working tree clobbered.
finally does not run for SIGINT/SIGTERM, and the tsc compile is the longest part of the run — the exact window a user is likely to interrupt. The tree is then left holding baseline content for the seven touched files with no indication why.
Register a restore-once handler for SIGINT/SIGTERM (and process.on('exit')) that replays restored, then re-raises the signal.
| execFileSync( | ||
| 'npx', | ||
| [ | ||
| 'tsc', | ||
| '-p', | ||
| 'config/tsconfig.cli.json', | ||
| '--outDir', | ||
| outDir, | ||
| '--composite', | ||
| 'false', | ||
| '--incremental', | ||
| 'false' | ||
| ], | ||
| { cwd: REPO, stdio: 'inherit' } | ||
| ) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm the local tsc binary path exists and check how other repo scripts invoke tsc.
fd -H -t f 'tsc' node_modules/typescript/bin 2>/dev/null
rg -n --iglob '*.{mjs,js,ts,json}' -g '!node_modules' "npx'?,?\s*\[?\s*'?tsc|node_modules/typescript/bin/tsc" | head -50Repository: stablyai/orca
Length of output: 183
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="config/scripts/cli-runtime-client-deferral-equivalence.mjs"
if [ -f "$file" ]; then
printf '%s\n' "=== file outline ==="
ast-grep outline "$file" --view compact || true
printf '%s\n' "=== relevant lines 1-140 ==="
cat -n "$file" | sed -n '1,140p'
else
printf '%s\n' "missing $file"
fi
printf '%s\n' "=== repository tsc invocation snippets ==="
rg -n --iglob '*.{mjs,js,ts,json}' -g '!node_modules' "npx|runTsc|tsc|typescri" | sed -n '1,120p'
printf '%s\n' "=== package files mentioning devDependencies or scripts ==="
fd -t f '(^package\.json$|tsconfig\.cli\.json$)' -x sh -c 'echo "--- $1"; sed -n "1,180p" "$1"; sed -n "1,220p" "$1" | grep -nE "typescript|tsc|runTsc|cli-runtime|devDependencies|scripts" || true' sh {}Repository: stablyai/orca
Length of output: 6807
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' "=== lockfiles and package manifests mentioning typescript ==="
fd -t f "^(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|package\.json)$" | xargs -r -n1 sh -c 'echo "--- $1"; rg -n "typescript|packageManager|workspace" "$1" | sed -n "1,80p"'
printf '%s\n' "=== tsconfig.cli.json ==="
if [ -f config/tsconfig.cli.json ]; then
cat -n config/tsconfig.cli.json | sed -n '1,180p'
fi
printf '%s\n' "=== tsc binary package metadata if present ==="
if [ -d node_modules/typescript/bin ]; then
node -e "const tsBin = require.resolve('typescript/bin/tsc'); console.log('resolve:', tsBin); const pkg = require('typescript/package.json'); console.log('typescipt version:', pkg.version || 'unknown')"
fiRepository: stablyai/orca
Length of output: 5879
🌐 Web query:
Node.js child_process execFile Windows batch command extension CMD .cmd shell option documentation
💡 Result:
In Node.js, child_process.execFile does not spawn a shell by default, which is the primary reason it cannot directly execute Windows.bat and.cmd files [1][2]. These files are not standalone executables; they require the Windows command processor (cmd.exe) to interpret and execute them [1][3]. If you need to run a.bat or.cmd file, you have three primary alternatives: 1. Use child_process.exec: Unlike execFile, exec spawns a shell by default, allowing it to interpret batch files correctly [1][4]. 2. Use child_process.spawn with the shell option: You can spawn a command using { shell: true } [1][5]. However, be aware that this approach can introduce security risks if you pass unsanitized user input [4][6]. 3. Explicitly invoke cmd.exe: You can manually spawn the command processor and pass the batch file as an argument using child_process.spawn('cmd.exe', ['/c', 'your-script.cmd']) [1][7]. This is often the most robust way to maintain control over arguments without relying on shell parsing [3]. Regarding the shell option: While child_process.execFile does support a shell option, enabling it (by setting shell: true or specifying a shell path) technically allows you to run batch files, as it changes the behavior to mirror that of exec [1][4]. Note that in newer Node.js versions, using the shell option with an arguments array is discouraged because it can bypass the safety provided by separating the executable from its arguments [3]. For security, avoid using shell options if you are handling unsanitized user input, as it exposes your application to arbitrary command injection [4][6]. If you must execute a batch file, ensure the file path is hardcoded or strictly validated [4].
Citations:
- 1: https://nodejs.org/api/child_process.html
- 2: https://nodejs.org/docs/latest-v24.x/api/child_process.html
- 3: https://www.thenodebook.com/child-processes/spawn-exec-fork
- 4: https://nodejs.org/docs/latest-v22.x/api/child_process.html
- 5: https://r2.nodejs.org/docs/v18.20.2/api/child_process.html
- 6: https://nodejs.org/api/child_process.md
- 7: https://stackoverflow.com/questions/68009544/how-to-make-child-process-exec-run-bat-file
Invoke the local tsc binary instead of relying on npx.
npx resolves to npx.cmd on Windows, and execFile does not launch .cmd scripts without a shell. The repo already ships node_modules/typescript/bin/tsc, so call that directly via process.execPath and add typescript through an npm/pnpm/yarn devDependency so the binary path remains portable.
| const baselineIndex = process.argv.indexOf('--baseline') | ||
| const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Default baseline of HEAD makes the comparison vacuous once the change is committed.
The file header (Line 5) states the baseline arm restores the touched files from HEAD~, but the default rev here is HEAD. After the PR branch is committed, git show HEAD:src/cli/index.ts returns the deferred implementation, so both arms compile identical sources and all 433 invocations match trivially. assertMarkersFresh() inspects the working tree only, so it cannot detect this.
Also, --baseline with no following argument yields undefined, which buildTree treats as "no restore" — again silently comparing the working tree against itself.
🛠️ Proposed fix: default to `HEAD~` and validate the flag value
const baselineIndex = process.argv.indexOf('--baseline')
-const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1]
+const baselineRev = baselineIndex === -1 ? 'HEAD~' : process.argv[baselineIndex + 1]
+if (!baselineRev) {
+ throw new Error('--baseline requires a git revision')
+}Optionally assert the baseline arm really is the pre-deferral code, e.g. verify git show ${baselineRev}:src/cli/index.ts does not contain await loadRuntimeClientClass().
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const baselineIndex = process.argv.indexOf('--baseline') | |
| const baselineRev = baselineIndex === -1 ? 'HEAD' : process.argv[baselineIndex + 1] | |
| const baselineIndex = process.argv.indexOf('--baseline') | |
| const baselineRev = baselineIndex === -1 ? 'HEAD~' : process.argv[baselineIndex + 1] | |
| if (!baselineRev) { | |
| throw new Error('--baseline requires a git revision') | |
| } |
| it('reuses one client instance across repeated ctx.client reads', async () => { | ||
| callMock.mockResolvedValue({ result: { worktrees: [] } }) | ||
|
|
||
| await main(['worktree', 'list', '--json'], '/tmp/repo') | ||
|
|
||
| expect(constructorArgsMock).toHaveBeenCalledTimes(1) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Exercise ctx.client twice before asserting memoization.
This passes if the current handler reads the getter once, even if a second read creates another client. Stub dispatch, dereference its context’s client twice, then assert one construction.
src/cli/index.ts was the only eager value-import of RuntimeClient, and five other eager modules imported just RuntimeClientError / RuntimeRpcFailureError from the runtime-client barrel -- dragging in client -> pairing -> zod -> ws -> e2ee on every invocation. Those error classes live in runtime/types.ts, which has zero children, so the five imports now point there and the client loads through the existing (already lazy by design) ctx.client getter. Eager modules 199 -> 46, with node_modules dropping 94 -> 0. `orca --help` 2.04x (59.6 -> 29.2 ms); the same for help, no-args, and both error paths, which return before constructing a client. Commands that DO construct one still gain 1.10-1.12x from not eagerly parsing the transport the local path never uses. Correction to an earlier note: websocket-transport alone is ~24 modules / ~8 ms, not the 107 / 28 ms once recorded -- that figure wrongly charged it for zod, which enters through shared/pairing on a different edge. Marginal cost, never isolated cost. Co-authored-by: Orca <[email protected]>
7f88f16 to
f20df77
Compare
…r workers (stablyai#9925)" This reverts commit cd05f2f for the v1.4.160-rc.4 cut. Three files needed manual resolution because later commits touched the same regions. Their post-9925 work is preserved: - src/main/runtime/rpc/core.ts and dispatcher.ts keep clientCapabilities and the RuntimeCapability import from stablyai#10129 (close-intent negotiation for paired runtimes). - src/cli/runtime/client.ts keeps the deferred websocket-transport import from stablyai#10919.
…tablyai#10919) src/cli/index.ts was the only eager value-import of RuntimeClient, and five other eager modules imported just RuntimeClientError / RuntimeRpcFailureError from the runtime-client barrel -- dragging in client -> pairing -> zod -> ws -> e2ee on every invocation. Those error classes live in runtime/types.ts, which has zero children, so the five imports now point there and the client loads through the existing (already lazy by design) ctx.client getter. Eager modules 199 -> 46, with node_modules dropping 94 -> 0. `orca --help` 2.04x (59.6 -> 29.2 ms); the same for help, no-args, and both error paths, which return before constructing a client. Commands that DO construct one still gain 1.10-1.12x from not eagerly parsing the transport the local path never uses. Correction to an earlier note: websocket-transport alone is ~24 modules / ~8 ms, not the 107 / 28 ms once recorded -- that figure wrongly charged it for zod, which enters through shared/pairing on a different edge. Marginal cost, never isolated cost. Co-authored-by: Orca <[email protected]>
Description
src/cli/index.tswas the only eager value-import ofRuntimeClientin the tree. Five other eager modules (args,flags,dispatch,format,selectors) imported justRuntimeClientError/RuntimeRpcFailureErrorfrom theruntime-clientbarrel — and that re-export dragged inclient → pairing → zod → ws → e2eeon every invocation, includingorca --help.Those error classes live in
src/cli/runtime/types.ts, which has zero children. The five imports now point there, and the client loads through the existingctx.clientgetter — already lazy by design; its comment even says "local-only handlers must not resolve runtime metadata just to dispatch." The getter stays synchronous, so no handler signature changes.ELI5
Typing
orca --helpused to load the entire networking stack — websockets, encryption, schema validation — before printing a help page it was always going to print without touching the network.Now it loads that only when a command actually needs to talk to something. Help is about twice as fast.
Proof of perf improvement
config/scripts/cli-runtime-client-deferral-benchmark.mjs(new). Both arms are realtscemits of real source — the baseline arm restores the touched files from a git rev and compiles that. Fresh process per sample; arms alternate lead across 30 rounds; per-arm medians.orca --helporca help worktreeorca(no args)orca agent-context --jsonorca status --jsonorca worktree list --jsonEager modules 199 → 46, with
node_modulesdropping 94 → 0.Scope, stated plainly: the 2× rows are help and error paths, which return before constructing a client. Commands that do construct one gain 1.10–1.12× — only from not eagerly parsing the transport the local path never uses. Most invocations are the latter.
A correction to a figure I previously recorded:
websocket-transportalone is ~24 modules / ~8 ms, not the "107 modules / 28 ms" I noted earlier. That number wrongly charged it for zod (79 modules, ~21 ms), which enters via a different edge —runtime/client → shared/pairing → shared/mobile-relay-pairing-offer → zod. Isolated cost overcounts; marginal cost is the shippable number. Same trap that inflated #10788.Proof of zero regression
instanceofidentity preserved —require('./runtime/types').RuntimeClientError === require('./runtime-client').RuntimeClientErroristrue(the barrel re-exports, it doesn't copy).resolveRemotePairingthrows from theRuntimeClientconstructor for--pairing-code+--environmenttogether, malformed codes, and unknown environments. All three compared byte-for-byte.src/cli/: 42 files, 561 tests passing. Bothtsconfig.nodeandtsconfig.tc.clitypecheck clean; oxfmt/oxlint clean.Two verification defects found and fixed by adversarial review
1. The safety guard could hang instead of failing.
assertNoStateMutatingCases()existed specifically to prevent anorca agent hooks offincident — butservewas in the fuzz pool and absent from the blocklist. Replaying the fixed seed: 15 of 400 cases lead withserve, which spawns Orca in the foreground and blocks, andspawnSynchad notimeout. It passed only by luck, becauseresolveForegroundOrcaExecutable()happened to throw first on this machine.Both halves fixed, and the design changed rather than just patched: a deny list only catches verbs someone thought of, which is precisely how
servesurvived review. There is now a fail-closedREAD_ONLY_FUZZ_TOKENSallowlist — every token in the pool must be explicitly declared read-only. I verified this by reintroducing the exact original defect (serveback in the pool, removed from the foreground list) and confirming it still fails:Fuzz token "serve" is not declared in READ_ONLY_FUZZ_TOKENS.run()also takes a 30 s timeout, so a hang is now a named failure.Critically, the guard was not masking a real difference — that was proven, not assumed, since it would have changed the verdict:
servecompared across 66 cases andagent hooks on|off|statusacross 27 (in a throwawayHOME, diffing the resultingsettings.jsonas well as output), 0 mismatches.2. A test was 4/5 vacuous. The
it.eachasserting constructor args looped overmock.calls, so the four cases constructing nothing passed on an empty loop body — instrumentation confirmed counts ofagent=1, environment=0, serve=0, vm=0, agent-context=0. Restructured to assert the expected construction count first, unconditionally. Verified by mutation: makingctx.clientreturn a stub for a group that must construct one now fails 10 tests; under the original test it was silently green.Still unverified, stated rather than glossed: the
serveandagent-hookscomparisons ran through throwaway harnesses (the committed script still deliberately excludes those paths), macOS/Node 24 only, and theservecomparison used a stub executable — the real Electron foreground path was never spawned.Review loop count + verdict
3 loops. Round 1 implemented and measured. Round 2 (adversarial) reproduced the speedup independently but returned FIX_FIRST on the two verification defects above. Round 3 fixed both, replaced the deny list with a fail-closed allowlist, and re-proved the excluded paths were equivalent.
Verdict: ship.
Made with Orca 🐋