Skip to content

perf(ssh): share relay native deps across bundles instead of recompiling per install dir - #18033

Merged
nwparker merged 1 commit into
mainfrom
feat/relay-native-deps-cache
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
feat/relay-native-deps-cache

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​825 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​825
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​911 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​904

Closes the first option in #18009 — item A's root cause. Removes the recompile that happens on every relay bundle change.

ELI5

Relay node_modules lived inside the bundle-hash-keyed directory ~/.orca-remote/relay-<version>+<hash>, with no reuse path and GC deleting the old dir wholesale. So any byte change in src/relay/ or the src/shared/ it pulls in minted a new directory and a fresh npm install — a node-gyp source compile on Linux, since node-pty ships no Linux prebuild.

Measured: 105 commits touched src/relay and 501 touched src/shared in 30 days, across 31 of 31 days. NATIVE_DEPS_COMMAND_TIMEOUT_MS is 240s inside a 900s deploy budget — eight of the fifteen deploy minutes were native deps, on a dependency set that is a pinned constant and hasn't changed in this sweep.

The directory key was coupled to the wrong quantity: identity churned at the rate of the JS bundle, while the expensive contents changed approximately never.

Now node_modules lives at ~/.orca-remote/native/<relayPlatform>-<depsHash>/node_modules, and each relay directory holds a symlink to it. depsHash covers RELAY_NATIVE_DEPS, an explicit epoch constant, and the bytes of every shipped node-pty-* patch artifact — so a patch change mints a new entry rather than leaving hosts on a tree built from the old one.

The four design questions, answered with evidence

1. Link, not copy. probeInstalledNativeDeps runs node -e require(...) with cwd = the relay dir, and makeNodePtySpawnHelperExecutable runs find <relayDir>/node_modules/node-pty/prebuilds. Both resolve through the symlink unchanged — neither needed a code change. Node realpaths module paths, so node-pty and @parcel/watcher load their own siblings out of the shared tree.

Windows is excluded rather than given a junction, and deliberately: node-pty's npm tarball already ships win32 prebuilts (no compile to avoid), and node-pty-1.1.0-console-list-agent-patch.cjs mutates the installed tree in place, which the immutability rule forbids for a shared one. The defect is Linux-only.

2. GC is reference-based, not refcounted — and did not need to be a bigger project. The symlink is the reference, so there is no counter to drift. remote-install-gc.ts's discipline is carried over verbatim: a listing that doesn't end in its own OK token, an unreadable link, or a reference shape this client never writes aborts the whole pass, not just that candidate. Deletion is the same three-step move — tombstone-rename → re-read references under the rename → remove — so a deploy that linked between the listing and the rename shows up in the recheck and gets its tree moved back.

3. No lock was needed, and ssh-relay-install-lock.ts is deliberately not invoked. Publication elects with mkdir "$cache", which is atomic and yields exactly one winner; a loser keeps its own tree. Because a published entry is immutable, there is no window where two deploys write one tree — the lock would have guarded nothing and added ~8 execs to the miss path. The crashed-winner case (entry exists, no .deps-complete) is reclaimed by an age rule, safe precisely because nothing links an entry until it is complete.

4. Migration seeds from an existing install. A first deploy on an existing host seeds by cp -Rp from a sibling relay-*/node_modules whose package.json pins the same versions and still has node-pty (so a toolchain-skip install can't qualify) — no recompile, no network. The seed isn't trusted: it stays a private install until the normal probe loads it, and only then is it published.

The hazard this could have introduced

A repair does rm -rf node_modules/node-pty — which through a shared symlink would be every relay on the host losing its addon. Two things close it: repairs opt out of the cache entirely (resetDeps.length === 0 gate), and every npm install is prefixed with if [ -L node_modules ]; then rm -f node_modules; fi; — zero extra execs, since it rides the existing install exec. A linked entry that fails to load falls back to a private install for that directory and never repairs the shared one.

Exec-count impact

Cache hit: net zero (the ensure exec replaces the npm install exec). Miss: +2. Repair and Windows: unchanged, so makeRepairToolchainSkipExecResponses and the repair sequences needed no edits.

User-facing regressions

None expected. The fallback is intact: if the cache cannot be created or used, the deploy proceeds with today's per-directory install.

One accepted limitation, documented in the module header: if a published entry later stops loading (a host-level Node or glibc change), each relay directory heals itself privately at today's cost, and the entry is not invalidated — invalidating in place would mean deleting a tree a running relay may hold.

Testing

pnpm test src/main/ssh: baseline 1798 passed; after 1855 passed, 16 skipped. No pre-existing test changed its assertions except two fixture slots.

Before/after on the six required deploy behaviours — with ssh-relay-deploy.ts stashed to its pre-change state: Tests 6 failed | 1 passed (7), including the headline × runs no npm install when a different bundle finds a complete entry on the host. Restored: Tests 7 passed (7).

ssh-relay-native-deps-cache-shell.test.ts runs the real scripts against a real temp tree under both /bin/sh and dash (Debian/Ubuntu's /bin/sh) — 26 tests covering publish/link/seed, one-winner election, a loser keeping its tree, and rm -rf of a linked relay dir leaving the shared tree intact. Asserting on command strings could not have shown any of that.

tc:node clean; check:code-quality:changed 0 findings across 11 files.

Note on the alternative

#1693 (prebuilt slots) was assessed and is much further away — the CI matrix does not exist, build-orcad-prebuilds.mjs cannot produce a Linux slot, nothing ships the prebuilds directory, and the nodeAbi gate would reject on every real host since the relay borrows the host's Node. See the correction comment on #18009. This PR needs none of that.

Relay node_modules lived inside `~/.orca-remote/relay-<version>+<hash>`, so
any byte change in `src/relay/` or the `src/shared/` it pulls in minted a new
directory and a fresh `npm install [email protected] @parcel/[email protected]`. On
Linux node-pty has no prebuild, so that is a node-gyp source compile on every
new bundle — eight of the fifteen deploy minutes, daily, on a dependency set
that is a pinned constant (#18009).

The tree now lives at `~/.orca-remote/native/<platform>-<depsHash>/node_modules`
and each relay directory symlinks to it. depsHash covers RELAY_NATIVE_DEPS, an
explicit epoch, and the bytes of every shipped `node-pty-*` patch artifact, so a
patch change mints a new entry rather than leaving hosts on a stale tree.

Three rules make one tree safe to share:

- A published entry is immutable. `.deps-complete` is written last, only after
  a probe on that host loaded both addons. Nothing installs, rebuilds or resets
  into a published entry: every `npm install` is prefixed with a symlink detach,
  so a repair on one directory can never `rm -rf node_modules/node-pty` out from
  under a live relay sharing the tree.
- Publication elects one winner with `mkdir`, so no client-side lock is needed
  and two deploys never write one tree. A loser keeps its own copy.
- Every failure degrades to today's per-directory install.

GC follows remote-install-gc.ts' discipline: a listing that does not end in its
own OK token, an unreadable link, or a reference whose shape this client never
writes aborts the whole pass. Deletion is tombstone-rename, re-read references
under the rename, then remove — a deploy that linked between the listing and the
rename gets its tree moved back. It only runs for a connection that could
compute a key, and never removes a pinned one.

Migration: a first deploy after this ships seeds its tree from a sibling relay
directory whose manifest pins the same versions, so an existing host does not
recompile once more. The seed is not trusted — it is a plain private install
until the normal probe loads it, and only then is it published.

Windows keeps the per-directory install: node-pty ships win32 prebuilts, so
there is no compile to avoid, and the console-list agent patch mutates the
installed tree in place, which rule 1 forbids for a shared one.

The POSIX scripts are exercised against a real tree under both /bin/sh and
dash, not just asserted on as strings.
@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The SSH relay deployment now uses a shared native-dependencies cache on supported POSIX hosts. Cache keys include platform, dependency versions, installation epoch, and patch contents. Deployments can link, seed, or publish cache entries after successful probes. Private installs detach shared symlinks before writes. Cache garbage collection removes unreferenced entries with tombstone and reference rechecks. Tests cover key generation, shell behavior, deployment flows, and GC safety.

Merge Risk: 🔵 Low · up to b2c43

The PR changes relay native dependencies from per-bundle installs to a shared host cache, reducing repeated compilation. Mergeability remains good, but cleanup races may leave orphaned cache data and a Node ABI change may cause stale entries to miss reuse and fall back to slower private installs; owners should address or explicitly accept these bounded risks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 11 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 identifies the SSH performance change: sharing relay native dependencies to avoid recompilation across install directories.
Description check ✅ Passed The description is detailed and on-topic. It explains the problem, design, safety considerations, linked issue, testing results, platform behavior, and fallback behavior. It does not include every tem…
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 is detailed and on-topic. It explains the problem, design, safety considerations, linked issue, testing results, platform behavior, and fallback behavior. It does not include every template heading or the required explicit visual-proof N/A statement, but the substantive information is mostly complete.

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/ssh/ssh-relay-native-deps-cache.ts (1)

76-86: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Include the remote Node ABI in the cache key.

resolveRelayNativeDepsCacheKey hashes only the epoch, dependency versions, and patch sources. Linux compiles node-pty against the remote Node runtime. After an ABI change, the linked entry can fail the probe; the deploy then detaches it, installs privately, and cannot republish because the complete entry already owns that key. Include the remote runtime's process.versions.modules in the hashed inputs.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 6e9c892d-31eb-4637-b7aa-6d2ec1ecca56

📥 Commits

Reviewing files that changed from the base of the PR and between c893793 and b2c431c.

📒 Files selected for processing (11)
  • src/main/ssh/remote-install-gc.ts
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-native-deps-cache-commands.ts
  • src/main/ssh/ssh-relay-native-deps-cache-deploy.test.ts
  • src/main/ssh/ssh-relay-native-deps-cache-gc.ts
  • src/main/ssh/ssh-relay-native-deps-cache-install.ts
  • src/main/ssh/ssh-relay-native-deps-cache-shell.test.ts
  • src/main/ssh/ssh-relay-native-deps-cache.test.ts
  • src/main/ssh/ssh-relay-native-deps-cache.ts
  • src/main/ssh/ssh-relay-native-deps-install-fixture.ts
  • src/main/ssh/ssh-relay-sftp-namespace-install.test.ts

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

Comment on lines +131 to +135
if (!recheck.readable || recheck.referencedKeys.has(key)) {
await execHostCommand(conn, host, moveRemoteTreeCommand(host, tombstone, entryDir)).catch(
() => {}
)
return false

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Inspect moveRemoteTreeCommand and removeRemoteTreeCommand semantics.
set -euo pipefail

fd -t f 'ssh-remote-commands.ts' -x ast-grep outline {} --items all
rg -nP -C10 'export function (moveRemoteTreeCommand|removeRemoteTreeCommand)' --type=ts

Repository: stablyai/orca

Length of output: 1882


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- repository guidance ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- remote command definitions ---'
cat -n src/main/ssh/ssh-remote-commands.ts | sed -n '35,90p'
printf '%s\n' '--- garbage-collection restore path ---'
cat -n src/main/ssh/ssh-relay-native-deps-cache-gc.ts | sed -n '85,155p'
printf '%s\n' '--- related command definitions and callers ---'
rg -n -C8 'listRelayNativeDepsCacheEntriesCommand|promoteRelayNativeDepsCacheCommand|moveRemoteTreeCommand|removeRemoteTreeCommand' src/main/ssh --type=ts
printf '%s\n' '--- applicable conventions and learnings ---'
for f in /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4/*/*.md; do
  case "$f" in
    */conventions/*|*/learnings/*|*/architecture/*) printf '\n### %s\n' "$f"; cat "$f" ;;
  esac
done

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- promotion command ---'
cat -n src/main/ssh/ssh-relay-native-deps-cache-commands.ts | sed -n '127,180p'
printf '%s\n' '--- cache path definitions ---'
cat -n src/main/ssh/ssh-relay-native-deps-cache.ts | sed -n '1,130p'
printf '%s\n' '--- relevant SSH learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src-main-ssh.md

Repository: stablyai/orca

Length of output: 10914


Guard tombstone restoration against an existing cache entry.

On supported POSIX hosts, moveRemoteTreeCommand emits mv. If promoteRelayNativeDepsCacheCommand recreates entryDir, the restore branch can move the tombstone inside it. listRelayNativeDepsCacheEntriesCommand searches only the base directory, so the nested tombstone and its node_modules tree can leak permanently. Restore only when entryDir is absent; otherwise remove the tombstone only after confirming the existing entry is complete.

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

ℹ️ Minor suggestions only — one concurrency rough edge worth a second look, nothing blocking.

Reviewed changes

  • Shared native-deps cache layout — relay node_modules now lives at ~/.orca-remote/native/<platform>-<depsHash>/node_modules, with each relay directory holding a symlink. The key hashes RELAY_NATIVE_DEPS (sorted) plus the epoch and the bytes of any shipped node-pty-* patch artifact.
  • Deploy-side attach/promote — ensure links a complete entry or seeds from a sibling relay install; promote publishes a probe-verified private tree behind a mkdir "$cache" election, with .deps-complete written last.
  • Symlink detach safety — every POSIX install is prefixed with if [ -L node_modules ]; then rm -f node_modules; fi; so a repair detaches rather than rm -rf-ing a shared tree; repairs opt out of the cache entirely.
  • GC — gcRelayNativeDepsCache mirrors remote-install-gc.ts's three-step tombstone move (rename → re-scan references → restore-or-remove) and fails closed on any unreadable reference.
  • Tests — 57 new tests across four files, including real shell scripts run against a real temp tree under both /bin/sh and /bin/dash.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

`mkdir -p "$base" 2>/dev/null || { ${notPromoted}; exit 0; }`,
`if [ -d "$cache" ] && [ ! -f "$cache/${RELAY_NATIVE_DEPS_CACHE_COMPLETE_NAME}" ]; then`,
` if [ -n "$(find "$cache" -maxdepth 0 -mmin +${CACHE_TAKEOVER_MINUTES} 2>/dev/null)" ]; then`,
' rm -rf "$cache" 2>/dev/null || true',

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.

The takeover reclaim (find -mmin +120 → rm -rf "$cache" → mkdir "$cache") reintroduces a narrow TOCTOU between two concurrent same-key promotes: if B's find runs against the stale entry, then A re-creates and populates the entry, B's delayed rm -rf deletes A's freshly-published tree before B re-wins mkdir. The outcome is benign because same-key trees are content-equivalent (A's symlink then resolves to B's tree), but it slightly weakens the 'mkdir elects one winner' argument the module header leans on. Worth either documenting this as an accepted race or making the reclaim atomic.

@nwparker
nwparker merged commit 7f4a17d into main Sep 2, 2026
33 checks passed
@nwparker
nwparker deleted the feat/relay-native-deps-cache branch September 2, 2026 05:51
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…ablyai#18033)

Relay node_modules lived inside `~/.orca-remote/relay-<version>+<hash>`, so
any byte change in `src/relay/` or the `src/shared/` it pulls in minted a new
directory and a fresh `npm install [email protected] @parcel/[email protected]`. On
Linux node-pty has no prebuild, so that is a node-gyp source compile on every
new bundle — eight of the fifteen deploy minutes, daily, on a dependency set
that is a pinned constant (stablyai#18009).

The tree now lives at `~/.orca-remote/native/<platform>-<depsHash>/node_modules`
and each relay directory symlinks to it. depsHash covers RELAY_NATIVE_DEPS, an
explicit epoch, and the bytes of every shipped `node-pty-*` patch artifact, so a
patch change mints a new entry rather than leaving hosts on a stale tree.

Three rules make one tree safe to share:

- A published entry is immutable. `.deps-complete` is written last, only after
  a probe on that host loaded both addons. Nothing installs, rebuilds or resets
  into a published entry: every `npm install` is prefixed with a symlink detach,
  so a repair on one directory can never `rm -rf node_modules/node-pty` out from
  under a live relay sharing the tree.
- Publication elects one winner with `mkdir`, so no client-side lock is needed
  and two deploys never write one tree. A loser keeps its own copy.
- Every failure degrades to today's per-directory install.

GC follows remote-install-gc.ts' discipline: a listing that does not end in its
own OK token, an unreadable link, or a reference whose shape this client never
writes aborts the whole pass. Deletion is tombstone-rename, re-read references
under the rename, then remove — a deploy that linked between the listing and the
rename gets its tree moved back. It only runs for a connection that could
compute a key, and never removes a pinned one.

Migration: a first deploy after this ships seeds its tree from a sibling relay
directory whose manifest pins the same versions, so an existing host does not
recompile once more. The seed is not trusted — it is a plain private install
until the normal probe loads it, and only then is it published.

Windows keeps the per-directory install: node-pty ships win32 prebuilts, so
there is no compile to avoid, and the console-list agent patch mutates the
installed tree in place, which rule 1 forbids for a shared one.

The POSIX scripts are exercised against a real tree under both /bin/sh and
dash, not just asserted on as strings.

Mirror-Of: 7f4a17d
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ablyai#18033)

Relay node_modules lived inside `~/.orca-remote/relay-<version>+<hash>`, so
any byte change in `src/relay/` or the `src/shared/` it pulls in minted a new
directory and a fresh `npm install [email protected] @parcel/[email protected]`. On
Linux node-pty has no prebuild, so that is a node-gyp source compile on every
new bundle — eight of the fifteen deploy minutes, daily, on a dependency set
that is a pinned constant (stablyai#18009).

The tree now lives at `~/.orca-remote/native/<platform>-<depsHash>/node_modules`
and each relay directory symlinks to it. depsHash covers RELAY_NATIVE_DEPS, an
explicit epoch, and the bytes of every shipped `node-pty-*` patch artifact, so a
patch change mints a new entry rather than leaving hosts on a stale tree.

Three rules make one tree safe to share:

- A published entry is immutable. `.deps-complete` is written last, only after
  a probe on that host loaded both addons. Nothing installs, rebuilds or resets
  into a published entry: every `npm install` is prefixed with a symlink detach,
  so a repair on one directory can never `rm -rf node_modules/node-pty` out from
  under a live relay sharing the tree.
- Publication elects one winner with `mkdir`, so no client-side lock is needed
  and two deploys never write one tree. A loser keeps its own copy.
- Every failure degrades to today's per-directory install.

GC follows remote-install-gc.ts' discipline: a listing that does not end in its
own OK token, an unreadable link, or a reference whose shape this client never
writes aborts the whole pass. Deletion is tombstone-rename, re-read references
under the rename, then remove — a deploy that linked between the listing and the
rename gets its tree moved back. It only runs for a connection that could
compute a key, and never removes a pinned one.

Migration: a first deploy after this ships seeds its tree from a sibling relay
directory whose manifest pins the same versions, so an existing host does not
recompile once more. The seed is not trusted — it is a plain private install
until the normal probe loads it, and only then is it published.

Windows keeps the per-directory install: node-pty ships win32 prebuilts, so
there is no compile to avoid, and the console-list agent patch mutates the
installed tree in place, which rule 1 forbids for a shared one.

The POSIX scripts are exercised against a real tree under both /bin/sh and
dash, not just asserted on as strings.
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