Skip to content

fix(ssh): recover orphaned relay install locks (#9828) - #10207

Merged
OrcaWin merged 9 commits into
stablyai:mainfrom
rodboev:pr/recover-orphaned-relay-lock
Jul 31, 2026
Merged

OrcaWin merged 9 commits into
stablyai:mainfrom
rodboev:pr/recover-orphaned-relay-lock

Conversation

@rodboev

@rodboev rodboev commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Stage relay uploads in attempt-owned .upload-* directories and promote them into the shared version directory only after the install lock is acquired.
  • A canceled pre-install upload now retries immediately instead of waiting behind a fresh shared .install-lock, while unconfirmed post-promotion installs still keep the existing fence.

Closes #9828.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused validation run in this session:

  • pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-deploy.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts, passed, covers the staged-upload retry, promotion ordering, cancellation cleanup, and native-deps fence regressions behind [Bug]: SSH relay retry silently waits on orphaned install lock after cancelled deployment #9828.
  • pnpm exec oxlint src/main/ssh/ssh-relay-deploy.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts; pnpm exec oxfmt --check src/main/ssh/ssh-relay-deploy.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts; pnpm run check:max-lines-ratchet, passed, covers the focused spec split and Orca's lint policy for the touched files.

AI Review Report

AI review traced the staged-upload, install-lock, promotion, and relay-launch paths across Linux and macOS POSIX shells, Windows PowerShell command generation, remote path quoting, and cross-version socket isolation. It flagged stale-stage command coverage, unconfirmed lock-create teardown collapse, a stale queue-driven cross-version fixture, stale validation counts, and test-file size pressure. The final branch fixes those findings, keeps the staged-upload regressions in focused specs, and leaves UI and Electron code untouched.

Security Audit

Remote path construction stays on the existing host-native builders, attempt-local stages never become the shared version directory before lock acquisition, and unconfirmed teardown still preserves the shared lock instead of overlapping a possibly live remote process. No auth, IPC, dependency, or secrets surfaces changed.

Notes

No visual change. No UI or Electron code changed. This closes the canceled pre-install upload path from #9828 by keeping the shared .install-lock out of the upload phase; INSTALL_LOCK_STALE_MS and the live post-promotion fence stay unchanged.

ELI5

Canceled SSH relay installs could leave locks that blocked the next install. Uploads stage in attempt-owned folders and only promote under the install lock so orphaned locks recover cleanly.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Relay deployment now uses reserved remote upload stages with ownership checks, promotion, cleanup, and stale-stage recovery. SFTP uploads support cancellation and report channel and transfer teardown status. Namespace validation uses an explicit home-relative root. Remote commands bound relay garbage-collection listings and support POSIX and Windows promotion. Tests cover deployment ordering, cancellation, recovery, lock handling, native dependency installation, cross-version isolation, and Docker SSH target configuration.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.67% which is insufficient. The required threshold is 80.00%. 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 relay install-lock recovery change addressed by the pull request.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections.
Linked Issues check ✅ Passed The changes address [#9828] by staging uploads before lock acquisition while preserving the fence for unconfirmed post-promotion termination.
Out of Scope Changes check ✅ Passed The implementation, tests, reliability tooling, and cross-platform helpers support staged-upload recovery and introduce no unrelated product changes.

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: Pro Plus

Run ID: 57e845d3-936e-4f79-901c-16c102e83b7a

📥 Commits

Reviewing files that changed from the base of the PR and between 8f40ddf and 08b997debcab88f6aaa93d5e5b96c343c38ea14e.

📒 Files selected for processing (8)
  • src/main/ssh/ssh-relay-cross-version-isolation.test.ts
  • src/main/ssh/ssh-relay-deploy.test.ts
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-install-lock.test.ts
  • src/main/ssh/ssh-relay-install-lock.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts
  • src/main/ssh/ssh-remote-commands.test.ts
  • src/main/ssh/ssh-remote-commands.ts

Comment thread src/main/ssh/ssh-relay-deploy.test.ts Resolved
@rodboev

rodboev commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

I updated the PR body to make the issue scope explicit. This change fixes the reproduced canceled-upload path by staging uploads before the shared relay directory exists, so a retry no longer waits behind a fresh orphaned .install-lock. The post-promotion live-installer fence and INSTALL_LOCK_STALE_MS behavior stay unchanged on purpose, so this PR doesn't add wait-age UI or console messaging.

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

🧹 Nitpick comments (1)
src/main/ssh/ssh-relay-deploy-staged-upload.test.ts (1)

164-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Optional: extract the shared execCommand command-router into a helper.

The same uname / echo $HOME / test -S / ORCA-NATIVE routing appears in four tests (Lines 164-178, 207-224, 285-299, 321-335). Extracting a small factory (accepting per-test overrides such as the stale-stage listing and the socketProbe sequence) removes ~4× duplication and prevents silent drift if the deploy command protocol changes.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f70ea18c-3604-42e2-9189-faf3308329ab

📥 Commits

Reviewing files that changed from the base of the PR and between 08b997debcab88f6aaa93d5e5b96c343c38ea14e and 53acc89c2b7cd45aa75a19773e11e296f0e751dc.

📒 Files selected for processing (4)
  • src/main/ssh/ssh-relay-deploy-staged-upload.test.ts
  • src/main/ssh/ssh-relay-deploy.test.ts
  • src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts
💤 Files with no reviewable changes (2)
  • src/main/ssh/ssh-relay-deploy.test.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts

@rodboev

rodboev commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

I looked at the optional router-helper nit and kept the per-test command routing inline for now. Each case tweaks a different part of the deploy protocol, such as stale-stage discovery, socket progression, or the termination boundary, and keeping those branches local makes the exercised remote sequence obvious next to the assertion. If this staged-upload surface grows again, I can factor the shared helper in a follow-up.

@AmethystLiang
AmethystLiang requested a review from OrcaWin July 24, 2026 16:50
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@OrcaWin
OrcaWin force-pushed the pr/recover-orphaned-relay-lock branch 2 times, most recently from 9d3012e to ad53ba5 Compare July 31, 2026 23:02

@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: 2

🧹 Nitpick comments (1)
config/scripts/run-ssh-staged-upload-reliability.mjs (1)

25-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fail when an explicitly configured PowerShell path is unusable, and probe once.

Two points:

  1. If --powershell or ORCA_POWERSHELL_EXECUTABLE names an executable whose probe fails, the code falls back to pwsh without any message. The gate evidence in config/reliability-gates.jsonc claims a specific PowerShell 7.6.4 executable, so a silent substitution can attribute a run to the wrong interpreter.
  2. Lines 32-38 and 44-48 run the same probe command twice. Reuse the first result. This also removes the null-stdout dereference on Line 48 if the second spawn fails.
♻️ Proposed refactor
-const powerShellExecutable = [
-  configuredPowerShell,
-  ...(process.platform === 'win32' ? ['pwsh.exe', 'powershell.exe'] : ['pwsh'])
-].find((candidate) => {
-  if (!candidate) {
-    return false
-  }
-  return (
-    spawnSync(
-      candidate,
-      ['-NoProfile', '-NonInteractive', '-Command', '$PSVersionTable.PSVersion.ToString()'],
-      { encoding: 'utf8' }
-    ).status === 0
-  )
-})
-if (!powerShellExecutable) {
-  console.error('A native PowerShell executable is required')
-  process.exit(2)
-}
-const powerShellVersion = spawnSync(
-  powerShellExecutable,
-  ['-NoProfile', '-NonInteractive', '-Command', '$PSVersionTable.PSVersion.ToString()'],
-  { encoding: 'utf8' }
-).stdout.trim()
+const probePowerShell = (candidate) => {
+  const probe = spawnSync(
+    candidate,
+    ['-NoProfile', '-NonInteractive', '-Command', '$PSVersionTable.PSVersion.ToString()'],
+    { encoding: 'utf8' }
+  )
+  return probe.status === 0 ? (probe.stdout ?? '').trim() : undefined
+}
+const candidates = configuredPowerShell
+  ? [configuredPowerShell]
+  : process.platform === 'win32'
+    ? ['pwsh.exe', 'powershell.exe']
+    : ['pwsh']
+let powerShellExecutable
+let powerShellVersion
+for (const candidate of candidates) {
+  const version = probePowerShell(candidate)
+  if (version !== undefined) {
+    powerShellExecutable = candidate
+    powerShellVersion = version
+    break
+  }
+}
+if (!powerShellExecutable) {
+  console.error(`A native PowerShell executable is required (tried: ${candidates.join(', ')})`)
+  process.exit(2)
+}

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ec5ee4a8-2c03-4288-9bf1-053ceb9843f4

📥 Commits

Reviewing files that changed from the base of the PR and between 53acc89c2b7cd45aa75a19773e11e296f0e751dc and ad53ba58c261964b6c89b04bbca5c1daec52f286.

📒 Files selected for processing (2)
  • config/reliability-gates.jsonc
  • config/scripts/run-ssh-staged-upload-reliability.mjs

Comment on lines +113 to +136
"evidenceRuns": [
{
"date": "2026-07-31",
"runner": "local",
"platform": "macos",
"command": "node config/scripts/run-ssh-staged-upload-reliability.mjs --powershell <PowerShell-7.6.4-executable> src/main/ssh/sftp-upload.test.ts src/main/ssh/ssh-file-transfer-abort.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts src/main/ssh/ssh-relay-sftp-namespace-install.test.ts src/main/ssh/ssh-relay-install-namespace.test.ts src/main/ssh/ssh-relay-upload-stage-commands.test.ts src/main/ssh/sftp-namespace-resolution.test.ts src/main/ssh/ssh-connection-sftp-wire.test.ts src/main/ssh/ssh-remote-commands.test.ts src/main/ssh/ssh-relay-cross-version-isolation.test.ts",
"result": "passed",
"durationSeconds": 57.9,
"summary": "Eleven focused files passed 152 tests with 3 platform skips using exact POSIX sh, native ARM macOS PowerShell 7.6.4, real ssh2 split-SFTP wire sessions, fixed-slot identity races, bounded recovery, joined cancellation teardown, and cross-version isolation."
},
{
"date": "2026-07-31",
"runner": "local",
"platform": "linux",
"command": "ORCA_REVIEW_SSH_UPLOAD_CANCEL=1 ORCA_REVIEW_SSH_TARGET_HOST=<non-loopback-host> ORCA_REVIEW_SSH_IMAGE=<throwaway-sshd-image> ORCA_REVIEW_EXPECT_RECOVERY=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-upload-cancel.docker.test.ts --maxWorkers=1 --reporter=verbose",
"result": "passed",
"durationSeconds": 12.58,
"summary": "A throwaway linux-arm64 Docker sshd acknowledged 65,536 of 837,401 relay.js bytes before live abort with no shared lock and preserved the foreign sleep sentinel. Two injected unconfirmed stages remained pre-lock; retry launched the relay, answered RPC, and read a real Git HEAD. Installed recovery preserved a same-owner identity-mismatched replacement, its original, a POSIX symlink, and its foreign target while draining one valid stale slot behind them. Real version GC retained all 15,197 unrelated names, emitted 25 bytes, and completed in 25 ms."
}
],
"runtimeBudget": {
"p95Seconds": 35,
"scope": "focused unit, SFTP-wire, and local Docker SSH contracts"
},

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Raise p95Seconds above the recorded in-scope duration.

The runtimeBudget.scope covers the focused unit, SFTP-wire, and Docker commands. The registered evidence run for the focused command took 57.9 seconds (Line 120), which exceeds the 35-second budget on Line 134. As written, the gate declares its own passing command over budget.

Set the budget above the observed duration, or narrow the scope to the Docker command only.

🔧 Proposed budget correction
       "runtimeBudget": {
-        "p95Seconds": 35,
+        "p95Seconds": 90,
         "scope": "focused unit, SFTP-wire, and local Docker SSH contracts"
       },
📝 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.

Suggested change
"evidenceRuns": [
{
"date": "2026-07-31",
"runner": "local",
"platform": "macos",
"command": "node config/scripts/run-ssh-staged-upload-reliability.mjs --powershell <PowerShell-7.6.4-executable> src/main/ssh/sftp-upload.test.ts src/main/ssh/ssh-file-transfer-abort.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts src/main/ssh/ssh-relay-sftp-namespace-install.test.ts src/main/ssh/ssh-relay-install-namespace.test.ts src/main/ssh/ssh-relay-upload-stage-commands.test.ts src/main/ssh/sftp-namespace-resolution.test.ts src/main/ssh/ssh-connection-sftp-wire.test.ts src/main/ssh/ssh-remote-commands.test.ts src/main/ssh/ssh-relay-cross-version-isolation.test.ts",
"result": "passed",
"durationSeconds": 57.9,
"summary": "Eleven focused files passed 152 tests with 3 platform skips using exact POSIX sh, native ARM macOS PowerShell 7.6.4, real ssh2 split-SFTP wire sessions, fixed-slot identity races, bounded recovery, joined cancellation teardown, and cross-version isolation."
},
{
"date": "2026-07-31",
"runner": "local",
"platform": "linux",
"command": "ORCA_REVIEW_SSH_UPLOAD_CANCEL=1 ORCA_REVIEW_SSH_TARGET_HOST=<non-loopback-host> ORCA_REVIEW_SSH_IMAGE=<throwaway-sshd-image> ORCA_REVIEW_EXPECT_RECOVERY=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-upload-cancel.docker.test.ts --maxWorkers=1 --reporter=verbose",
"result": "passed",
"durationSeconds": 12.58,
"summary": "A throwaway linux-arm64 Docker sshd acknowledged 65,536 of 837,401 relay.js bytes before live abort with no shared lock and preserved the foreign sleep sentinel. Two injected unconfirmed stages remained pre-lock; retry launched the relay, answered RPC, and read a real Git HEAD. Installed recovery preserved a same-owner identity-mismatched replacement, its original, a POSIX symlink, and its foreign target while draining one valid stale slot behind them. Real version GC retained all 15,197 unrelated names, emitted 25 bytes, and completed in 25 ms."
}
],
"runtimeBudget": {
"p95Seconds": 35,
"scope": "focused unit, SFTP-wire, and local Docker SSH contracts"
},
"evidenceRuns": [
{
"date": "2026-07-31",
"runner": "local",
"platform": "macos",
"command": "node config/scripts/run-ssh-staged-upload-reliability.mjs --powershell <PowerShell-7.6.4-executable> src/main/ssh/sftp-upload.test.ts src/main/ssh/ssh-file-transfer-abort.test.ts src/main/ssh/ssh-relay-deploy-staged-upload.test.ts src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts src/main/ssh/ssh-relay-sftp-namespace-install.test.ts src/main/ssh/ssh-relay-install-namespace.test.ts src/main/ssh/ssh-relay-upload-stage-commands.test.ts src/main/ssh/sftp-namespace-resolution.test.ts src/main/ssh/ssh-connection-sftp-wire.test.ts src/main/ssh/ssh-remote-commands.test.ts src/main/ssh/ssh-relay-cross-version-isolation.test.ts",
"result": "passed",
"durationSeconds": 57.9,
"summary": "Eleven focused files passed 152 tests with 3 platform skips using exact POSIX sh, native ARM macOS PowerShell 7.6.4, real ssh2 split-SFTP wire sessions, fixed-slot identity races, bounded recovery, joined cancellation teardown, and cross-version isolation."
},
{
"date": "2026-07-31",
"runner": "local",
"platform": "linux",
"command": "ORCA_REVIEW_SSH_UPLOAD_CANCEL=1 ORCA_REVIEW_SSH_TARGET_HOST=<non-loopback-host> ORCA_REVIEW_SSH_IMAGE=<throwaway-sshd-image> ORCA_REVIEW_EXPECT_RECOVERY=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-relay-upload-cancel.docker.test.ts --maxWorkers=1 --reporter=verbose",
"result": "passed",
"durationSeconds": 12.58,
"summary": "A throwaway linux-arm64 Docker sshd acknowledged 65,536 of 837,401 relay.js bytes before live abort with no shared lock and preserved the foreign sleep sentinel. Two injected unconfirmed stages remained pre-lock; retry launched the relay, answered RPC, and read a real Git HEAD. Installed recovery preserved a same-owner identity-mismatched replacement, its original, a POSIX symlink, and its foreign target while draining one valid stale slot behind them. Real version GC retained all 15,197 unrelated names, emitted 25 bytes, and completed in 25 ms."
}
],
"runtimeBudget": {
"p95Seconds": 90,
"scope": "focused unit, SFTP-wire, and local Docker SSH contracts"
},

Comment on lines +50 to +53
const requestedFiles = cliArguments.filter(
(_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1
)
const files = requestedFiles.length > 0 ? requestedFiles : defaultFiles

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Fix the argument filter: it drops the first test path when --powershell is absent.

cliArguments.indexOf('--powershell') returns -1 when the flag is absent. Then powerShellFlag + 1 is 0, so the predicate index !== powerShellFlag + 1 removes cliArguments[0].

Effects:

  • node config/scripts/run-ssh-staged-upload-reliability.mjs a.test.ts b.test.ts runs only b.test.ts.
  • node config/scripts/run-ssh-staged-upload-reliability.mjs a.test.ts produces an empty requestedFiles and silently runs all 11 defaultFiles.

Guard the filter with the flag presence.

🐛 Proposed fix
-const requestedFiles = cliArguments.filter(
-  (_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1
-)
+const requestedFiles =
+  powerShellFlag >= 0
+    ? cliArguments.filter(
+        (_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1
+      )
+    : cliArguments
📝 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.

Suggested change
const requestedFiles = cliArguments.filter(
(_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1
)
const files = requestedFiles.length > 0 ? requestedFiles : defaultFiles
const requestedFiles =
powerShellFlag >= 0
? cliArguments.filter(
(_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1
)
: cliArguments
const files = requestedFiles.length > 0 ? requestedFiles : defaultFiles

@OrcaWin
OrcaWin force-pushed the pr/recover-orphaned-relay-lock branch from ad53ba5 to a3c4796 Compare July 31, 2026 23:10
@OrcaWin
OrcaWin merged commit f56e6ad into stablyai:main Jul 31, 2026
45 of 56 checks passed

@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: 8

🧹 Nitpick comments (8)
src/main/ssh/ssh-relay-deploy-staged-upload.test.ts (1)

138-152: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the imported timing constants instead of the literal 900_000.

Line 167 advances a hardcoded 900_000, and line 171 asserts the same value in the message. RELAY_DEPLOY_TIMEOUT_MS is already imported and used in the next test. A change to the timing constant would leave this test asserting a stale value. Line 142 also repeats the isRelayAlreadyInstalled reset already done in beforeEach, and line 152 immediately overrides it.

♻️ Proposed cleanup
       const conn = makeMockConnection()
-      vi.mocked(isRelayAlreadyInstalled).mockReset().mockResolvedValue(true)
       vi.mocked(execCommand).mockImplementation((_conn, command) => {
-      await vi.advanceTimersByTimeAsync(900_000)
+      await vi.advanceTimersByTimeAsync(RELAY_DEPLOY_TIMEOUT_MS)
 
       const result = await promise
       expect(result).toBeInstanceOf(Error)
-      expect((result as Error).message).toBe('Relay deployment timed out after 900s')
+      expect((result as Error).message).toBe(
+        `Relay deployment timed out after ${RELAY_DEPLOY_TIMEOUT_MS / 1000}s`
+      )
src/main/ssh/ssh-relay-upload-cancel.docker.test.ts (3)

155-160: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the relay build platform instead of hardcoding linux-arm64.

Lines 157-160 and lines 248-252 read out/relay/linux-arm64, and lines 288, 362, and 369 pass getRemoteHostPlatform('linux-arm64'). On an x64 review host the container and the local relay build are both x64, so statSync and readFileSync throw an opaque ENOENT before any assertion runs. Compute the platform once from the container architecture, or fail early with a message that names the missing build directory.

♻️ Proposed change
+const RELAY_PLATFORM = `linux-${process.arch === 'arm64' ? 'arm64' : 'x64'}` as const
+const LOCAL_RELAY_DIR = join(process.cwd(), 'out', 'relay', RELAY_PLATFORM)

Then replace the literal uses:

-    const localRelayDir = join(process.cwd(), 'out', 'relay', 'linux-arm64')
+    const localRelayDir = LOCAL_RELAY_DIR

Also applies to: 246-252


328-328: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the scale count and assert it against the same constant.

Line 328 creates 15197 directories in a shell loop, and line 397 repeats the literal 15_197. The two values must stay in sync, and the loop is the slowest step of the suite. Extract one constant and reference it in both places.

♻️ Proposed change
+const GC_SCALE_ENTRY_COUNT = 15_197
-          `i=0; while [ "$i" -lt 15197 ]; do mkdir ${shellQuote(`/root/.orca-remote/relay-${relayVersion}.upload-scale-`)}"$i"; i=$((i + 1)); done`
+          `i=0; while [ "$i" -lt ${GC_SCALE_ENTRY_COUNT} ]; do mkdir ${shellQuote(`/root/.orca-remote/relay-${relayVersion}.upload-scale-`)}"$i"; i=$((i + 1)); done`
-      expect(scaleEntries).toBe(15_197)
+      expect(scaleEntries).toBe(GC_SCALE_ENTRY_COUNT)

Also applies to: 391-398


346-358: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the reclamation assertion fail with a readable message.

Line 357 runs test ! -e <stage> && echo RECLAIMED. If the stage still exists, the remote command exits non-zero, so execFileSync throws instead of producing an expect diff. Report the presence as output and assert on that value.

♻️ Proposed change
-      expect(
-        dockerExec(activeFixture, `test ! -e ${shellQuote(reclaimableStage)} && echo RECLAIMED`)
-      ).toBe('RECLAIMED')
+      expect(
+        dockerExec(
+          activeFixture,
+          `test -e ${shellQuote(reclaimableStage)} && echo PRESENT || echo RECLAIMED`
+        )
+      ).toBe('RECLAIMED')
tests/e2e/helpers/docker-ssh-relay-target.ts (1)

126-132: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Simplify the host validation and narrow the published bind address.

Three points in this block:

  • The nested if at lines 127-131 is redundant. Validate only the configured value.
  • If ORCA_E2E_SSH_TARGET_HOST holds only whitespace, trim() yields '', the default 127.0.0.1 applies, and the error then reports 127.0.0.1 for a value the caller never set. Validate the trimmed env value directly.
  • Line 150 binds to 0.0.0.0 for any non-loopback host, which publishes the container SSH port on every interface of the runner. Bind to the configured host address instead.
♻️ Proposed change
-  const host = process.env.ORCA_E2E_SSH_TARGET_HOST?.trim() || '127.0.0.1'
-  if (host === 'localhost' || host === '::1' || host.startsWith('127.')) {
-    if (process.env.ORCA_E2E_SSH_TARGET_HOST) {
-      throw new Error(`ORCA_E2E_SSH_TARGET_HOST must be non-loopback: ${host}`)
-    }
-  }
-  const bindHost = host === '127.0.0.1' ? host : '0.0.0.0'
+  const configuredHost = process.env.ORCA_E2E_SSH_TARGET_HOST?.trim()
+  if (
+    configuredHost &&
+    (configuredHost === 'localhost' ||
+      configuredHost === '::1' ||
+      configuredHost.startsWith('127.'))
+  ) {
+    throw new Error(`ORCA_E2E_SSH_TARGET_HOST must be non-loopback: ${configuredHost}`)
+  }
+  const host = configuredHost || '127.0.0.1'
+  const bindHost = host

If Docker cannot bind the mapped port to the configured address in your CI network setup, keep 0.0.0.0 and state that constraint in a one-line comment.

Also applies to: 150-150

src/main/ssh/ssh-relay-upload-stage-commands.ts (1)

35-50: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the slot-name pattern from RELAY_UPLOAD_STAGE_SLOT_COUNT.

The pattern ^slot-[0-7]$ encodes the slot count a second time. If RELAY_UPLOAD_STAGE_SLOT_COUNT changes, reservation emits slot-8 and parseReservedRelayUploadStage rejects it at runtime.

♻️ Proposed refactor
-  if (!/^slot-[0-7]$/u.test(slotName)) {
+  const slotIndex = /^slot-(\d+)$/u.exec(slotName)?.[1]
+  if (!slotIndex || Number(slotIndex) >= RELAY_UPLOAD_STAGE_SLOT_COUNT) {
     throw new Error('Invalid relay upload stage slot')
   }
src/main/ssh/ssh-relay-install-namespace.ts (1)

102-121: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reject CR and LF in relativeFileName, as the install mapping does.

relaySftpNamespaceMapping rejects \r and \n at lines 86-88. assertSafeRemotePathSegment with 'posix' returns early and allows both characters, so this stage mapping accepts a filename that can forge log lines. The only current caller passes '.version', so this is a consistency gap today.

♻️ Proposed refactor
   if (relativeFileName !== undefined) {
     assertSafeRemotePathSegment(relativeFileName, 'posix')
+    if (relativeFileName.includes('\r') || relativeFileName.includes('\n')) {
+      throw new Error('Unsafe remote path segment in relay SFTP mapping')
+    }
   }
src/main/ssh/ssh-remote-commands.ts (1)

66-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unused promoteRemoteTreeContentsCommand export.

promoteRemoteTreeContentsCommand has no production references outside its definition, while staged promotion uses promoteOwnedRelayUploadStageCommand. Remove the duplicate export to avoid maintenance risk.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6ab2c32d-76f0-44ca-951c-a84ad29ecb40

📥 Commits

Reviewing files that changed from the base of the PR and between ad53ba58c261964b6c89b04bbca5c1daec52f286 and a3c4796.

📒 Files selected for processing (35)
  • config/reliability-gates.jsonc
  • config/scripts/run-ssh-staged-upload-reliability.mjs
  • src/main/ssh/sftp-namespace-resolution.test.ts
  • src/main/ssh/sftp-namespace-resolution.ts
  • src/main/ssh/sftp-upload.test.ts
  • src/main/ssh/sftp-upload.ts
  • src/main/ssh/ssh-connection-sftp-namespace.test.ts
  • src/main/ssh/ssh-connection-sftp-wire.test.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ssh/ssh-file-transfer-abort.test.ts
  • src/main/ssh/ssh-file-transfer-abort.ts
  • src/main/ssh/ssh-relay-cross-version-isolation.test.ts
  • src/main/ssh/ssh-relay-deploy-staged-upload.test.ts
  • src/main/ssh/ssh-relay-deploy-timing.ts
  • src/main/ssh/ssh-relay-deploy.test.ts
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-install-lock.test.ts
  • src/main/ssh/ssh-relay-install-lock.ts
  • src/main/ssh/ssh-relay-install-namespace.test.ts
  • src/main/ssh/ssh-relay-install-namespace.ts
  • src/main/ssh/ssh-relay-install-transfers.ts
  • src/main/ssh/ssh-relay-native-deps-install-fixture.ts
  • src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts
  • src/main/ssh/ssh-relay-sftp-namespace-install.test.ts
  • src/main/ssh/ssh-relay-upload-cancel.docker.test.ts
  • src/main/ssh/ssh-relay-upload-stage-commands.test.ts
  • src/main/ssh/ssh-relay-upload-stage-commands.ts
  • src/main/ssh/ssh-relay-upload-stage-contract.ts
  • src/main/ssh/ssh-relay-upload-stage-windows-commands.ts
  • src/main/ssh/ssh-relay-versioned-install.ts
  • src/main/ssh/ssh-remote-commands.test.ts
  • src/main/ssh/ssh-remote-commands.ts
  • tests/e2e/helpers/docker-ssh-relay-connection.ts
  • tests/e2e/helpers/docker-ssh-relay-target.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/main/ssh/ssh-relay-install-lock.test.ts
  • src/main/ssh/ssh-relay-install-lock.ts
  • config/scripts/run-ssh-staged-upload-reliability.mjs
  • config/reliability-gates.jsonc
  • src/main/ssh/ssh-relay-native-deps-install-staged-upload.test.ts
  • src/main/ssh/ssh-relay-cross-version-isolation.test.ts

Comment on lines +71 to +98
const abortTransfer = (): void => {
const reason =
options?.signal?.reason instanceof Error
? options.signal.reason
: Object.assign(new Error('Upload aborted'), { name: 'AbortError' })
readStream?.destroy(reason)
writeStream?.destroy()
void fileHandle?.close().catch(() => {})
fn(val as never)
void closeHandle().catch(() => {})
}
const onWriteClose = (): void => settle(resolve)
const onWriteError = (err: Error): void => settle(reject, err)
const onReadError = (err: Error): void => settle(reject, err)

void open(localPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
.then(async (handle) => {
if (settled) {
void handle.close().catch(() => {})
return
}
fileHandle = handle
const statResult = await lstat(localPath)
if (statResult.isSymbolicLink() || !statResult.isFile()) {
throw new Error(`Unsupported upload source: ${localPath}`)
}
const openedStat = await handle.stat()
if (
!openedStat.isFile() ||
openedStat.size !== statResult.size ||
(statResult.ino !== 0 && openedStat.ino !== 0 && openedStat.ino !== statResult.ino) ||
(statResult.dev !== 0 && openedStat.dev !== 0 && openedStat.dev !== statResult.dev)
) {
throw new Error(`File changed during upload: ${localPath}`)
}
// Why: validate the local source before creating the remote write
// target, so rejected sources do not leave empty files behind.
writeStream = sftp.createWriteStream(remotePath, {
flags: options?.exclusive ? 'wx' : 'w'
})
writeStream.on('close', onWriteClose)
writeStream.on('error', onWriteError)
readStream = handle.createReadStream()
readStream.on('error', onReadError)
readStream.pipe(writeStream)
options?.signal?.addEventListener('abort', abortTransfer, { once: true })
if (options?.signal?.aborted) {
abortTransfer()
}
try {
const readDone = finished(readStream, { cleanup: true }).catch((error: unknown) => {
writeStream?.destroy()
throw error
})
.catch((err: unknown) => settle(reject, err))
})
const writeDone = finished(writeStream, { cleanup: true }).catch((error: unknown) => {
readStream?.destroy(error instanceof Error ? error : undefined)
throw error
})
readStream.pipe(writeStream)
const results = await Promise.allSettled([readDone, writeDone])
const failure = results.find((result) => result.status === 'rejected')
if (failure?.status === 'rejected') {
throw failure.reason
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Unify the abort reason instead of relying on stream-settlement order.

abortTransfer destroys readStream with reason but destroys writeStream with no reason. If readStream already finished before abort fires (plausible for small files, since backpressure has not yet engaged), only writeStream gets destroyed, and finished(writeStream) rejects with a generic premature-close error, not one named AbortError. results.find(rejected) then throws that generic error instead of the abort reason.

Capture the abort reason once and throw it whenever the signal aborted, independent of which stream settles first.

🐛 Proposed fix to unify the abort reason
+    let abortReason: (Error & { name: string }) | undefined
     const abortTransfer = (): void => {
-      const reason =
-        options?.signal?.reason instanceof Error
-          ? options.signal.reason
-          : Object.assign(new Error('Upload aborted'), { name: 'AbortError' })
-      readStream?.destroy(reason)
-      writeStream?.destroy()
+      abortReason =
+        options?.signal?.reason instanceof Error
+          ? (options.signal.reason as Error & { name: string })
+          : Object.assign(new Error('Upload aborted'), { name: 'AbortError' })
+      readStream?.destroy(abortReason)
+      writeStream?.destroy(abortReason)
       void closeHandle().catch(() => {})
     }
@@
       const results = await Promise.allSettled([readDone, writeDone])
+      if (abortReason) {
+        throw abortReason
+      }
       const failure = results.find((result) => result.status === 'rejected')
       if (failure?.status === 'rejected') {
         throw failure.reason
       }
📝 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.

Suggested change
const abortTransfer = (): void => {
const reason =
options?.signal?.reason instanceof Error
? options.signal.reason
: Object.assign(new Error('Upload aborted'), { name: 'AbortError' })
readStream?.destroy(reason)
writeStream?.destroy()
void fileHandle?.close().catch(() => {})
fn(val as never)
void closeHandle().catch(() => {})
}
const onWriteClose = (): void => settle(resolve)
const onWriteError = (err: Error): void => settle(reject, err)
const onReadError = (err: Error): void => settle(reject, err)
void open(localPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
.then(async (handle) => {
if (settled) {
void handle.close().catch(() => {})
return
}
fileHandle = handle
const statResult = await lstat(localPath)
if (statResult.isSymbolicLink() || !statResult.isFile()) {
throw new Error(`Unsupported upload source: ${localPath}`)
}
const openedStat = await handle.stat()
if (
!openedStat.isFile() ||
openedStat.size !== statResult.size ||
(statResult.ino !== 0 && openedStat.ino !== 0 && openedStat.ino !== statResult.ino) ||
(statResult.dev !== 0 && openedStat.dev !== 0 && openedStat.dev !== statResult.dev)
) {
throw new Error(`File changed during upload: ${localPath}`)
}
// Why: validate the local source before creating the remote write
// target, so rejected sources do not leave empty files behind.
writeStream = sftp.createWriteStream(remotePath, {
flags: options?.exclusive ? 'wx' : 'w'
})
writeStream.on('close', onWriteClose)
writeStream.on('error', onWriteError)
readStream = handle.createReadStream()
readStream.on('error', onReadError)
readStream.pipe(writeStream)
options?.signal?.addEventListener('abort', abortTransfer, { once: true })
if (options?.signal?.aborted) {
abortTransfer()
}
try {
const readDone = finished(readStream, { cleanup: true }).catch((error: unknown) => {
writeStream?.destroy()
throw error
})
.catch((err: unknown) => settle(reject, err))
})
const writeDone = finished(writeStream, { cleanup: true }).catch((error: unknown) => {
readStream?.destroy(error instanceof Error ? error : undefined)
throw error
})
readStream.pipe(writeStream)
const results = await Promise.allSettled([readDone, writeDone])
const failure = results.find((result) => result.status === 'rejected')
if (failure?.status === 'rejected') {
throw failure.reason
}
let abortReason: (Error & { name: string }) | undefined
const abortTransfer = (): void => {
abortReason =
options?.signal?.reason instanceof Error
? (options.signal.reason as Error & { name: string })
: Object.assign(new Error('Upload aborted'), { name: 'AbortError' })
readStream?.destroy(abortReason)
writeStream?.destroy(abortReason)
void closeHandle().catch(() => {})
}
options?.signal?.addEventListener('abort', abortTransfer, { once: true })
if (options?.signal?.aborted) {
abortTransfer()
}
try {
const readDone = finished(readStream, { cleanup: true }).catch((error: unknown) => {
writeStream?.destroy()
throw error
})
const writeDone = finished(writeStream, { cleanup: true }).catch((error: unknown) => {
readStream?.destroy(error instanceof Error ? error : undefined)
throw error
})
readStream.pipe(writeStream)
const results = await Promise.allSettled([readDone, writeDone])
if (abortReason) {
throw abortReason
}
const failure = results.find((result) => result.status === 'rejected')
if (failure?.status === 'rejected') {
throw failure.reason
}

Comment on lines +168 to +181
const teardown = await Promise.race([
deployment,
new Promise<typeof teardownExpired>((resolve) => {
teardownTimeoutHandle = setTimeout(
() => resolve(teardownExpired),
RELAY_DEPLOY_TEARDOWN_TIMEOUT_MS
)
})
]).finally(() => clearTimeout(teardownTimeoutHandle!))
const timeoutError = Object.assign(
new Error(`Relay deployment timed out after ${RELAY_DEPLOY_TIMEOUT_MS / 1000}s`),
teardownConfirmation(teardown === teardownExpired ? undefined : teardown)
)
throw timeoutError

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

Return a late successful deployment instead of discarding it.

The teardown race can resolve with status: 'fulfilled'. In that case the relay is launched and outcome.result holds a live transport and socket path. The current code throws the timeout error and drops that result, so nothing closes the launched transport and the caller reports a timeout for a running relay.

🐛 Proposed fix
     ]).finally(() => clearTimeout(teardownTimeoutHandle!))
+    if (teardown !== teardownExpired && teardown.status === 'fulfilled') {
+      // A late success still owns the launched transport; hand it back instead of leaking it.
+      return teardown.result
+    }
     const timeoutError = Object.assign(
       new Error(`Relay deployment timed out after ${RELAY_DEPLOY_TIMEOUT_MS / 1000}s`),
       teardownConfirmation(teardown === teardownExpired ? undefined : teardown)
     )
     throw timeoutError
📝 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.

Suggested change
const teardown = await Promise.race([
deployment,
new Promise<typeof teardownExpired>((resolve) => {
teardownTimeoutHandle = setTimeout(
() => resolve(teardownExpired),
RELAY_DEPLOY_TEARDOWN_TIMEOUT_MS
)
})
]).finally(() => clearTimeout(teardownTimeoutHandle!))
const timeoutError = Object.assign(
new Error(`Relay deployment timed out after ${RELAY_DEPLOY_TIMEOUT_MS / 1000}s`),
teardownConfirmation(teardown === teardownExpired ? undefined : teardown)
)
throw timeoutError
const teardown = await Promise.race([
deployment,
new Promise<typeof teardownExpired>((resolve) => {
teardownTimeoutHandle = setTimeout(
() => resolve(teardownExpired),
RELAY_DEPLOY_TEARDOWN_TIMEOUT_MS
)
})
]).finally(() => clearTimeout(teardownTimeoutHandle!))
if (teardown !== teardownExpired && teardown.status === 'fulfilled') {
// A late success still owns the launched transport; hand it back instead of leaking it.
return teardown.result
}
const timeoutError = Object.assign(
new Error(`Relay deployment timed out after ${RELAY_DEPLOY_TIMEOUT_MS / 1000}s`),
teardownConfirmation(teardown === teardownExpired ? undefined : teardown)
)
throw timeoutError

Comment on lines +416 to +421
await execHostCommand(
conn,
hostPlatform,
recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir),
{ signal: deploySignal }
)

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

Make pre-upload stale-stage recovery best-effort.

This execHostCommand failure propagates and fails the deployment before any stage is reserved. The Windows recovery script uses -ErrorAction Stop on Move-Item, Remove-Item, and Get-ChildItem -Recurse, so a single contended or unreadable stage entry blocks every new install. The post-launch call at Line 578 already treats recovery as best-effort.

Keep abort propagation, and swallow other failures.

🛡️ Proposed fix
-    await execHostCommand(
-      conn,
-      hostPlatform,
-      recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir),
-      { signal: deploySignal }
-    )
+    await execHostCommand(
+      conn,
+      hostPlatform,
+      recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir),
+      { signal: deploySignal }
+    ).catch((err: unknown) => {
+      deploySignal?.throwIfAborted()
+      if (isUnconfirmedSshCommandTermination(err)) {
+        throw err
+      }
+    })
📝 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.

Suggested change
await execHostCommand(
conn,
hostPlatform,
recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir),
{ signal: deploySignal }
)
await execHostCommand(
conn,
hostPlatform,
recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir),
{ signal: deploySignal }
).catch((err: unknown) => {
deploySignal?.throwIfAborted()
if (isUnconfirmedSshCommandTermination(err)) {
throw err
}
})

Comment on lines +123 to +131
export function makeRelayUploadStageDirectoryCommand(
namespace: RelayUploadStageNamespace,
host: RemoteHostPlatform,
shellStageDir: string
): string {
const payloadDir = joinRemotePath(host, shellStageDir, 'payload')
const markerPath = joinRemotePath(host, shellStageDir, namespace.markerFileName)
return `${makeRemoteDirectoryCommand(host, payloadDir)} && umask 077 && touch ${shellEscape(markerPath)}`
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find every reference to the stage directory helper with context.
rg -nP -C3 '\bmakeRelayUploadStageDirectoryCommand\b' --type=ts

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -u

echo "Repo files matching target filename:"
fd -a 'ssh-relay-install-namespace\.ts$' . || true

echo
echo "All occurrences of helper name in tracked TS files:"
rg -n -C3 '\bmakeRelayUploadStageDirectoryCommand\b' --glob '*.ts' . || true

echo
echo "All occurrences in tracked files:"
rg -n -C3 '\bmakeRelayUploadStageDirectoryCommand\b' . || true

Repository: stablyai/orca

Length of output: 3967


🏁 Script executed:

#!/bin/bash
set -u

echo "Outline:"
ast-grep outline src/main/ssh/ssh-relay-install-namespace.ts --view expanded || true

echo
echo "Relevant source lines:"
cat -n src/main/ssh/ssh-relay-install-namespace.ts | sed -n '60,160p'

echo
echo "Relevant test lines:"
cat -n src/main/ssh/ssh-relay-install-namespace.test.ts | sed -n '1,190p'

echo
echo "Remote host types and command helpers:"
rg -n -C3 'RemoteHostPlatform|makeRemoteDirectoryCommand|isWindowsRemoteHost|LINUX|WINDOWS' src/main/ssh ssh-relay-install-namespace.ts || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -u

echo "Helper definitions:"
rg -n -C4 'export function makeRemoteDirectoryCommand|function makeRemoteDirectoryCommand|makeRemoteDirectoryCommand\s*=' src/main/ssh --type=ts || true

echo
echo "MakeRemoteDirectoryCommand references (files only):"
rg -n --files-with-matches '\bmakeRemoteDirectoryCommand\b' src/main/ssh --type=ts || true

Repository: stablyai/orca

Length of output: 1100


Gate makeRelayUploadStageDirectoryCommand behind isWindowsRemoteHost.

makeRemoteDirectoryCommand emits PowerShell on Windows, so the trailing POSIX sequence must be excluded or generated with a Windows-safe marker creation step.

Source: Coding guidelines

Comment on lines +44 to +47
vi.mock('./ssh-relay-install-marker', async (importOriginal) => ({
...(await importOriginal<typeof RelayInstallMarkerModule>()),
createRelayInstallMarkerFileName: () => '.sftp-namespace-00000000000000000000000000000000'
}))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return distinct deterministic marker values.

createRelayInstallMarkerFileName returns the same value for every call. The stage marker and install-lock marker are therefore equal. The assertions at Line 372 cannot detect accidental marker reuse.

Return deterministic per-call marker values. Assert that stageMarker and installMarker differ.

Comment on lines +111 to +117
describe.each([
['POSIX', posix] as const,
...((powerShellExecutable ? [['PowerShell', windows] as const] : []) as (readonly [
string,
RemoteHostPlatform
])[])
])('%s relay upload stage commands', (_label, host) => {

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

Gate the POSIX-dialect suites and the symlink test on non-Windows.

Two problems appear when this file runs on a Windows host:

  • Line 73 executes /bin/sh. Windows has no /bin/sh, so spawnSync sets status to null and every assertion in the POSIX rows of describe.each (line 112) and in describe('POSIX ownership race fencing') (line 221) fails.
  • Line 172 calls symlinkSync. Windows CI agents usually lack Developer Mode or elevation, so the call throws EPERM.

Add process.platform === 'win32' guards so the POSIX rows and the symlink test skip on Windows.

🛡️ Proposed guards
+const posixShellAvailable = process.platform !== 'win32'
+
 describe.each([
-  ['POSIX', posix] as const,
+  ...((posixShellAvailable ? [['POSIX', posix] as const] : []) as (readonly [
+    string,
+    RemoteHostPlatform
+  ])[]),
   ...((powerShellExecutable ? [['PowerShell', windows] as const] : []) as (readonly [
     string,
     RemoteHostPlatform
   ])[])
 ])('%s relay upload stage commands', (_label, host) => {
-  it('rejects a payload reparse point without copying or deleting it', () => {
+  it.skipIf(process.platform === 'win32')(
+    'rejects a payload reparse point without copying or deleting it',
+    () => {
-describe('POSIX ownership race fencing', () => {
+describe.runIf(posixShellAvailable)('POSIX ownership race fencing', () => {

As per coding guidelines: "code, commands, and scripts must work on macOS, Linux, and Windows". Based on learnings: tests that create filesystem symlinks should be guarded with it.skipIf(process.platform === 'win32').

Also applies to: 164-172, 221-222

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawnSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Sources: Coding guidelines, Learnings

Comment on lines +227 to +254
function recoverPosixStageCommand(poolDir: string, staleMinutes: number): string {
const pool = shellEscape(poolDir)
const slots = Array.from({ length: RELAY_UPLOAD_STAGE_SLOT_COUNT }, (_, index) => index).join(' ')
return [
`pool=${pool}; [ -d "$pool" ] && [ ! -L "$pool" ] || exit 0;`,
`for n in ${slots}; do`,
'slot="$pool/slot-$n"; claim="$pool/claim-$n"; deleting="$pool/delete-$n";',
`if [ -d "$deleting" ] && [ ! -L "$deleting" ]; then owner_file="$deleting/${OWNER_FILE_NAME}"; identity_file="$deleting/${IDENTITY_FILE_NAME}"; deleting_actual=$(cat "$owner_file" 2>/dev/null) || deleting_actual=; expected_identity=$(cat "$identity_file" 2>/dev/null) || expected_identity=; deleting_identity=$(ls -id "$deleting" 2>/dev/null | awk '{print $1}') || deleting_identity=; deleting_old=$(find "$owner_file" -prune -type f -mmin +${staleMinutes} -print 2>/dev/null) || deleting_old=; if [ -n "$deleting_identity" ] && [ "$deleting_identity" = "$expected_identity" ] && [ -f "$owner_file" ] && [ ! -L "$owner_file" ] && [ -f "$identity_file" ] && [ ! -L "$identity_file" ] && printf '%s' "$deleting_actual" | grep -Eq '^\\.sftp-namespace-[0-9a-f]{32}$' && [ -n "$deleting_old" ] && links=$(find "$deleting" -type l -print -quit 2>/dev/null) && [ -z "$links" ]; then rm -rf "$deleting"; exit 0; fi; fi;`,
'if [ ! -e "$claim" ] && [ ! -L "$claim" ] && [ ! -e "$deleting" ] && [ ! -L "$deleting" ] && [ -d "$slot" ] && [ ! -L "$slot" ] &&',
`old=$(find "$slot/${OWNER_FILE_NAME}" -prune -type f -mmin +${staleMinutes} -print 2>/dev/null) && [ -n "$old" ]; then`,
'mv "$slot" "$claim" 2>/dev/null || continue;',
'fi;',
`owner_file="$claim/${OWNER_FILE_NAME}"; identity_file="$claim/${IDENTITY_FILE_NAME}"; actual=$(cat "$owner_file" 2>/dev/null) || actual=; expected_identity=$(cat "$identity_file" 2>/dev/null) || expected_identity=; identity=$(ls -id "$claim" 2>/dev/null | awk '{print $1}') || identity=; old=$(find "$owner_file" -prune -type f -mmin +${staleMinutes} -print 2>/dev/null) || old=;`,
`if [ -n "$identity" ] && [ "$identity" = "$expected_identity" ] && [ -d "$claim" ] && [ ! -L "$claim" ] && [ -f "$owner_file" ] && [ ! -L "$owner_file" ] && [ -f "$identity_file" ] && [ ! -L "$identity_file" ] && printf '%s' "$actual" | grep -Eq '^\\.sftp-namespace-[0-9a-f]{32}$' && [ -n "$old" ]; then`,
'claim_identity="$identity";',
'[ ! -e "$deleting" ] && [ ! -L "$deleting" ] && mv "$claim" "$deleting" 2>/dev/null || continue;',
`owner_file="$deleting/${OWNER_FILE_NAME}"; identity_file="$deleting/${IDENTITY_FILE_NAME}"; deleting_actual=$(cat "$owner_file" 2>/dev/null) || deleting_actual=; expected_identity=$(cat "$identity_file" 2>/dev/null) || expected_identity=; deleting_identity=$(ls -id "$deleting" 2>/dev/null | awk '{print $1}') || deleting_identity=; deleting_old=$(find "$owner_file" -prune -type f -mmin +${staleMinutes} -print 2>/dev/null) || deleting_old=;`,
`if [ -n "$deleting_identity" ] && [ "$deleting_identity" = "$claim_identity" ] && [ "$deleting_identity" = "$expected_identity" ] && [ -d "$deleting" ] && [ ! -L "$deleting" ] && [ -f "$owner_file" ] && [ ! -L "$owner_file" ] && [ -f "$identity_file" ] && [ ! -L "$identity_file" ] && printf '%s' "$deleting_actual" | grep -Eq '^\\.sftp-namespace-[0-9a-f]{32}$' && [ -n "$deleting_old" ] && links=$(find "$deleting" -type l -print -quit 2>/dev/null) && [ -z "$links" ]; then`,
'rm -rf "$deleting"; exit 0;',
'fi;',
'if [ ! -e "$claim" ] && [ ! -L "$claim" ]; then mv "$deleting" "$claim" 2>/dev/null || true; fi;',
'continue;',
'fi;',
posixRestoreClaim(),
'done;',
'exit 0'
].join(' ')
}

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

Stale recovery restores claims it did not create, on both platforms. Both recovery loops guard the claim restore only by the absence of slot. A live installer between the claim prelude and the delete step has already moved slot to claim, so recovery moves that active claim back and breaks the owner's promotion or cleanup. The fix in both scripts is the same: record that this run performed the slot to claim move, and restore only then.

  • src/main/ssh/ssh-relay-upload-stage-commands.ts#L227-L254: set moved_claim=1 after the recovery mv "$slot" "$claim", and skip the slot with [ "$moved_claim" = 1 ] || continue; before the ownership checks and posixRestoreClaim().
  • src/main/ssh/ssh-relay-upload-stage-windows-commands.ts#L232-L244: set $moved = $true after Move-Item -LiteralPath $slot -Destination $claim, and continue when $moved is false, so windowsRestoreClaim() runs only for a claim this run created.
📍 Affects 2 files
  • src/main/ssh/ssh-relay-upload-stage-commands.ts#L227-L254 (this comment)
  • src/main/ssh/ssh-relay-upload-stage-windows-commands.ts#L232-L244

Comment on lines +209 to +238
it('bounds real POSIX GC output with more than the exec-cap stage population', async () => {
const root = mkdtempSync(join(tmpdir(), 'orca-relay-gc-scale-'))
try {
for (let index = 0; index < 15_197; index += 1) {
mkdirSync(join(root, `relay-0.1.0+abc.upload-${String(index).padStart(12, '0')}`))
}
mkdirSync(join(root, 'relay-0.1.0+aaa'))
mkdirSync(join(root, 'relay-0.1.0+bbb'))

const output = await runShellCommand(listRelayBaseDirsCommand(posix, root))
const entries = output.trim().split('\n')

expect(entries).toEqual(['relay-0.1.0+aaa', 'relay-0.1.0+bbb'])
expect(Buffer.byteLength(output)).toBeLessThan(1_024)
expect(entries.length).toBeLessThanOrEqual(MAX_RELAY_GC_LISTING_ENTRIES)
} finally {
rmSync(root, { recursive: true, force: true })
}
}, 30_000)

it('fails closed when real POSIX GC enumeration fails', async () => {
const root = mkdtempSync(join(tmpdir(), 'orca-relay-gc-failure-'))
try {
const command = `find() { return 23; }\n${listRelayBaseDirsCommand(posix, root)}`
await expect(runShellCommand(command)).rejects.toThrow('shell exited 1')
} finally {
rmSync(root, { recursive: true, force: 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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check for platform guards around POSIX-only shell tests in ssh-remote-commands.test.ts
rg -n "skipIf|platform === 'win32'|process.platform" src/main/ssh/ssh-remote-commands.test.ts

Repository: stablyai/orca

Length of output: 363


🏁 Script executed:

#!/bin/bash
set -eu

echo "== file size =="
wc -l src/main/ssh/ssh-remote-commands.test.ts

echo "== relevant imports/top section =="
sed -n '1,120p' src/main/ssh/ssh-remote-commands.test.ts

echo "== runShellCommand definition/usages =="
rg -n "runShellCommand|listRelayBaseDirsCommand|spawn\\('/bin/sh'|spawn\\('"/bin/sh|MAX_RELAY_GC_LISTING_ENTRIES|describe\\(.*ssh" src/main/ssh/ssh-remote-commands.test.ts src/main/ssh -S

Repository: stablyai/orca

Length of output: 3945


🏁 Script executed:

#!/bin/bash
set -eu

echo "== POSIX guard references =="
rg -n "runIf\\(process\\.platform !== 'win32'\\)|skipIf\\(process\\.platform === 'win32'\\)|process\\.platform" src/main/ssh/ssh-remote-commands.test.ts

echo "== shell command usages =="
rg -n "runShellCommand\\(" src/main/ssh/ssh-remote-commands.test.ts

echo "== targeted lines around POSIX guards =="
sed -n '180,250p' src/main/ssh/ssh-remote-commands.test.ts
sed -n '250,320p' src/main/ssh/ssh-remote-commands.test.ts
sed -n '420,480p' src/main/ssh/ssh-remote-commands.test.ts

Repository: stablyai/orca

Length of output: 9102


Guard the POSIX-only shell GC tests on Windows.

runShellCommand spawns /bin/sh, and the two new real-shell GC tests call it directly without skipping on Windows. Wrap these tests with it.runIf(process.platform !== 'win32') or describe.skipIf(process.platform === 'win32') so CI does not try to start /bin/sh on Windows.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync, spawn, spawnSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Source: Coding guidelines

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes orphaned relay install locks (#9828) by staging uploads in attempt-owned .upload-stages/slot-N/payload directories and promoting them into the shared version directory only after the install lock is acquired. This decouples the upload phase from the lock so a canceled pre-install upload no longer leaves an orphaned lock that blocks subsequent installs.

  • Staged upload protocol: new ssh-relay-upload-stage-commands.ts / ssh-relay-upload-stage-windows-commands.ts implement reserve → upload → lock → promote → cleanup across POSIX and PowerShell, with inode-validated ownership and stale-slot recovery.
  • Transfer abort improvement: sftp-upload.ts rewrites uploadFile with node:stream/promises.finished(), explicit autoClose: false, and per-file AbortSignal support; raceSftpFileTransferWithAbort gains a new sshTransferTeardownConfirmed flag and a deregistrable close listener.
  • Post-timeout teardown window: deployAndLaunchRelay now waits up to RELAY_DEPLOY_TEARDOWN_TIMEOUT_MS (5 s) after the deploy timeout fires before throwing, so the error carries accurate sshChannelCloseConfirmed / sshTransferTeardownConfirmed metadata for lock-orphan recovery decisions.

Confidence Score: 4/5

The staged-upload logic is complex but well-tested, and the core ordering invariant (upload to lock to promote) is clearly upheld throughout the deploy flow.

The change introduces a non-trivial remote shell protocol (reserve/promote/cleanup across POSIX sh and PowerShell) with inode-identity checks, stale-recovery loops, and a new teardown-confirmation window. The focused test suite covers the critical retry, cancellation, and cross-version paths. The only flagged issues are a hardcoded stale-duration string in two error messages and an exported-but-unused production function, neither of which affects correctness.

Files Needing Attention: ssh-relay-upload-stage-commands.ts and ssh-relay-upload-stage-windows-commands.ts carry the new remote shell logic and deserve close attention; ssh-relay-deploy.ts coordinates the full staged flow and is the most likely place for edge-case ordering issues.

Important Files Changed

Filename Overview
src/main/ssh/ssh-relay-deploy.ts Core deploy orchestrator reworked: upload now goes to a staged slot (reserve → upload → lock → promote → cleanup) instead of directly into the versioned relay dir; timeout handling gains a 5-second teardown window for teardown confirmation metadata
src/main/ssh/ssh-relay-upload-stage-commands.ts New file: POSIX shell command builders for the upload staging protocol (reserve, promote, cleanup, recover); contains complex inode-identity checks and symlink-safety guards
src/main/ssh/ssh-relay-upload-stage-windows-commands.ts New file: PowerShell equivalents of the upload staging commands using Win32 file-identity via inline C# and Get-Item ReparsePoint checks; mirrors POSIX logic faithfully
src/main/ssh/sftp-upload.ts Rewrites uploadFile to use node:stream/promises.finished(), autoClose:false with explicit handle.close(), and per-file AbortSignal support; uploadDirectory now propagates the signal to each file upload
src/main/ssh/ssh-file-transfer-abort.ts Adds sshTransferTeardownConfirmed flag (set when both SFTP channel close and operation settlement are observed after abort) and deregisterable close listener to prevent listener leak
src/main/ssh/ssh-relay-install-lock.ts Now re-throws unconfirmed SSH termination errors from the lock-acquire loop instead of swallowing them, preventing the lock waiter from masking a connection drop as ordinary contention
src/main/ssh/ssh-relay-install-namespace.ts Adds RelayUploadStageNamespace type, createRelayUploadStageNamespace, relayUploadStageSftpNamespaceMapping, and makeRelayUploadStageDirectoryCommand; makeRelayUploadStageDirectoryCommand is exported but not called in the production deploy flow
src/main/ssh/ssh-relay-install-transfers.ts Propagates AbortSignal into uploadDirectory and adds a deregistrable close-listener return from the fallback SFTP transfer path
src/main/ssh/ssh-relay-versioned-install.ts GC listing is now bounded by MAX_RELAY_GC_LISTING_ENTRIES (64) to prevent unbounded output parsing on hosts with many relay versions
src/main/ssh/ssh-relay-upload-stage-contract.ts New constants/types file defining the staging protocol: slot count (8), stale threshold (40 min), file names, and the slot shape

Reviews (1): Last reviewed commit: "test(ssh): align deploy timeout oracle" | Re-trigger Greptile

'fi;',
'fi;',
'done;',
`printf '%s\\n' 'Orca relay upload staging quota is full; reconnect after 40 minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}' >&2;`,

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 The stale duration in the error message is hardcoded as "40 minutes" rather than derived from RELAY_UPLOAD_STAGE_STALE_SECONDS. If the constant is ever changed, this user-facing string will silently describe the wrong wait time.

Suggested change
`printf '%s\\n' 'Orca relay upload staging quota is full; reconnect after 40 minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}' >&2;`,
`printf '%s\\n' 'Orca relay upload staging quota is full; reconnect after ${RELAY_UPLOAD_STAGE_STALE_SECONDS / 60} minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}' >&2;`,

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

'exit 0',
'} catch { continue }',
'}',
`throw ${powerShellLiteral(`Orca relay upload staging quota is full; reconnect after 40 minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}`)}`

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 Same hardcoded "40 minutes" discrepancy as the POSIX version — derives the duration from the literal string rather than RELAY_UPLOAD_STAGE_STALE_SECONDS.

Suggested change
`throw ${powerShellLiteral(`Orca relay upload staging quota is full; reconnect after 40 minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}`)}`
`throw ${powerShellLiteral(`Orca relay upload staging quota is full; reconnect after ${RELAY_UPLOAD_STAGE_STALE_SECONDS / 60} minutes or inspect .orca-remote/${RELAY_UPLOAD_STAGE_POOL_NAME}`)}`

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +123 to +130
export function makeRelayUploadStageDirectoryCommand(
namespace: RelayUploadStageNamespace,
host: RemoteHostPlatform,
shellStageDir: string
): string {
const payloadDir = joinRemotePath(host, shellStageDir, 'payload')
const markerPath = joinRemotePath(host, shellStageDir, namespace.markerFileName)
return `${makeRemoteDirectoryCommand(host, payloadDir)} && umask 077 && touch ${shellEscape(markerPath)}`

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 makeRelayUploadStageDirectoryCommand is exported but unreachable in production. The reservation command (reservePosixStageCommand / reserveWindowsRelayUploadStageCommand) already creates slot-N/payload and touches the marker file as part of a single atomic reserve step. makeRelayUploadStageDirectoryCommand is only exercised by a unit test and is never called from ssh-relay-deploy.ts or any other production path. Either wire it in somewhere intentional or remove the export to avoid confusion about the directory-creation contract.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#10207)

* fix(ssh): recover orphaned relay install locks (stablyai#9828)

* test(ssh): split staged upload relay specs (stablyai#9828)

* fix(ssh): verify staged relay upload namespace

* fix(ssh): bound stale relay stage cleanup

* fix(ssh): complete bounded stage recovery

* fix(ssh): generate valid PowerShell stage scripts

* fix(ssh): make staged upload cancellation safe

* fix(ssh): fence staged relay recovery

* test(ssh): align deploy timeout oracle

---------

Co-authored-by: OrcaWin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: SSH relay retry silently waits on orphaned install lock after cancelled deployment

3 participants