Repository navigation
fix(ssh): recover orphaned relay install locks (#9828) - #10207
Conversation
📝 WalkthroughWalkthroughRelay 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)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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.tssrc/main/ssh/ssh-relay-deploy.test.tssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-install-lock.test.tssrc/main/ssh/ssh-relay-install-lock.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/main/ssh/ssh-remote-commands.test.tssrc/main/ssh/ssh-remote-commands.ts
|
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 |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/ssh/ssh-relay-deploy-staged-upload.test.ts (1)
164-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winOptional: extract the shared
execCommandcommand-router into a helper.The same
uname/echo $HOME/test -S/ORCA-NATIVErouting 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 thesocketProbesequence) 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.tssrc/main/ssh/ssh-relay-deploy.test.tssrc/main/ssh/ssh-relay-native-deps-install-staged-upload.test.tssrc/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
|
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. |
9d3012e to
ad53ba5
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
config/scripts/run-ssh-staged-upload-reliability.mjs (1)
25-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFail when an explicitly configured PowerShell path is unusable, and probe once.
Two points:
- If
--powershellorORCA_POWERSHELL_EXECUTABLEnames an executable whose probe fails, the code falls back topwshwithout any message. The gate evidence inconfig/reliability-gates.jsoncclaims a specific PowerShell 7.6.4 executable, so a silent substitution can attribute a run to the wrong interpreter.- Lines 32-38 and 44-48 run the same probe command twice. Reuse the first result. This also removes the
null-stdoutdereference 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.jsoncconfig/scripts/run-ssh-staged-upload-reliability.mjs
| "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" | ||
| }, |
There was a problem hiding this comment.
📐 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.
| "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" | |
| }, |
| const requestedFiles = cliArguments.filter( | ||
| (_argument, index) => index !== powerShellFlag && index !== powerShellFlag + 1 | ||
| ) | ||
| const files = requestedFiles.length > 0 ? requestedFiles : defaultFiles |
There was a problem hiding this comment.
🎯 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.tsruns onlyb.test.ts.node config/scripts/run-ssh-staged-upload-reliability.mjs a.test.tsproduces an emptyrequestedFilesand silently runs all 11defaultFiles.
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.
| 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 |
ad53ba5 to
a3c4796
Compare
There was a problem hiding this comment.
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 winUse 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_MSis 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 theisRelayAlreadyInstalledreset already done inbeforeEach, 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 winDerive 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 passgetRemoteHostPlatform('linux-arm64'). On an x64 review host the container and the local relay build are both x64, sostatSyncandreadFileSyncthrow 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_DIRAlso applies to: 246-252
328-328: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName 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 winMake 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, soexecFileSyncthrows instead of producing anexpectdiff. 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 winSimplify the host validation and narrow the published bind address.
Three points in this block:
- The nested
ifat lines 127-131 is redundant. Validate only the configured value.- If
ORCA_E2E_SSH_TARGET_HOSTholds only whitespace,trim()yields'', the default127.0.0.1applies, and the error then reports127.0.0.1for a value the caller never set. Validate the trimmed env value directly.- Line 150 binds to
0.0.0.0for 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 = hostIf Docker cannot bind the mapped port to the configured address in your CI network setup, keep
0.0.0.0and 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 winDerive the slot-name pattern from
RELAY_UPLOAD_STAGE_SLOT_COUNT.The pattern
^slot-[0-7]$encodes the slot count a second time. IfRELAY_UPLOAD_STAGE_SLOT_COUNTchanges, reservation emitsslot-8andparseReservedRelayUploadStagerejects 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 winReject CR and LF in
relativeFileName, as the install mapping does.
relaySftpNamespaceMappingrejects\rand\nat lines 86-88.assertSafeRemotePathSegmentwith'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 valueRemove the unused
promoteRemoteTreeContentsCommandexport.
promoteRemoteTreeContentsCommandhas no production references outside its definition, while staged promotion usespromoteOwnedRelayUploadStageCommand. 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.jsoncconfig/scripts/run-ssh-staged-upload-reliability.mjssrc/main/ssh/sftp-namespace-resolution.test.tssrc/main/ssh/sftp-namespace-resolution.tssrc/main/ssh/sftp-upload.test.tssrc/main/ssh/sftp-upload.tssrc/main/ssh/ssh-connection-sftp-namespace.test.tssrc/main/ssh/ssh-connection-sftp-wire.test.tssrc/main/ssh/ssh-connection.tssrc/main/ssh/ssh-file-transfer-abort.test.tssrc/main/ssh/ssh-file-transfer-abort.tssrc/main/ssh/ssh-relay-cross-version-isolation.test.tssrc/main/ssh/ssh-relay-deploy-staged-upload.test.tssrc/main/ssh/ssh-relay-deploy-timing.tssrc/main/ssh/ssh-relay-deploy.test.tssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-install-lock.test.tssrc/main/ssh/ssh-relay-install-lock.tssrc/main/ssh/ssh-relay-install-namespace.test.tssrc/main/ssh/ssh-relay-install-namespace.tssrc/main/ssh/ssh-relay-install-transfers.tssrc/main/ssh/ssh-relay-native-deps-install-fixture.tssrc/main/ssh/ssh-relay-native-deps-install-staged-upload.test.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/main/ssh/ssh-relay-sftp-namespace-install.test.tssrc/main/ssh/ssh-relay-upload-cancel.docker.test.tssrc/main/ssh/ssh-relay-upload-stage-commands.test.tssrc/main/ssh/ssh-relay-upload-stage-commands.tssrc/main/ssh/ssh-relay-upload-stage-contract.tssrc/main/ssh/ssh-relay-upload-stage-windows-commands.tssrc/main/ssh/ssh-relay-versioned-install.tssrc/main/ssh/ssh-remote-commands.test.tssrc/main/ssh/ssh-remote-commands.tstests/e2e/helpers/docker-ssh-relay-connection.tstests/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
| 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 | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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 | |
| } |
| 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 |
There was a problem hiding this comment.
🩺 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.
| 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 |
| await execHostCommand( | ||
| conn, | ||
| hostPlatform, | ||
| recoverOneStaleRelayUploadStageCommand(hostPlatform, uploadStagePoolDir), | ||
| { signal: deploySignal } | ||
| ) |
There was a problem hiding this comment.
🩺 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.
| 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 | |
| } | |
| }) |
| 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)}` | ||
| } |
There was a problem hiding this comment.
🎯 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=tsRepository: 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' . || trueRepository: 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 || trueRepository: 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 || trueRepository: 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
| vi.mock('./ssh-relay-install-marker', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof RelayInstallMarkerModule>()), | ||
| createRelayInstallMarkerFileName: () => '.sftp-namespace-00000000000000000000000000000000' | ||
| })) |
There was a problem hiding this comment.
🎯 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.
| describe.each([ | ||
| ['POSIX', posix] as const, | ||
| ...((powerShellExecutable ? [['PowerShell', windows] as const] : []) as (readonly [ | ||
| string, | ||
| RemoteHostPlatform | ||
| ])[]) | ||
| ])('%s relay upload stage commands', (_label, host) => { |
There was a problem hiding this comment.
🩺 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, sospawnSyncsetsstatustonulland every assertion in the POSIX rows ofdescribe.each(line 112) and indescribe('POSIX ownership race fencing')(line 221) fails. - Line 172 calls
symlinkSync. Windows CI agents usually lack Developer Mode or elevation, so the call throwsEPERM.
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
| 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(' ') | ||
| } |
There was a problem hiding this comment.
🩺 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: setmoved_claim=1after the recoverymv "$slot" "$claim", and skip the slot with[ "$moved_claim" = 1 ] || continue;before the ownership checks andposixRestoreClaim().src/main/ssh/ssh-relay-upload-stage-windows-commands.ts#L232-L244: set$moved = $trueafterMove-Item -LiteralPath $slot -Destination $claim, andcontinuewhen$movedis false, sowindowsRestoreClaim()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
| 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 }) | ||
| } | ||
| }) | ||
|
|
There was a problem hiding this comment.
🩺 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.tsRepository: 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 -SRepository: 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.tsRepository: 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 SummaryThis PR fixes orphaned relay install locks (#9828) by staging uploads in attempt-owned
Confidence Score: 4/5The 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.
|
| 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;`, |
There was a problem hiding this comment.
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.
| `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}`)}` |
There was a problem hiding this comment.
Same hardcoded
"40 minutes" discrepancy as the POSIX version — derives the duration from the literal string rather than RELAY_UPLOAD_STAGE_STALE_SECONDS.
| `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!
| 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)}` |
There was a problem hiding this comment.
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.
…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]>
Summary
.upload-*directories and promote them into the shared version directory only after the install lock is acquired..install-lock, while unconfirmed post-promotion installs still keep the existing fence.Closes #9828.
Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildFocused 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-lockout of the upload phase;INSTALL_LOCK_STALE_MSand 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.