Skip to content

perf(ssh): reuse one proxy connection for system SSH on Windows - #31731

Closed
bing-xbx wants to merge 7 commits into
stablyai:mainfrom
bing-xbx:perf/windows-ssh-connection-reuse
Closed

bing-xbx wants to merge 7 commits into
stablyai:mainfrom
bing-xbx:perf/windows-ssh-connection-reuse

Conversation

@bing-xbx

@bing-xbx bing-xbx commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Windows system-SSH commands to ProxyCommand/ProxyJump targets currently repeat the proxy handshake for every command. This change starts one validated loopback forward after the initial connection succeeds; later commands authenticate through that forward while retaining the original alias, credentials and host-key identity. Commands keep using the direct proxy route until the forward is ready and fall back when it exits or startup fails.

The original contributor implementation and ancestry are preserved. The refresh also preserves current-main SSH identity diagnostics and fixes startup/cleanup races:

  • Disconnect and reconnect abort the pending route generation, including port allocation, listener polling, the login probe and the allocated forward. A stale completion cannot replace the new connection's route.
  • Probe abort, timeout and stream errors close the live probe. Disposal is idempotent, skips known exited/signaled child PIDs, and rechecks child liveness before a delayed direct-kill fallback.
  • The touched forward launcher uses the existing process-host abstraction; no additional process wrapper is introduced.

The route remains limited to proxied Windows system-SSH connections, respects systemSshConnectionReuse: false, and excludes Kerberos and unclaimed aliases. It binds only to loopback and changes no persisted schema or client/server wire contract. No UI changes.

Related: #31558, #32582.

Validation

At the final integration head on main 9b6a2e8ff1fe:

  • 77 tests across eight suites pass, including three opt-in tests against an isolated real local OpenSSH server. These cover the touched forward launcher, actual authentication/listener ownership and existing port-forward behavior.
  • The independently reviewed production source is byte-identical to candidate b301b6ac7ba1, where 92 focused tests/seven suites passed. Independent review ran 53 focused tests plus three separate probes. Counts overlap.
  • Node typecheck, full oxlint for all eight changed code files, all seven changed-code quality scans, process-host import checks and diff checks pass.
  • Three original lifecycle regressions were reproduced before the correction. Independent review also reproduced and verified the probe stream-error leak fix.

All local tests use ORCA_BACKGROUND_LAUNCH=1; no app windows were launched. Current-head CI remains the source for platform/build results.

Reliability and remaining acceptance

Invariant: ssh.system-transport-owned-lifecycle — canceled connection generations must stop pending route work and cannot adopt or dispose a newer connection's route. The oracles assert zero post-cancellation allocation, immediate forward/probe disposal, stopped listener polling, stale-generation isolation, and zero tree-kill dispatch for a child already known to have exited. These directly address the disconnect/reconnect paths in this PR. Logs and independent counterexample probes are preserved in the audit evidence.

Gate gap: there is no dedicated loopback-lifecycle entry in config/reliability-gates.jsonc; the focused regression suites run through normal unit CI. The existing Docker SSH resource-lifecycle gate covers broader terminal recovery and does not establish this Windows proxy behavior.

Performance budget: startup remains off the connection-critical await path; one pending/held route belongs to a connection generation. Existing 60-second listener and 15-second probe bounds remain, and cancellation releases their polling/socket/probe work. No new polling loop or per-command proxy process is added by the correction.

Provider/platform coverage: macOS local real-OpenSSH forward acceptance and deterministic connection/Windows-branch tests pass. The optimization is gated out on macOS/Linux. Local/daemon PTY identity and WSL routing are unchanged. Desktop-hosted mobile and folder workspaces use the same connection lifetime without a workspace-kind assumption; live mobile, folder and mixed-version remote acceptance was not performed.

Native Windows ProxyCommand/ProxyJump authentication, host-key rejection/certificates/FIDO, full-app timing, app exit and descendant cleanup remain unverified at this final head. Windows disposal initiates asynchronous tree-kill; disconnect does not await confirmed descendant exit. The exited-PID guard prevents knowingly targeting a dead child but does not eliminate the OS exit/PID-reuse race or prove descendants are gone after a natural root exit. No complete process-quiescence or issue-closure claim is made.

The original contributor reported real Windows 11/OpenSSH 9.5p2 module measurements: direct commands took 8.0–10.7 seconds and five routed commands took 0.64–0.78 seconds, with existing known-host trust accepted. Those historical measurements and cleanup observations were not independently repeated on this final source. Full application connection latency remains unmeasured here.

Windows OpenSSH cannot multiplex (ControlMaster fails with "getsockname
failed: Not a socket"), so every system-SSH exec for a ProxyCommand or
ProxyJump target re-ran the proxy handshake. Hold one `ssh -N -L` through
the real proxy per session and dial later execs over 127.0.0.1 with
HostName/Port/ProxyCommand=none/ProxyJump=none/HostKeyAlias overrides.

The route starts after connect, is proven with a login before use, falls
back to per-command proxying on any failure, honors
systemSshConnectionReuse: false, and is torn down with its proxy child
via terminateWindowsProcessTree.

Fixes stablyai#31558
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c44bc391-d026-45f9-bf65-c0413aed3f4d
📥 Commits

Reviewing files that changed from the base of the PR and between 6268f2f and 2e098b6.

📒 Files selected for processing: 6
  • config/process-host-direct-import-baseline.txt
  • src/main/ssh/connection/ssh-connection-loopback-cancel.test.ts
  • src/main/ssh/connection/ssh-connection.ts
  • src/main/ssh/system-transport/system-ssh-forward-process.ts
  • src/main/ssh/system-transport/system-ssh-loopback-route.test.ts
  • src/main/ssh/system-transport/system-ssh-loopback-route.ts
💤 Files with no reviewable changes: 1
  • config/process-host-direct-import-baseline.txt

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

📝 Walkthrough

The change adds Windows-specific loopback routing for eligible system-SSH proxy targets. It starts and probes a persistent local forward, then supplies loopback connection arguments to later SSH commands. The implementation adds listener-timeout handling, route cleanup, and generation-aware connection-state management. Tests cover route selection, SSH arguments, startup, probe failures, reconnects, fallback behavior, and disposal.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 2e098

Confirm that a forward which exits before its callback is registered cannot leave subsequent commands using a closed port. Until then, merging carries a bounded fallback risk.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning The PR implements the main [#31558] Windows system-SSH reuse path. It starts a validated loopback forward, preserves the proxied host-key alias, routes later operations through loopback, respects the … Add the specified 300-second idle lifetime after the last route use. Track the route identity and invalidate or rebuild the route when that identity changes. Add automated tests for both behaviors.
Docstring Coverage Warning Docstring coverage is 26.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly summarizes the main change: reusing one proxy connection for Windows system SSH.
Description check Passed The description is detailed and covers the change, rationale, linked issues, testing, platform scope, limitations, and cleanup behavior. It does not reproduce every template heading or checklist, but …
Out of Scope Changes check Passed The changed source, process-host adjustment, lifecycle handling, and tests support [#31558]. They cover loopback forwarding, argument preservation, eligibility gates, fallback, cancellation, and proce…
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, linked issues, testing, platform scope, limitations, and cleanup behavior. It does not reproduce every template heading or checklist, but it provides the required information in substance.

Full details: Out of Scope Changes check

Explanation

The changed source, process-host adjustment, lifecycle handling, and tests support [#31558]. They cover loopback forwarding, argument preservation, eligibility gates, fallback, cancellation, and process cleanup. No unrelated product behavior is shown.

Full details: Linked Issues check

Explanation

The PR implements the main [#31558] Windows system-SSH reuse path. It starts a validated loopback forward, preserves the proxied host-key alias, routes later operations through loopback, respects the reuse opt-out, and falls back when startup or the forward fails. The issue also specifies a 300-second idle lifetime and identity-based invalidation. The reviewed code has no idle timer or last-use tracking, and its generation checks do not detect identity changes.

Resolution

Add the specified 300-second idle lifetime after the last route use. Track the route identity and invalidate or rebuild the route when that identity changes. Add automated tests for both behaviors.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 18791919-5992-4c50-ab99-50ad34792e80
📥 Commits

Reviewing files that changed from the base of the PR and between b0fcdb4 and b1cdd46.

📒 Files selected for processing: 6
  • src/main/ssh/connection/ssh-connection.ts
  • src/main/ssh/system-transport/system-ssh-args.ts
  • src/main/ssh/system-transport/system-ssh-forward-process.test.ts
  • src/main/ssh/system-transport/system-ssh-forward-process.ts
  • src/main/ssh/system-transport/system-ssh-loopback-route.test.ts
  • src/main/ssh/system-transport/system-ssh-loopback-route.ts

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

…start is in flight

Key the route-starting guard by connect generation so a start superseded by reconnect cannot block the new generation's route. Adds SshConnection lifecycle tests: route adoption, reconnect during a pending start, forward exit, and disconnect.
…ection-reuse

# Conflicts:
#	src/main/ssh/connection/ssh-connection.ts

@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


ℹ️ Review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 40babcf9-0e49-4f60-b103-dc10765001d1
📥 Commits

Reviewing files that changed from the base of the PR and between 3835c2d and 14a8524.

📒 Files selected for processing: 2
  • src/main/ssh/connection/ssh-connection.ts
  • src/main/ssh/system-transport/system-ssh-args.ts

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

… an already-exited forward

Check connection ownership before starting the forward, and make onExit fire for a forward that exited before the listener was registered, so the connection never keeps a dead route.
@bing-xbx

Copy link
Copy Markdown
Contributor Author

@nwparker this is the Windows counterpart of the system-SSH ControlMaster reuse: Windows OpenSSH can't multiplex, so proxied targets currently pay the full proxy handshake on every exec. On a real ProxyCommand host it takes execs from ~8–10s to ~0.7s each.

It's rebased onto your ssh-connection split (hooks the probe's onConnected), CodeRabbit's three findings are fixed with tests, and it's gated to win32 + proxied targets with the existing systemSshConnectionReuse opt-out. Happy to reshape it if you'd rather fold it into the transport differently, and I can test any Windows-specific follow-up against a real proxied host.

nwparker added a commit that referenced this pull request Oct 24, 2026
…33030)

* perf(ssh): reuse one proxy connection for system SSH on Windows

Windows OpenSSH cannot multiplex (ControlMaster fails with "getsockname
failed: Not a socket"), so every system-SSH exec for a ProxyCommand or
ProxyJump target re-ran the proxy handshake. Hold one `ssh -N -L` through
the real proxy per session and dial later execs over 127.0.0.1 with
HostName/Port/ProxyCommand=none/ProxyJump=none/HostKeyAlias overrides.

The route starts after connect, is proven with a login before use, falls
back to per-command proxying on any failure, honors
systemSshConnectionReuse: false, and is torn down with its proxy child.

Rebased from #31731 (commits b1cdd46, 3835c2d, 6268f2f) onto current main,
including the pending-route cancellation fix from b301b6a.

Co-authored-by: Neil <[email protected]>

* refactor(ssh): stop the loopback forward through process-host's tree kill

Reuse signalProcessTree instead of a hand-rolled taskkill-then-kill
fallback: it already joins an in-flight tree kill, refuses a reaped PID,
and falls back to killing the root, so the route keeps no parallel copy
of that logic.

* fix(ssh): harden the Windows loopback route against review findings

- Manual targets: take the forward's sshd port and the HostKeyAlias from
  the stored endpoint; `ssh -G` ran on the label and named another host.
- Hold the forward with ServerAlive probes so a silently dead proxy ends
  it and commands fall back instead of stalling on 127.0.0.1.
- Never route forwards: their argv must stay stable for orphan recovery,
  and the route's own forward must take the real proxy.
- Upload sessions read the route per file, so an exited route's port is
  not dialled after it closes.
- Skip the route for security-key identities, whose forward and probe
  logins would each ask for an unprompted touch.

* fix(ssh): keep the loopback route for manual targets no Host block claims

The unclaimed-alias endpoint rewrite only applies to config-backed targets,
so manual targets with a configHost no block names stay eligible.

* fix(ssh): keep the held loopback forward non-interactive

The forward is an optional background login; with BatchMode=no a password or
passphrase login raised an extra prompt right after connect, which the
non-interactive probe then discarded anyway.

* fix(ssh): admit the loopback route only when it changes nothing but the route

Overriding HostName to 127.0.0.1 changes which ssh_config blocks match, so a
`Match host <real host>` block could silently switch the remote User (or
identities, certificates, known-hosts files) for every routed command. Run
`ssh -G` with and without the route options and refuse the route on any
difference outside HostName/Port/HostKeyAlias/ProxyCommand/ProxyJump.

Also ask the agent with `ssh-add -L` and refuse the route when it may hold a
security key, so the background forward and probe never request a touch.
Both checks run through process-host and fail closed.

* feat(ssh): make Windows proxy connection reuse an opt-in per-target setting

The loopback route rewrites HostName, which ssh_config can key settings on,
so it no longer turns on by itself: a new optional systemSshProxyConnectionReuse
field (default off, Windows only) enables it from the SSH host's Advanced
settings. Old clients and servers ignore or omit the field.

Admission stays as the safety net and now:
- takes the forward's sshd port and HostKeyAlias from the direct `ssh -G`,
  so a manual host's own Host block cannot send the route to another sshd;
- refuses any non-routing value with a `%` token, which `ssh -G` can leave
  unexpanded while a routed login expands `%h` to 127.0.0.1;
- checks the security-key and agent identities of every ProxyJump hop;
- asserts the routed config really dials 127.0.0.1 with no proxy left.

* fix(ssh): offer proxy reuse only for hosts this desktop dials, refuse ${VAR} paths

- The switch now appears only for this desktop's own SSH hosts. A paired
  server's add-host dialog never shows or sends it, so an older server's
  strict schema is never handed the new field, and a client's platform no
  longer decides a server's setting.
- Admission also refuses `${VAR}` references, which `ssh -G` prints
  unexpanded while a login expands them.
- Advanced no longer auto-opens just for the opt-in.

---------

Co-authored-by: Bingxin Xu <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Thank you so much, @bing-xbx! Your diagnosis was spot on. We measured 55 proxy handshakes per Windows connect, and with a slow proxy your held loopback forward cut connect time from about 200 s to about 33 s. We shipped your approach in #33030, with your commit and authorship kept. Review turned up several ssh_config cases where switching to a loopback route could quietly change which user or keys a login uses (Match host, %h, ${VAR}), so we made it an opt-in per-host setting ("Reuse one proxy connection" under Advanced on Windows). It still checks the effective config automatically and falls back to the normal route on any doubt. On top of your work we also added keepalives, kept user port forwards off the route, made the background tunnel non-interactive, and skip it when a security key might be needed. Your real Windows measurements made this an easy call. Thanks again!

@nwparker nwparker closed this Oct 24, 2026
@bing-xbx

Copy link
Copy Markdown
Contributor Author

Thank you @nwparker ! Really appreciate the quick response. Happy to contribute to the project!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants