Skip to content

fix(ssh): collect relay versions only when provably exited; runtimes/ store GC - #24130

Merged
OrcaWin merged 4 commits into
mainfrom
OrcaWin/node-rt-p2-gc
Oct 1, 2026
Merged

OrcaWin merged 4 commits into
mainfrom
OrcaWin/node-rt-p2-gc

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​691 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​687
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​705 $\color{#cf222e}{\Huge{\mathbf{−}}}$​41 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​664

ELI5

Remote hosts were filling up with old relay folders (5 GB on one test host), because a stale socket file looked like a running relay. The cleanup now checks whether the relay process is actually alive. It also keeps the previous version and cleans up the shared Node runtimes safely.

What Changed

  • .relay-pid: the relay writes it into its version folder after it starts listening.
  • Three-way liveness (relay-version-dir-liveness.ts):
    • exited only when the recorded PID is dead and every relay-*.sock refuses a connection. A live PID means live. Anything uncertain means unverifiable, and the folder is kept.
    • Folders with no PID file keep today's rule, and Windows keeps its named-pipe check.
  • Previous relay version is kept, the way orcad keeps its previous version.
  • runtimes/ store:
    • It gets its own owner in remote-install-model.ts, so relay and orcad cleanup can never touch it.
    • A runtime is deleted only when no kept folder references it, it isn't the current or previous pin, and no process runs from it. The process check can only keep a runtime, never cause a deletion.
    • The reviewer fixed a bug where a runtime reached through a symlinked home escaped the process check.
  • Legacy folders: the new model lists legacy relay-* and orcad-* folders as diagnostics only this release (design D10, two-step).

Why

A socket file outlives its daemon, so test -S alone could never collect dead installs. A connect probe alone would race with a daemon that is about to go idle; checking the PID first closes that race.

Linked Issue

Part of the Node runtime plan (Phase 2; design D5 and D10). Related: #13852, #21215, #19194. Stacked on #24110.

Visual Proof

N/A. This changes cleanup on remote hosts, with no UI.

Testing

  • Real-shell tests cover:

    • relay liveness: a stale socket with a dead PID, a stale socket with a live PID, no PID file, and a timeout;
    • runtime-store GC: a runtime held by a running process, including through a symlinked home.
  • The previous-version pin and the ownership rules have unit tests. pnpm tc and the quality gates pass.

  • Limits:

    • Runtime-store cleanup isn't called in production yet, because nothing calls orcad's cleanup.
    • There's one .relay-pid per folder, although one folder can serve several relays.
    • There's no install lock for runtime promotion yet.
  • I manually tested these changes locally

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

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.

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors garbage collection for relay and runtime storage.

The PR is not yet safe to merge because relay GC can classify a version directory used by a live relay as exited.

Findings

  1. P1 Relocated live sockets go unseen ▶
  2. P2 References can arrive after recheck ▶

Summary

This PR adds relay PID-based liveness checks, pins the previous relay install, and introduces a separately owned Node runtime-store collector.

  • No new findings arose from changes since the previous review.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Relay version GC] --> B[Pin current and previous installs]
  B --> C[Check PID and relay sockets]
  C -->|Exited| D[Remove eligible version directory]
  C -->|Live or unverifiable| E[Keep directory]
  F[Runtime-store GC] --> G[Inventory references, pins, and processes]
  G --> H[Rename eligible runtime and recheck]
  H -->|New hold found| I[Restore runtime]
  H -->|No hold found| J[Delete runtime]
Loading

Reviews (3) · Last reviewed commit: "test(ssh): wait for the holder process t..."

'pid=$(cat "$pid_file" 2>/dev/null) || { echo UNVERIFIABLE; exit 0; }',
'case "$pid" in "" | *[!0-9]*) echo UNVERIFIABLE; exit 0;; esac',
'if orcad_alive "$pid"; then echo LIVE; exit 0; fi',
'for f in "$dir"/relay-*.sock "$dir"/relay.sock; do',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Relocated live sockets go unseen

On a host with a long home path, relay sockets move under /tmp/.orca-relay-…, but this probe checks only the version directory. If two relays share that directory and the last one to write .relay-pid exits while the other remains active, the probe sees a dead PID and no sockets. It reports EXITED, allowing GC to remove an install that a live relay still uses.

Comment on lines +179 to +184
if (!recheck || holdReason(sha, recheck, new Set(options.currentPins)) !== null) {
await restoreTree(conn, host, tombstone, entryDir, options.signal)
kept.push(name)
continue
}
if (await removeTree(conn, host, tombstone, options.signal)) {

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 References can arrive after recheck

The collector checks for new references after renaming a runtime, then deletes it without coordinating with installers. If an installer writes a slot’s .runtime-node marker for an older, unpinned runtime after that check, the deletion leaves the slot pointing to a missing bin/node, and its launcher exits with status 78. This is a non-blocking concern while runtime-store cleanup is not called in production, but it needs a handoff with installers before the collector is enabled.

@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 critical issues — well-tested change; one minor suggestion inline about the strength of the new exited verdict.

Reviewed changes

  • Relay version-dir liveness becomes three-way (relay-version-dir-liveness.ts, new): the relay publishes .relay-pid after binding (relay-pid-publication.ts, relay-daemon.ts), and GC deletes only on an exited verdict — recorded PID dead and every in-dir relay-*.sock refusing. No-PID dirs keep the test -S rule; Windows keeps the pipe probe.
  • Previous relay build is pinned (remote-install-previous-version.ts, new): the shared GC resolves the newest other completed install by .install-complete mtime via resolveExtraPinnedDirNames, and deletes nothing when the host cannot answer.
  • runtimes/ gets its own owner (remote-install-model.ts): neither version-dir model can list or delete the shared Node store.
  • Shared runtime-store GC (remote-node-runtime-store-gc.ts + remote-node-runtime-store-inventory.ts, new): delete a node-<sha> only when verified, unreferenced, unpinned and unheld, using rename-to-tombstone then full re-inventory with restore; abandoned tombstones are purged. Wired only from orcad GC when nodeRuntimePins is supplied.
  • Tests across liveness (real /bin/sh + real sockets), previous-version ordering (real shell), and runtime-store GC (real processes, symlinked home) are meaningful and would fail on the behavior they pin.

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

' *) echo UNVERIFIABLE; exit 0;;',
' esac',
'done',
'echo EXITED'

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 exited verdict here rests on "recorded PID dead" plus a failed connect, but unlike parseRelayEndpointIncumbentProbe it never enumerates socket holders, and the single last-writer .relay-pid cannot represent a version dir serving several instances (the PR body notes this). A live sibling whose own relay-*.sock was unlinked or relocated outside $dir is invisible to this loop, so the header's "provably dead" wording (lines 5-8) claims more than the evidence carries. This is largely the pre-existing blind spot of test -S/in-dir globs, but since the worst outcome here is deleting a tree under a running relay, it is worth either enumerating holders before saying exited (reuse RELAY_LSOF_PROBE_JS) or explicitly scoping the header to the in-dir socket set.

Technical details
# `exited` is asserted from less evidence than the boundary doc requires

## Affected sites
- `src/main/ssh/relay-version-dir-liveness.ts:43` — sibling-instance case handled only through the `accepted` branch
- `src/main/ssh/relay-version-dir-liveness.ts:51` — `echo EXITED` when no in-dir socket accepts
- `src/main/ssh/relay-version-dir-liveness.ts:5-8` — header claims provable exit
- `src/main/ssh/relay-pid-publication.ts:21-24` — one `.relay-pid`, last writer, never removed on shutdown
- `src/main/ssh/ssh-relay-endpoint-incumbent.ts:181` — the established `exited` requires `holdersEnumerable && (refused || absent)`

## Relevant behavior
- `remote-install-gc.ts:307-308` treats `!== 'exited'` as live, so `exited` is the only verdict that authorizes deletion.
- `ssh-relay-endpoint-incumbent.ts:10-20` documents that an unlinked-socket relay is "invisible to this probe by construction".
- Startup/takeover windows: `relay-daemon.ts:108-109` binds before publishing the PID, and `relay-socket-ownership.ts:198-212` unlinks a stale inode before rebinding, so a brief `absent`/`refused` interval can coincide with a live process.

## Required outcome (pick one)
- Enumerate socket holders (as the incumbent probe does) before returning `exited`, or
- Treat "dead recorded PID + no accepting in-dir socket" as `unverifiable`, or
- Keep the current behavior but narrow the header claim to the in-dir socket set and record the unlinked/relocated-sibling blind spot as an accepted limitation.

## Open question
- Is a version dir that still hosts a live-but-unlinked relay intentionally collectible, or should it be kept?

m4air added 4 commits October 1, 2026 00:40
…s the previous build

The relay records .relay-pid in its version dir once it owns its socket. GC calls a
relay version dir exited only when that PID is provably dead and every relay-*.sock
refuses a connection; a dir without a PID file keeps the test -S rule. The most
recently completed other relay build is pinned like orcad's rollback target.
Design D5 GC liveness.
…n owner

runtimes/ gets its own owner in the install model, so no version-dir GC (new or old
clients, whose listings are prefix-scoped) can list or delete it. A store pass
removes node-<sha> only when no retained dir references it, it is neither a current
pin nor the newest other verified runtime, and a ps or /proc check ran and found no
process using it. Legacy relay-*/orcad-* dirs are read for references and reported
as diagnostics only (design D10 two-step). Wired behind orcad GC's nodeRuntimePins.
…a symlinked home

/proc exe resolves symlinks and argv keeps whatever spelling launched the runtime, so
filtering on the exact $root path missed in-use runtimes on hosts like /home -> /var/home.
Filter on the store segment instead; the parser already attributes holds root-agnostically.
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-gc branch from 3dc1d67 to 06355b9 Compare October 1, 2026 07:53
@OrcaWin
OrcaWin changed the base branch from OrcaWin/node-rt-cutover to main October 1, 2026 07:54
@OrcaWin OrcaWin closed this Oct 1, 2026
@OrcaWin OrcaWin reopened this Oct 1, 2026
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered
📝 Walkthrough

Walkthrough

The changes add relay PID publication, endpoint liveness checks, and completed-install ordering to remote version cleanup. They add remote Node runtime-store inventory and garbage collection, including retention checks and staged removal. The install inventory now classifies the shared runtimes directory separately. Orcad cleanup can run the shared runtime-store collector when runtime pins are supplied.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 06355

Runtime-store cleanup could delete a Node runtime that a running process is still using on hosts that restrict /proc. The process check should be marked as run only after it has actually read process links. Cleanup is not yet called in production, which limits the immediate exposure.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 06355

Cleanup gains useful retention safeguards, but interrupted recovery can leave a needed shared runtime unavailable at its original path. The risk is constrained by explicit runtime pins and conservative reference checks; no privilege escalation was established.

Retained concerns

  • Medium · reliability · observed: When opt-in runtime collection runs, post-rename recovery can report a runtime as kept without restoring its original path. Restoration reuses the operation's AbortSignal, suppresses confirmed failures, and ignores the restore command's BUSY result. If a reference appears after rename or inventory becomes unverifiable, interruption or restoration failure can leave dependent installs unable to launch. Later collection preserves referenced tombstones but does not repair the missing runtime path, weakening rollback and failure containment.
Security review details

Security Blast Radius

  • inferred — The intended destructive scope is the shared runtime store beneath one supplied remote home, using the supplied SSH connection's filesystem authority. A stranded runtime can affect multiple install directories referencing that hash. Account permissions and symlink targets determine effective filesystem exposure; cross-account or service-wide privilege expansion was not established.

Trust Boundaries and Controls

  • observed — Process observations add retention holds, and a completely unavailable process check blocks collection. However, successful ps execution or a readable /proc/self/exe marks the check as available while unreadable individual process executables are skipped. This records probe availability, not proven complete process visibility.

Resilience and Maintainability Implications

  • inferred — The post-rename recheck reduces concurrent-reference risk but does not make recovery atomic. Runtime acquisition can accept an existing verified executable, while restoration may be cancelled or fail without confirming launchability. The demonstrated restoration safeguard therefore remains conditional on successful compensation; caller-level serialization was not established.

Hardening Proposals

  • proposed — Give compensation a bounded recovery path independent of the cancelled operation, verify restoration outcomes before reporting an entry as kept, and provide explicit recovery for referenced tombstones. Coordinate runtime acquisition and collection so reference publication and deletion cannot race across clients.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.02% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 41 functions across 22 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 describes the primary changes: safer relay-version collection and runtime-store garbage collection.
Description check ✅ Passed The description covers the core template sections, explains the behavior and rationale, identifies linked issues, documents testing, and states that visual proof is not applicable. Some administrative…
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: 45fa0d83-a89b-44ec-bcf3-8b691e78ff8b

📥 Commits

Reviewing files that changed from the base of the PR and between 94f6c53 and 06355b9.

📒 Files selected for processing (22)
  • src/main/ssh/orcad-remote-gc.test.ts
  • src/main/ssh/orcad-remote-gc.ts
  • src/main/ssh/relay-version-dir-liveness.test.ts
  • src/main/ssh/relay-version-dir-liveness.ts
  • src/main/ssh/remote-install-gc-termination.test.ts
  • src/main/ssh/remote-install-gc.ts
  • src/main/ssh/remote-install-model.test.ts
  • src/main/ssh/remote-install-model.ts
  • src/main/ssh/remote-install-previous-version.test.ts
  • src/main/ssh/remote-install-previous-version.ts
  • src/main/ssh/remote-node-runtime-store-gc.test.ts
  • src/main/ssh/remote-node-runtime-store-gc.ts
  • src/main/ssh/remote-node-runtime-store-inventory.ts
  • src/main/ssh/ssh-relay-cross-version-isolation.test.ts
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-endpoint-incumbent.ts
  • src/main/ssh/ssh-relay-versioned-install.test.ts
  • src/main/ssh/ssh-remote-commands.ts
  • src/relay/relay-daemon.ts
  • src/relay/relay-pid-publication.test.ts
  • src/relay/relay-pid-publication.ts
  • src/shared/relay-artifacts.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +82 to +85
'if ps_out=$(ps -e -o args= 2>/dev/null); then',
" printf 'PROCESS_CHECK ps\\n'",
` printf '%s\\n' "$ps_out" | grep -F -- /${ORCAD_RUNTIMES_DIRNAME}/ | sed 's/^/HOLD /'`,
'fi',

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- changed file ---'
cat -n src/main/ssh/remote-node-runtime-store-inventory.ts
printf '%s\n' '--- merge-base diff ---'
git diff --no-ext-diff --unified=80 6593d7d194c758238119e548f1005d898374e2a1 06355b91f604a3803aa30783e0bc88ee1c0222c5 -- src/main/ssh/remote-node-runtime-store-inventory.ts
printf '%s\n' '--- direct references ---'
rg -n --glob '*.{ts,d.ts}' 'processCheckRan|PROCESS_CHECK proc|readlink /proc|PROCESS_CHECK ps|parseRuntimeStoreInventory|runtimeStoreInventoryCommand' src

Repository: stablyai/orca

Length of output: 16275


🏁 Script executed:

set -eu
cat -n src/main/ssh/remote-node-runtime-store-gc.ts | sed -n '35,145p'
printf '%s\n' '--- related tests ---'
cat -n src/main/ssh/remote-node-runtime-store-gc.test.ts | sed -n '35,135p'

Repository: stablyai/orca

Length of output: 8641


Only mark the /proc check after reading a numeric PID link.

readlink /proc/self/exe does not prove that the scan can read runtime processes. The loop ignores failed PID-link reads, but PROCESS_CHECK proc still sets processCheckRan. The collector can then remove a running, unpinned runtime when held is empty.

Suggested fix
 if [ -n "$(readlink /proc/self/exe 2>/dev/null)" ]; then
-  printf 'PROCESS_CHECK proc\n'
+  proc_pid_read=0
   for p in /proc/[0-9]*/exe; do
     t=$(readlink "$p" 2>/dev/null) || continue
+    proc_pid_read=1
     case "$t" in */${ORCAD_RUNTIMES_DIRNAME}/*) printf 'HOLD %s\n' "$t";; esac
   done
+  [ "$proc_pid_read" -eq 1 ] && printf 'PROCESS_CHECK proc\n'
 fi

@OrcaWin
OrcaWin merged commit 9ddcc9b into main Oct 1, 2026
45 of 47 checks passed
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