Skip to content

feat(ssh): runtime-store GC in production and exec-stdin upload fallback - #24136

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

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

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​585 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​579
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​537 $\color{#cf222e}{\Huge{\mathbf{−}}}$​59 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​478

ELI5

Two things. First, cleanup of the shared Node runtimes now actually runs after a pinned relay starts, under a lock so it can't race an install. Second, when a host's SFTP is missing or sandboxed (Synology, chrooted jump hosts), Orca now streams uploads over the SSH command channel instead of failing.

What Changed

  • Runtime GC in production:
    • The pinned relay deploy runs gcRemoteNodeRuntimeStore after launch, after the version-folder GC. The legacy path never calls it.
    • The new runtimes/.store-lock mkdir lock (20-minute stale rule) covers promotion, which re-probes under the lock, and GC, which tries the lock once and skips the pass if it's busy.
    • This closes the ensure-then-reference race from fix(ssh): collect relay versions only when provably exited; runtimes/ store GC #24130.
  • Exec-stdin fallback:
    • When SFTP is refused or sandboxed, the runtime archive and relay bundle stream over an exec channel's stdin, then are hash-checked. It covers both the system-ssh and ssh2 transports.
    • Only precise SFTP errors trigger it; a lost transport never does.

Why

Design D5: without a production caller, runtime GC did nothing. The upload fallback addresses #12868 and #15479.

Linked Issue

Part of the Node runtime plan (Phase 2). Stacked on #24130 (includes #24129).

Visual Proof

N/A. This changes remote host setup, with no UI.

Testing

  • Command construction and fallback selection are tested for both transports.

  • A real local-shell test streams a payload over 10 MB and checks its hash.

  • Not tested against a real Synology or chrooted host: the ssh2 error strings are matched from ssh2 1.17.0's source.

  • Follow-ups:

    • Clients from before this change promote without the lock; GC's rename, re-check and restore steps still guard against them.
    • Orcad's install path has the same ensure-then-reference window.
  • 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: 1/5

[High risk] Adds runtime store garbage collection and file transfer fallback.

The PR does not appear safe to merge: Windows application-control refusals can bypass a usable host-Node relay, and three previously reported blocking issues remain.

Findings

  1. P1 Release can remove another owner's lock ▶
  2. P1 Sweep can delete active uploads ▶
  3. P1 PTY failure blocks entire relay ▶
  4. P2 Interrupted uploads leave partial files ▶

Summary

The PR activates post-launch runtime-store collection and adds exec-stdin uploads when POSIX SFTP is unavailable. Changes since the previous review also enable a pinned-Node Windows relay, including Windows runtime installation and ConPTY support, and correct a production rollout headroom-gate condition.

  • The Windows application-control fallback needs correction before merge.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Windows pinned Node] --> B{Application control permits node.exe?}
  B -->|Yes| C[Verify and launch pinned relay]
  B -->|No, classified noexec| D[Unavailable]
  D -. Skips .-> E[Legacy host-Node relay]
Loading

Reviews (4) · Last reviewed commit: "test(ssh): rung C relays never take the ..."

Comment on lines +37 to +40
}
})
}

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 Release can remove another owner's lock

If a runtime-store GC pass stays active beyond the 20-minute stale threshold, another client can replace its .store-lock. When the original pass finishes, this unconditional release removes the new owner's lock. A third client can then run GC or promotion at the same time, defeating the lock that protects runtime publication and deletion. The release needs to verify that it still owns the current lock.

Knowledge Base Used: Remote connectivity and execution

Comment on lines +135 to +137
` recent=$(find "$s" -mmin -${staleMinutes} -print 2>/dev/null) || continue`,
' [ -z "$recent" ] || continue',
` rm -rf -- "$s" && printf '${SWEPT_STAGE} %s\n' "\${s##*/}"`,

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 Sweep can delete active uploads

If an SFTP archive upload pauses for more than 20 minutes while another client runs GC, this sweep deletes its stage because no file has been modified recently. The uploader has not yet taken the store lock, and the SFTP transfer has no matching idle timeout. When the upload resumes, its stage is gone and runtime promotion fails. An old file timestamp alone does not show that the upload has ended.

Knowledge Base Used: Remote connectivity and execution

Comment on lines +146 to +147
case 'failed':
throw new Error(`The pinned Node self-test at ${remoteRelayDir} failed: ${verdict.detail}`)

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 PTY failure blocks entire relay

If a host cannot open a PTY—for example, a container without usable /dev/pts—the self-test reports a spawn failure and this branch aborts the pinned relay install. File and Git services never start, although the legacy relay can launch with terminal support degraded. A PTY spawn failure should not prevent those other relay services from starting.

Knowledge Base Used: Remote connectivity and execution

if (!Number.isSafeInteger(byteLength) || byteLength < 0) {
throw new Error(`Invalid upload size: ${byteLength}`)
}
const part = `${remotePath}.orca-part-${options.token}`

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 Interrupted uploads leave partial files

If an exec upload is aborted or times out before the shell reaches its failure branch, that branch cannot remove the .orca-part-* file. No later cleanup targets these filenames, so repeated interrupted uploads can leave large partial archives in the remote install area. This is a non-blocking cleanup gap.

@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 — one design tradeoff worth a decision, plus minor notes below.

Reviewed changes — initial review of the full PR: the runtime-store GC wired into the production pinned-relay deploy under a new .store-lock, and a new exec-stdin upload fallback for hosts whose SFTP is refused or sandboxed.

  • Runtime-store GC in production — after a pinned launch, gcRemoteNodeRuntimeStore runs with the launched pin as currentPins, sequenced after the version/ripgrep passes that drop superseded refs.
  • .store-lock — remote-node-runtime-store-lock.ts reuses the install lock's mkdir primitives and 20-minute stale rule; GC tries once and skips a busy pass, promotion waits.
  • Stage sweeping — GC removes .stage-* dirs nothing has written to inside the stale window; the stage prefix is now a shared constant.
  • Exec-stdin upload fallback — a new writer streams bytes into an exec channel, size-checks and atomically renames; selected only for exact ssh2 SFTP-refusal/sandbox errors on POSIX non-system-ssh transports, latched per connect generation.
  • Pinned-Node relay runtime — per-host remoteRuntime: 'pinned-node' opt-in, glibc probing with a 2.28 floor, prebuilt addons staged from the orcad slot, a runtime-folded relay version, pre-launch self-test verdicts, and an optional informational runtime on the handshake.

ℹ️ Nitpicks

  • ssh-exec-stdin-file-transfer.ts — a .orca-part-<token> partial written before an abrupt client abort/crash is never cleaned up; the new GC sweeps only .stage-*. Harmless (the suffix keeps it out of the "final file" class) but it can accumulate in a relay version dir.
  • execCommand's new stdin handling (ssh-relay-exec-command.ts:204-208) has no test for the local-read-error or non-zero-close-while-piping paths; ssh-exec-stdin-file-transfer.test.ts only models the remote-side truncation (head -c 1000).
  • PR body claim precision: the fallback "covers both the system-ssh and ssh2 transports", but canFallBackToExecStdin deliberately excludes the system-SSH transport (it already writes via exec). Worth wording as "the ssh2 transport gains the fallback; system-SSH already streams".

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

Comment on lines +90 to +103
export async function withRuntimeStoreLock<T>(
conn: SshConnection,
host: RemoteHostPlatform,
storeDir: string,
task: () => Promise<T>,
signal?: AbortSignal
): Promise<T> {
await acquireInstallLock(conn, storeDir, host, {
signal,
lockName: RUNTIME_STORE_LOCK_NAME,
relayGcClaim: false
})
return runHoldingLock(conn, host, storeDir, task)
}

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 store lock inherits the install lock's 20-minute stale takeover, but its holder is not bounded below that threshold the way an install-lock holder is. That steal rule exists because RELAY_DEPLOY_TIMEOUT_MS (15 min) keeps a live install-lock holder shorter than the 20-minute stale rule; a GC holder has no such bound — collectHoldingStoreLock runs an unbounded plan.purgeTombstones loop plus up to 8 move/re-inventory/remove cycles, each a 30 s exec. If a pass crosses 20 minutes, another client can legitimately steal the lock, and because releaseRuntimeStoreLock carries no ownership token it then deletes the thief's lock, letting a third holder run concurrently.

Technical details
# Store lock has no bound below its own steal threshold and no ownership check on release

## Affected sites
- `src/main/ssh/remote-node-runtime-store-lock.ts:90-103` — `withRuntimeStoreLock` acquires via `acquireInstallLock`, which steals any lock older than `INSTALL_LOCK_STALE_SECONDS` (1200 s).
- `src/main/ssh/remote-node-runtime-store-lock.ts:29-38` — `releaseRuntimeStoreLock` unconditionally `rm -rf`s the lock dir with no proof this process still owns it.
- `src/main/ssh/remote-node-runtime-store-gc.ts:221-256` — the GC task's duration is the sum of an unbounded `purgeTombstones` loop and up to `MAX_REMOVALS_PER_PASS` (8) move/re-inventory/remove cycles; no aggregate cap.
- `src/main/ssh/ssh-relay-install-lock-commands.ts:86-128` — the reused POSIX steal (`posixStealInstallLockCommand`) is what enables the ABA.

## Required outcome
- A GC pass cannot outlive the lock's stale threshold while it is still considered the owner, or a stolen lock cannot be released by the former holder.

## Suggested approach (optional)
- Bound `collectHoldingStoreLock` (e.g. cap `purgeTombstones` like `MAX_REMOVALS_PER_PASS`, or add an aggregate deadline below 1200 s) and/or have the lock carry a per-holder token (random value written into the lock dir) that `releaseRuntimeStoreLock` verifies before removing.

## Open questions for the human
- Is a >20-minute GC pass actually reachable on the supported hosts (large tombstone backlog + slow/large removals), or is the current narrow window acceptable given the rename/re-check/restore guard?

@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-gc branch from 3dc1d67 to 06355b9 Compare October 1, 2026 07:53
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-transfer-gc branch from 3c6d318 to 22a2da0 Compare October 1, 2026 08:51
@OrcaWin
OrcaWin requested a review from Jinwoo-H as a code owner October 1, 2026 08:51
@OrcaWin
OrcaWin changed the base branch from OrcaWin/node-rt-p2-gc to main October 1, 2026 08:52
@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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 74a3eb97-d138-43f4-9927-cb20512ba033

📥 Commits

Reviewing files that changed from the base of the PR and between 38481bb and 2241d8e.

📒 Files selected for processing (4)
  • src/main/ssh/orcad-remote-node-runtime.ts
  • src/main/ssh/ssh-relay-deploy-pinned-node.test.ts
  • src/main/ssh/ssh-relay-pinned-node-install.test.ts
  • src/main/ssh/ssh-relay-pinned-node-install.ts

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


📝 Walkthrough

Walkthrough

The change adds a shared lock for remote Node runtime promotion and garbage collection. Runtime collection now sweeps stale upload stages, and pinned deployments retain the active runtime hash. Pinned relay installation checks for the runtime under the lock. New exec-stdin transfer helpers support file, string, and directory uploads. Relay transfers use exec-stdin fallback for selected SFTP failures on eligible hosts.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 2241d

This change adds locking around remote runtime promotion and cleanup, and an upload fallback for hosts that refuse SFTP. No concrete merge-blocking issue remains from this review.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 2241d

The upload fallback uses the existing SSH connection and preserves staged writes and runtime verification. The main remaining risk is cleanup racing deployment of an older cached runtime. Recovery after interrupted remote work also needs stronger assurance.

Retained concerns

  • Low · reliability · inferred: New production GC can strand an older cached Orcad candidate between runtime ensure and reference upload. This requires competing client pins, a runtime outside the collector's current and newest-previous retention set, and no existing reference or running process. A reference published after GC's final recheck cannot prevent deletion. Pinned relay installation has a final locked check, but Orcad installation does not. Preflight failure preserves the incumbent, limiting this to candidate availability and recovery rather than demonstrated data loss or privilege expansion.
Security review details

Security Blast Radius

  • inferred — The directly evidenced mutation scope is the deployment trees and shared runtime store reached through the supplied SSH connection. Shared-store cleanup can affect multiple relay and Orcad versions under the same remote installation root; broader tenant, account, or environment exposure is not established.

Security Findings and Attack Paths

  • inferred — The supported adverse interleaving concerns deployment availability: another client's collector can remove an unreferenced older cached runtime before Orcad uploads its marker. The candidate then fails preflight without stopping the incumbent. This does not establish an attacker-controlled privilege-escalation path.

Trust Boundaries and Controls

  • observed — Sandbox-triggered fallback intentionally replaces the SFTP namespace with the shell namespace for the existing destination path. It uses the same connection's exec capability rather than a new credential. Shell paths are escaped, payload contents travel through stdin, and local file uploads reject symlinks and check opened-file identity and size. The namespace transition alone does not demonstrate unauthorized access beyond existing shell authority.

Resilience and Maintainability Implications

  • observed — Unconfirmed remote termination preserves the runtime stage and store lock instead of assuming mutation has ended. Stage sweeping preserves recently modified contents and stages whose inspection fails. Lock recovery nevertheless permits age-based takeover after twenty minutes, while lock release removes the shared lock path without an owner-generation check.

Hardening Proposals

  • proposed — Apply the pinned relay's post-reference runtime check and repair pattern to Orcad installation, or coordinate runtime reservation and durable reference publication as one ownership transition.
  • proposed — Consider owner-generation fencing for stale-lock takeover and release, or establish that old remote mutations have terminated before recovery admits a new owner. This would strengthen recovery guarantees beyond local timeout bounds.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 47 functions across 21 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 both primary changes: production runtime-store garbage collection and the exec-stdin upload fallback.
Description check ✅ Passed The description provides a clear ELI5 summary, change details, rationale, testing information, visual-proof status, and relevant limitations. The linked issue is referenced as #24130 but no actual iss…
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
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-transfer-gc branch from 22a2da0 to 38481bb Compare October 1, 2026 09:11
@greptile-apps

This comment has been minimized.

@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 in this delta — the two D5 features were rebased onto the runtime-ladder base and two test commits landed. The only behavior adaptation is that rung C (host Node) and Windows hosts no longer take the runtime-store lock.

Reviewed changes — incremental delta since the prior pullfrog review (22a2da06 → 38481bb2): the PR was rebased onto the pinned-runtime ladder and now carries only the runtime-store GC and exec-stdin upload features.

  • Rebased onto the runtime ladder — the post-launch gcRemoteNodeRuntimeStore call in deployAndLaunchRelayOnRuntime is now keyed on prebuilt?.kind === 'pinned-node', so rung C and the legacy host-Node path skip it; currentPins stays the launched pin.
  • Store lock only for the pinned rung — verifyPinnedRelayInstall takes the store lock and confirms/reinstalls the pin only for plan.kind === 'pinned-node' on a POSIX host; host-Node and Windows plans skip the store-lock round trips.
  • Test coverage — assertions that rung C never calls withRuntimeStoreLock, that the OpenCode runtime setup answers the .store-lock (exec count 7 → 11), and that the pinned deploy GCs after gcOldRelayVersions.

The other functional files in the diff (remote-node-runtime-store-lock.ts, remote-node-runtime-store-gc.ts, ssh-exec-stdin-file-transfer.ts, ssh-relay-install-transfers.ts) are unchanged from the previously reviewed state. The six affected ssh test files pass locally (58 tests).

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

m4air added 4 commits October 1, 2026 02:35
…store lock (D5)

The pinned-Node relay deploy now collects runtimes/ after a successful
launch, keeping the pin it runs. Promotion in ensureRemoteOrcadNodeRuntime
and GC deletion both hold runtimes/.store-lock (install-lock primitives,
20-minute stale rule); GC only tries the lock and skips when busy. A cold
pinned install re-checks its runtime under the lock once the relay ref is
visible, closing the ensure-then-ref window. GC also sweeps runtimes/.stage-*
dirs nothing has written to within the stale rule.
… is refused (D5)

On the bundled ssh2 transport to a POSIX host, a definite SFTP refusal
(subsystem refused, sftp-server exited during the handshake, or a chrooted
view answering NO_SUCH_FILE for a shell-created path) now falls back to
writing through an exec channel's stdin, reusing makePosixWriteFileCommand
with a byte-count check and atomic rename. Transport loss, timeouts and
aborts never select the fallback. execCommand gains a stdin option.
…p test

Promotion now runs under runtimes/.store-lock, so the mocked host must grant
the lock and the stage-exhaustion case makes four more round trips.
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-transfer-gc branch from 38481bb to 2241d8e Compare October 1, 2026 09:35

@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 in this delta. The branch was rebased onto the base that absorbed the Windows pinned-Node relay (#24135, 67014c8); the only production change is the promote/GC branch split that follows from that base, and no new review comments are warranted.

Reviewed changes — incremental delta since the prior pullfrog review (38481bb2 → 2241d8e2): the rebase adaptation for the Windows pinned-Node base plus the two test commits already covered.

  • Windows promote takes no store lock — ensureRemoteOrcadNodeRuntime now splits the Windows promote (windowsNodeRuntimePromoteCommand, hostRemovedStage = windows) from the POSIX path that re-probes and promotes inside withRuntimeStoreLock. Consistent by design: gcRemoteNodeRuntimeStore returns skipped on Windows and confirmPinnedRuntimeHeld is POSIX-only.
  • Store lock still scoped to the pinned POSIX rung — verifyPinnedRelayInstall confirms/reinstalls the held runtime only for plan.kind === 'pinned-node' on a POSIX host; rung C and Windows skip the lock round trips (asserted by the new test).
  • Tests — the OpenCode runtime setup test answers the .store-lock round trips (exec count 7 → 11); the two test commits are content-identical to those reviewed at 38481bb2.

The exec-stdin, store-lock, and store-GC modules (remote-node-runtime-store-lock.ts, remote-node-runtime-store-gc.ts, ssh-exec-stdin-file-transfer.ts, ssh-relay-install-transfers.ts) are unchanged from the previously reviewed state.

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

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