Repository navigation
fix(ssh): handle owner displacement and graceful shutdown - #12367
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe changes add bounded SSH shutdown handling to the application quit sequence. SSH work is fenced during shutdown, active sessions are detached, transports are disconnected, and in-flight operations are drained. Owner recovery now retries pending publication errors with lifecycle guards. PTY consumer sessions validate hello data, track displaced owners, support rollback-safe takeovers, and clean up displaced relay clients. Tests cover shutdown races, recovery retries, durability, validation, and owner displacement. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0f935f15-bc70-4a5e-88d6-c14c60f54858
📒 Files selected for processing (14)
src/main/index.tssrc/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/main/ssh/ssh-owner-recovery-retry.test.tssrc/main/ssh/ssh-owner-recovery-retry.tssrc/main/ssh/ssh-relay-session-recovery-durability.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/dispatcher.tssrc/relay/relay-pty-consumer-owner-displacement.test.tssrc/relay/ssh-pty-consumer-session-adapter.tssrc/shared/pty-consumer-session-contract.tssrc/shared/pty-consumer-session-hello.tssrc/shared/pty-consumer-session.test.tssrc/shared/pty-consumer-session.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/ssh.ts (1)
1317-1318: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winFence the reset transport immediately before it opens.
Line 1318 only fences reset admission. If shutdown starts while
doResetRelay()waits forinFlightConnect.promise,doResetRelay()can later callconnectionManager.connect(target)without checking the gate again. That transport can open after the bounded join and final drain.Check
quitTeardownStartGateimmediately before the fallbackconnectionManager.connect(target)call. Add a shutdown-race test for a reset paused behind an in-flight connect.Proposed fix
const existingConn = connectionManager!.getConnection(targetId) -const conn = existingConn ?? (await connectionManager!.connect(target)) +let conn = existingConn +if (!conn) { + assertSshConnectsNotFenced() + conn = await connectionManager!.connect(target) +}
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7a882aea-152a-451a-9d3e-1e7d9ca84fd4
📒 Files selected for processing (7)
src/main/index.tssrc/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/main/quit-teardown-start-gate.tssrc/main/ssh/ssh-relay-session-recovery-durability.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/relay-pty-consumer-owner-displacement.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/index.ts
- src/main/ssh/ssh-relay-session.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/ssh.ts (1)
1109-1113: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftHandle cancelled
doConnectafterconnectionManager.connect()completes.The manager deletes and disconnects a cancelled in-flight connect when it later resolves. But
doConnectthen checksownsSession()and rethrowscreateCancelledConnectAttemptError()at the later call site, so that cleanup may be undone by the surrounding error branch instead of leaving the transport disconnected. Close and remove only the exact connection that resolved late, and still clean up its session/transport whensession.establish()resumes after invalidation. Cover the delayed resolution case in the connect-fence shutdown drain tests.
🧹 Nitpick comments (2)
src/shared/pty-consumer-session.test.ts (1)
254-302: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider consolidating the two overlapping-recovery tests.
The two tests differ only in the settlement call (
commitPublicationvsrollbackPublication) and the expecteddisplacedOwner.connectionId. Adescribe.eachorit.eachtable would remove the duplicated setup and make the contract difference explicit.Also consider asserting the state of the losing owner after the retry. In the commit case,
connection-1should already be gone. In the rollback case,connection-2should no longer hold the owner grant. Neither test checks that today.src/relay/relay-pty-consumer-owner-displacement.test.ts (1)
298-308: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe captured settlement can point at the wrong frame.
firstReconnectSettlementis reassigned on every write to the first reconnect client. Line 335 settles whichever write happened last. If the dispatcher writes a keepalive or any other frame to that client before line 335, the test settles the wrong frame and the assertions become misleading rather than failing clearly.Consider capturing only the first unsettled write, or asserting the frame identity before settling.
♻️ Capture the first pending settlement only
const firstReconnectClientId = dispatcher.attachClient( (data, settle) => { firstReconnectWrites.push(Buffer.from(data)) - firstReconnectSettlement = settle + firstReconnectSettlement ??= settle return true },Also applies to: 335-335
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f1236fc7-59aa-41b2-9558-befe1fee330e
📥 Commits
Reviewing files that changed from the base of the PR and between 460f3cf1c40af5b42f7b721ba97518ca47e8a78e and a5574a8bfa1d7b07b7d5e0c92dafc2a67879bc35.
📒 Files selected for processing (5)
src/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/relay/relay-pty-consumer-owner-displacement.test.tssrc/shared/pty-consumer-session.test.tssrc/shared/pty-consumer-session.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/shared/pty-consumer-session.ts
- src/main/ipc/ssh.test.ts
a5574a8 to
2a27589
Compare
SSH connections can reconnect with valid session proof after network loss or device sleep. When the incumbent owner is still half-open, allow the reconnecting client to displace it outright rather than wait for socket closure — a window that may never close. Retain displaced deliveries for the new owner to rotate. During app shutdown, drain SSH sessions without terminating recovery operations, and retry pending owner grants in case a replacement commits mid-drain.
Make QuitTeardownStartGate a shared singleton so SSH connects use the same shutdown fence as the main quit path. Track test-connection probes to ensure they complete before final teardown. Guard owner displacement to prevent stale owners from clearing recovery state claimed by newer owners.
Test was using tick-based Promise.resolve() loops which don't guarantee the async operation has started. Replace with signal-based synchronization that waits for the actual lease flush. Also add nullish-coalescing to error code check to prevent crashes if error is null or undefined.
2a27589 to
ca529a9
Compare
|
@coderabbitai Fixing. Will be in the next commit |
|
Tip For best results, initiate chat on the files or code changes.
You are interacting with an AI system. |
When a connect is cancelled after its transport has opened, that cancelled attempt still owns the transport and must close it — otherwise it leaks. Add disconnectConnection() to close by identity (not by target ID) so a cancelled attempt closes only the transport it minted, without tearing down its replacement's live transport. Track priorConnection to detect whether this attempt opened a new transport or reused an existing one, and close only on abandonment if this attempt owns the session.
When an owner reconnects with a new proof while an old one is still live, the old proof is now fenced with SUPERSEDED_ERROR instead of retrying indefinitely. The relay also closes stale transports to signal that their recovery generation has been overtaken by a newer one. This ensures overlapping reconnect scenarios complete with the newest proof rather than getting blocked by stale recovery attempts.
When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS can recycle those fds (0 and 1) for new sockets or files. If Node still treats process.stdin/stdout as those numbers, subsequent operations corrupt socket clients and trigger shutdown errors. Re-pin the fds by opening /dev/null to keep them occupied and prevent recycling.
* fix(ssh): handle owner displacement and graceful shutdown SSH connections can reconnect with valid session proof after network loss or device sleep. When the incumbent owner is still half-open, allow the reconnecting client to displace it outright rather than wait for socket closure — a window that may never close. Retain displaced deliveries for the new owner to rotate. During app shutdown, drain SSH sessions without terminating recovery operations, and retry pending owner grants in case a replacement commits mid-drain. * fix(ssh): handle owner displacement and graceful shutdown Make QuitTeardownStartGate a shared singleton so SSH connects use the same shutdown fence as the main quit path. Track test-connection probes to ensure they complete before final teardown. Guard owner displacement to prevent stale owners from clearing recovery state claimed by newer owners. * fix(ssh): fix flaky test sync and add error code safety check Test was using tick-based Promise.resolve() loops which don't guarantee the async operation has started. Replace with signal-based synchronization that waits for the actual lease flush. Also add nullish-coalescing to error code check to prevent crashes if error is null or undefined. * fix(ssh): fence reset transport opens during shutdown * fix(ssh): keep recovery leases stable across reconnects * fix(ssh): close transports owned by cancelled connect attempts When a connect is cancelled after its transport has opened, that cancelled attempt still owns the transport and must close it — otherwise it leaks. Add disconnectConnection() to close by identity (not by target ID) so a cancelled attempt closes only the transport it minted, without tearing down its replacement's live transport. Track priorConnection to detect whether this attempt opened a new transport or reused an existing one, and close only on abandonment if this attempt owns the session. * fix(ssh): fence old owner proofs and close superseded transports When an owner reconnects with a new proof while an old one is still live, the old proof is now fenced with SUPERSEDED_ERROR instead of retrying indefinitely. The relay also closes stale transports to signal that their recovery generation has been overtaken by a newer one. This ensures overlapping reconnect scenarios complete with the newest proof rather than getting blocked by stale recovery attempts. * fix(relay): re-pin stdin/stdout fds after closing to prevent recycling When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS can recycle those fds (0 and 1) for new sockets or files. If Node still treats process.stdin/stdout as those numbers, subsequent operations corrupt socket clients and trigger shutdown errors. Re-pin the fds by opening /dev/null to keep them occupied and prevent recycling.
…2367) * fix(ssh): handle owner displacement and graceful shutdown SSH connections can reconnect with valid session proof after network loss or device sleep. When the incumbent owner is still half-open, allow the reconnecting client to displace it outright rather than wait for socket closure — a window that may never close. Retain displaced deliveries for the new owner to rotate. During app shutdown, drain SSH sessions without terminating recovery operations, and retry pending owner grants in case a replacement commits mid-drain. * fix(ssh): handle owner displacement and graceful shutdown Make QuitTeardownStartGate a shared singleton so SSH connects use the same shutdown fence as the main quit path. Track test-connection probes to ensure they complete before final teardown. Guard owner displacement to prevent stale owners from clearing recovery state claimed by newer owners. * fix(ssh): fix flaky test sync and add error code safety check Test was using tick-based Promise.resolve() loops which don't guarantee the async operation has started. Replace with signal-based synchronization that waits for the actual lease flush. Also add nullish-coalescing to error code check to prevent crashes if error is null or undefined. * fix(ssh): fence reset transport opens during shutdown * fix(ssh): keep recovery leases stable across reconnects * fix(ssh): close transports owned by cancelled connect attempts When a connect is cancelled after its transport has opened, that cancelled attempt still owns the transport and must close it — otherwise it leaks. Add disconnectConnection() to close by identity (not by target ID) so a cancelled attempt closes only the transport it minted, without tearing down its replacement's live transport. Track priorConnection to detect whether this attempt opened a new transport or reused an existing one, and close only on abandonment if this attempt owns the session. * fix(ssh): fence old owner proofs and close superseded transports When an owner reconnects with a new proof while an old one is still live, the old proof is now fenced with SUPERSEDED_ERROR instead of retrying indefinitely. The relay also closes stale transports to signal that their recovery generation has been overtaken by a newer one. This ensures overlapping reconnect scenarios complete with the newest proof rather than getting blocked by stale recovery attempts. * fix(relay): re-pin stdin/stdout fds after closing to prevent recycling When the relay closes stdin/stdout to signal EOF to the SSH peer, the OS can recycle those fds (0 and 1) for new sockets or files. If Node still treats process.stdin/stdout as those numbers, subsequent operations corrupt socket clients and trigger shutdown errors. Re-pin the fds by opening /dev/null to keep them occupied and prevent recycling.
Summary
Fix SSH reconnect lockouts by allowing a reconnect with valid logical-owner proof to displace a half-open incumbent, while serializing overlapping owner publications behind a bounded retry. Also fence reset-created transports once committed app shutdown has started.
What changed
ownerLeasestable for the lifetime of one logical ownership claim.ownerGenerationas the per-admission delivery fencing epoch.-32042retry while one owner response is settling.ssh:resetRelayopens a replacement transport.Reliability contract
agent-session.provider-ownership): one published SSH PTY owner generation has write authority at a time; reconnecting the same logical owner cannot be permanently rejected merely because another grant publication is settling.agent-session.provider-ownershiptracks the single-owner authority contract;terminal-performance.output-backpressure-budgetcovers the SSH relay response-settlement, generation-fencing, and reconnect paths. Both gates remain experimental/partial.Verification