From b0c6a3b30fc046c92d8c84c88c594f25fa4b38b1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 17:24:31 -0700 Subject: [PATCH 01/37] test(remote): reproduce PTY hub start wedge --- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index b7c1ba8ad11f..a8453740b16d 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -100,6 +100,92 @@ func TestAttachRPCSurfacesPTYAllocationFailure(t *testing.T) { } } +func TestAttachRPCStalledSessionStartDoesNotBlockHealthyReattach(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + const healthySessionID = "healthy-session" + if _, _, _, err := hub.attachRPC( + context.Background(), + healthySessionID, + "initial-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ); err != nil { + t.Fatalf("start healthy session: %v", err) + } + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + stalledResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + "stalled-session", + "stalled-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + stalledResult <- err + }() + + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("stalled session never attempted PTY allocation") + } + + healthyResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + healthySessionID, + "reattachment", + 80, + 24, + "", + "", + true, + false, + ) + healthyResult <- err + }() + + select { + case err := <-healthyResult: + if err != nil { + close(releaseStart) + <-stalledResult + t.Fatalf("reattach healthy session: %v", err) + } + case <-time.After(time.Second): + close(releaseStart) + <-stalledResult + <-healthyResult + t.Fatal("healthy reattach blocked behind another session's stalled PTY allocation") + } + + close(releaseStart) + if err := <-stalledResult; err != nil { + t.Fatalf("finish formerly stalled session start: %v", err) + } +} + func TestServeWSRequiresExplicitLeaseFile(t *testing.T) { var stderr bytes.Buffer code := run([]string{"serve", "--ws", "--listen", "127.0.0.1:0"}, strings.NewReader(""), &bytes.Buffer{}, &stderr) From 9de72b5f161cb4dd16bcd5d752a22ce3a7854176 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 17:31:44 -0700 Subject: [PATCH 02/37] fix(remote): isolate persistent PTY session startup --- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 116 ++++++++++-- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 174 +++++++++++++++++- 2 files changed, 268 insertions(+), 22 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 52e9808e0dab..052fd939ec45 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -93,6 +93,7 @@ var ( errWSLeaseMissing = errors.New("attach lease missing") errWSLeaseExpired = errors.New("attach lease expired") errWSLeaseForbidden = errors.New("attach lease rejected") + errWSPTYHubClosed = errors.New("PTY hub is closed") wsLeaseMu sync.Mutex ) @@ -197,9 +198,20 @@ type wsPTYSession struct { terminateOnce sync.Once } +type wsPTYSessionStart struct { + done chan struct{} + err error +} + type wsPTYHub struct { - mu sync.Mutex - sessions map[wsPTYSessionKey]*wsPTYSession + mu sync.Mutex + sessions map[wsPTYSessionKey]*wsPTYSession + // startingSessions reserves a session key while PTY allocation and process + // startup run without mu. Callers for the same key join that start; callers + // for healthy or unrelated sessions never wait behind it. + startingSessions map[wsPTYSessionKey]*wsPTYSessionStart + closed bool + closedCh chan struct{} nextAttachmentID uint64 nextAnonymousID uint64 shell string @@ -226,12 +238,14 @@ func newWebSocketPTYHub(cfg wsPTYServerConfig, stderr io.Writer) *wsPTYHub { idleTTL = defaultWebSocketSessionIdleTTL } return &wsPTYHub{ - sessions: map[wsPTYSessionKey]*wsPTYSession{}, - shell: strings.TrimSpace(cfg.Shell), - stderr: stderr, - scrollbackLimit: limit, - sessionIdleTTL: idleTTL, - openPTY: pty.Open, + sessions: map[wsPTYSessionKey]*wsPTYSession{}, + startingSessions: map[wsPTYSessionKey]*wsPTYSessionStart{}, + closedCh: make(chan struct{}), + shell: strings.TrimSpace(cfg.Shell), + stderr: stderr, + scrollbackLimit: limit, + sessionIdleTTL: idleTTL, + openPTY: pty.Open, } } @@ -821,25 +835,82 @@ func (h *wsPTYHub) prepareAttachment( inputSeqAck bool, ) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { h.mu.Lock() - + if h.closed { + h.mu.Unlock() + return nil, nil, nil, errWSPTYHubClosed + } sessionKey := persistentPTYSessionKey(sessionID) if !persistent { sessionKey = anonymousPTYSessionKey(sessionID, h.nextAnonymousID) h.nextAnonymousID++ } - session := h.sessions[sessionKey] - if session == nil || session.closed { + h.mu.Unlock() + + var session *wsPTYSession + for { + h.mu.Lock() + if h.closed { + h.mu.Unlock() + return nil, nil, nil, errWSPTYHubClosed + } + session = h.sessions[sessionKey] + if session != nil && !session.closed { + break + } + if start := h.startingSessions[sessionKey]; start != nil { + closedCh := h.closedCh + h.mu.Unlock() + select { + case <-start.done: + if start.err != nil { + return nil, nil, nil, start.err + } + case <-closedCh: + return nil, nil, nil, errWSPTYHubClosed + case <-ctx.Done(): + return nil, nil, nil, ctx.Err() + } + continue + } if requireExisting { h.mu.Unlock() return nil, nil, nil, fmt.Errorf("persistent PTY session %q is not running", sessionID) } - var err error - session, err = h.startSessionLocked(sessionKey, sessionID, cols, rows, command) - if err != nil { - h.mu.Unlock() - return nil, nil, nil, err + + start := &wsPTYSessionStart{done: make(chan struct{})} + h.startingSessions[sessionKey] = start + h.mu.Unlock() + + startedSession, startErr := h.startSession(sessionKey, sessionID, cols, rows, command) + discardStartedSession := false + + h.mu.Lock() + delete(h.startingSessions, sessionKey) + if startErr == nil { + switch existingSession := h.sessions[sessionKey]; { + case h.closed: + startErr = errWSPTYHubClosed + discardStartedSession = true + case existingSession != nil && !existingSession.closed: + discardStartedSession = true + default: + h.sessions[sessionKey] = startedSession + } + } + start.err = startErr + close(start.done) + h.mu.Unlock() + + if startedSession != nil { + h.runSession(startedSession) + if discardStartedSession { + startedSession.terminateProcesses() + startedSession.closePTYFiles() + } + } + if startErr != nil { + return nil, nil, nil, startErr } - h.sessions[sessionKey] = session } if attachmentID == "" { @@ -906,7 +977,7 @@ func (h *wsPTYHub) prepareAttachment( return attachment, attachmentCtx, sessionDone, nil } -func (h *wsPTYHub) startSessionLocked(sessionKey wsPTYSessionKey, sessionID string, cols int, rows int, command string) (*wsPTYSession, error) { +func (h *wsPTYHub) startSession(sessionKey wsPTYSessionKey, sessionID string, cols int, rows int, command string) (*wsPTYSession, error) { shellPath := resolvePTYShell(h.shell) trimmedCommand := strings.TrimSpace(command) var cmd *exec.Cmd @@ -968,10 +1039,13 @@ func (h *wsPTYHub) startSessionLocked(sessionKey wsPTYSessionKey, sessionID stri input: make(chan wsPTYInputChunk, defaultPTYInputQueueCap), done: make(chan struct{}), } + return session, nil +} + +func (h *wsPTYHub) runSession(session *wsPTYSession) { go h.waitSessionProcess(session) go h.pumpSession(session) go h.writeInputLoop(session) - return session, nil } func persistentPTYCommand(command *exec.Cmd) (*exec.Cmd, error) { @@ -1200,6 +1274,10 @@ func (h *wsPTYHub) closeSessionForAttachment(attachment *wsPTYAttachment) { func (h *wsPTYHub) closeAll() { h.mu.Lock() + if !h.closed { + h.closed = true + close(h.closedCh) + } sessions := make([]*wsPTYSession, 0, len(h.sessions)) for id, session := range h.sessions { delete(h.sessions, id) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index a8453740b16d..1b1596d5ffb8 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -19,6 +19,7 @@ import ( "runtime" "strconv" "strings" + "sync/atomic" "syscall" "testing" "time" @@ -122,9 +123,12 @@ func TestAttachRPCStalledSessionStartDoesNotBlockHealthyReattach(t *testing.T) { openPTY := hub.openPTY startEntered := make(chan struct{}) releaseStart := make(chan struct{}) + var startCount atomic.Int32 hub.openPTY = func() (*os.File, *os.File, error) { - close(startEntered) - <-releaseStart + if startCount.Add(1) == 1 { + close(startEntered) + <-releaseStart + } return openPTY() } @@ -180,12 +184,175 @@ func TestAttachRPCStalledSessionStartDoesNotBlockHealthyReattach(t *testing.T) { t.Fatal("healthy reattach blocked behind another session's stalled PTY allocation") } + independentResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + "independent-session", + "independent-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + independentResult <- err + }() + select { + case err := <-independentResult: + if err != nil { + close(releaseStart) + <-stalledResult + t.Fatalf("start independent session: %v", err) + } + case <-time.After(time.Second): + close(releaseStart) + <-stalledResult + <-independentResult + t.Fatal("independent session start blocked behind another session's stalled PTY allocation") + } + close(releaseStart) if err := <-stalledResult; err != nil { t.Fatalf("finish formerly stalled session start: %v", err) } } +func TestAttachRPCConcurrentSameSessionStartsOnce(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}, 2) + releaseStart := make(chan struct{}) + var startCount atomic.Int32 + hub.openPTY = func() (*os.File, *os.File, error) { + startCount.Add(1) + startEntered <- struct{}{} + <-releaseStart + return openPTY() + } + + attach := func(attachmentID string) <-chan error { + result := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + "shared-session", + attachmentID, + 80, + 24, + "sleep 30", + "", + false, + false, + ) + result <- err + }() + return result + } + + firstResult := attach("first-attachment") + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("first attach never attempted PTY allocation") + } + secondResult := attach("second-attachment") + close(releaseStart) + + if err := <-firstResult; err != nil { + t.Fatalf("first attach: %v", err) + } + if err := <-secondResult; err != nil { + t.Fatalf("second attach: %v", err) + } + if got := startCount.Load(); got != 1 { + t.Fatalf("PTY start count = %d, want 1 for concurrent attaches to one session", got) + } + + hub.mu.Lock() + session := hub.sessions[persistentPTYSessionKey("shared-session")] + pendingStarts := len(hub.startingSessions) + attachmentCount := 0 + if session != nil { + attachmentCount = len(session.attachments) + } + hub.mu.Unlock() + if pendingStarts != 0 { + t.Fatalf("pending session starts = %d, want 0 after successful start", pendingStarts) + } + if attachmentCount != 2 { + t.Fatalf("shared session attachments = %d, want 2", attachmentCount) + } +} + +func TestCloseAllDoesNotWaitForStalledSessionStart(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + attachResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + "closing-session", + "closing-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + attachResult <- err + }() + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("session start never attempted PTY allocation") + } + + closeDone := make(chan struct{}) + go func() { + hub.closeAll() + close(closeDone) + }() + select { + case <-closeDone: + case <-time.After(time.Second): + close(releaseStart) + <-attachResult + t.Fatal("closeAll blocked behind a stalled session start") + } + + close(releaseStart) + err := <-attachResult + if !errors.Is(err, errWSPTYHubClosed) { + t.Fatalf("attach after closeAll error = %v, want PTY hub closed", err) + } + + hub.mu.Lock() + sessionCount := len(hub.sessions) + pendingStarts := len(hub.startingSessions) + hub.mu.Unlock() + if sessionCount != 0 { + t.Fatalf("published sessions after closeAll = %d, want 0", sessionCount) + } + if pendingStarts != 0 { + t.Fatalf("pending session starts after completion = %d, want 0", pendingStarts) + } +} + func TestServeWSRequiresExplicitLeaseFile(t *testing.T) { var stderr bytes.Buffer code := run([]string{"serve", "--ws", "--listen", "127.0.0.1:0"}, strings.NewReader(""), &bytes.Buffer{}, &stderr) @@ -549,7 +716,7 @@ func TestWebSocketPTYPersistentInteractiveBashChildSurvivesHangup(t *testing.T) hub.mu.Lock() defer hub.mu.Unlock() startupCommand := `/bin/true; if [ -n "${CMUX_PERSISTENT_PTY_EXEC_HELPER:-}" ]; then exec "$CMUX_PERSISTENT_PTY_EXEC_HELPER" --internal-persistent-pty-exec /bin/bash /bin/bash --noprofile --norc -i; fi; exec /bin/bash --noprofile --norc -i` - session, err := hub.startSessionLocked( + session, err := hub.startSession( persistentPTYSessionKey(sessionID), sessionID, 80, @@ -560,6 +727,7 @@ func TestWebSocketPTYPersistentInteractiveBashChildSurvivesHangup(t *testing.T) return err } hub.sessions[session.key] = session + hub.runSession(session) return nil }(); err != nil { t.Fatalf("start persistent interactive Bash session: %v", err) From 6aad22a9ea26b69fd608f87fed1790545fe8c69b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 17:30:25 -0700 Subject: [PATCH 03/37] test: bound zero-progress SSH PTY reattach churn --- cmux.xcodeproj/project.pbxproj | 4 + .../SSHPTYAttachNoProgressRetryTests.swift | 114 ++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 cmuxTests/SSHPTYAttachNoProgressRetryTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c21a1e70623f..df2abace74cd 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1930,6 +1930,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C77070000000000000000002 /* SSHPTYAttachExitCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000001 /* SSHPTYAttachExitCode.swift */; }; C77070000000000000000003 /* SSHPTYAttachExitCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000001 /* SSHPTYAttachExitCode.swift */; }; C77070000000000000000006 /* SSHPTYAttachExitCodeClassifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000007 /* SSHPTYAttachExitCodeClassifierTests.swift */; }; + A87500010000000000000001 /* SSHPTYAttachNoProgressRetryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500010000000000000002 /* SSHPTYAttachNoProgressRetryTests.swift */; }; 6E8B6A69A468EF938B9AD8C2 /* SSHPTYAttachReconnectInputFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */; }; B816E948EC5E42AF967648AC /* SSHPTYAttachReconnectInputFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */; }; E60610200000000000000002 /* SSHPTYAttachReconnectInputFilterControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60610200000000000000001 /* SSHPTYAttachReconnectInputFilterControl.swift */; }; @@ -4332,6 +4333,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 797800050000000000000002 /* SSHPersistentPTYRetryLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPersistentPTYRetryLifecycleTests.swift; sourceTree = ""; }; C77070000000000000000001 /* SSHPTYAttachExitCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachExitCode.swift; sourceTree = ""; }; C77070000000000000000007 /* SSHPTYAttachExitCodeClassifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachExitCodeClassifierTests.swift; sourceTree = ""; }; + A87500010000000000000002 /* SSHPTYAttachNoProgressRetryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachNoProgressRetryTests.swift; sourceTree = ""; }; 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilter.swift; sourceTree = ""; }; E60610200000000000000001 /* SSHPTYAttachReconnectInputFilterControl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterControl.swift; sourceTree = ""; }; E60610400000000000000001 /* SSHPTYAttachReconnectInputFilterPumpIO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterPumpIO.swift; sourceTree = ""; }; @@ -6877,6 +6879,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 4F73A5C0BB93507E18261385 /* SSHStartupManualReconnectTests.swift */, 797800040000000000000002 /* SSHDeepSleepReattachTests.swift */, 8410A0010000000000000001 /* SSHForegroundAuthenticationMarkerCleanupTests.swift */, + A87500010000000000000002 /* SSHPTYAttachNoProgressRetryTests.swift */, 797800050000000000000002 /* SSHPersistentPTYRetryLifecycleTests.swift */, F6724603A1B2C3D4E5F67246 /* RemoteTmuxHostRemoteCommandOverrideTests.swift */, F6724601A1B2C3D4E5F67246 /* SSHConfiguredRemoteCommandHostTests.swift */, @@ -10067,6 +10070,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 797800050000000000000001 /* SSHPersistentPTYRetryLifecycleTests.swift in Sources */, C77070000000000000000003 /* SSHPTYAttachExitCode.swift in Sources */, C77070000000000000000006 /* SSHPTYAttachExitCodeClassifierTests.swift in Sources */, + A87500010000000000000001 /* SSHPTYAttachNoProgressRetryTests.swift in Sources */, 6E8B6A69A468EF938B9AD8C2 /* SSHPTYAttachReconnectInputFilter.swift in Sources */, E60610200000000000000003 /* SSHPTYAttachReconnectInputFilterControl.swift in Sources */, E60610400000000000000003 /* SSHPTYAttachReconnectInputFilterPumpIO.swift in Sources */, diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift new file mode 100644 index 000000000000..e824784aeb75 --- /dev/null +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -0,0 +1,114 @@ +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite(.serialized) +struct SSHPTYAttachNoProgressRetryTests { + private struct ProcessResult { + let status: Int32 + let stderr: String + let timedOut: Bool + } + + @Test("Repeated zero-progress bridge closures stop after the health budget") + func repeatedZeroProgressClosuresStop() throws { + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-ssh-pty-no-progress-\(UUID().uuidString)", isDirectory: true) + let fakeCLI = root.appendingPathComponent("cmux") + let fakeSleep = root.appendingPathComponent("sleep") + let attemptFile = root.appendingPathComponent("attempts") + let policyLog = root.appendingPathComponent("policy-log") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + try Self.writeShellFile(at: fakeCLI, lines: [ + "#!/bin/sh", + "case \" $* \" in", + " *\" ssh-pty-attach \"*)", + " count=$(cat \"$CMUX_TEST_ATTEMPT_FILE\" 2>/dev/null || printf 0)", + " count=$((count + 1))", + " printf '%s' \"$count\" > \"$CMUX_TEST_ATTEMPT_FILE\"", + " printf '%s/%s\\n' \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY:-missing}\" \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT:-missing}\" >> \"$CMUX_TEST_POLICY_LOG\"", + " exit 252", + " ;;", + " *) exit 0 ;;", + "esac", + ]) + try Self.writeShellFile(at: fakeSleep, lines: ["#!/bin/sh", "exit 0"]) + for executable in [fakeCLI, fakeSleep] { + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + } + + var environment = ProcessInfo.processInfo.environment + environment["PATH"] = "\(root.path):\(environment["PATH"] ?? "/usr/bin:/bin")" + environment["CMUX_BUNDLED_CLI_PATH"] = fakeCLI.path + environment["CMUX_SOCKET_PATH"] = "/tmp/cmux-debug-test.sock" + environment["CMUX_WORKSPACE_ID"] = "11111111-1111-1111-1111-111111111111" + environment["CMUX_SURFACE_ID"] = "22222222-2222-2222-2222-222222222222" + environment["CMUX_TEST_ATTEMPT_FILE"] = attemptFile.path + environment["CMUX_TEST_POLICY_LOG"] = policyLog.path + environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = "3" + environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" + environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" + + let result = Self.run( + command: SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), + environment: environment + ) + + #expect(!result.timedOut, Comment(rawValue: result.stderr)) + #expect(result.status == 1, Comment(rawValue: result.stderr)) + #expect(try String(contentsOf: attemptFile, encoding: .utf8) == "3") + #expect( + try String(contentsOf: policyLog, encoding: .utf8) == """ + 0/3 + 1/3 + 2/3 + + """ + ) + #expect(result.stderr.contains("made no progress after 3 attempts"), Comment(rawValue: result.stderr)) + } + + private static func writeShellFile(at url: URL, lines: [String]) throws { + try (lines.joined(separator: "\n") + "\n").write(to: url, atomically: true, encoding: .utf8) + } + + private static func run(command: String, environment: [String: String]) -> ProcessResult { + let process = Process() + let stderrPipe = Pipe() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = ["-c", command] + process.environment = environment + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = stderrPipe + do { + try process.run() + } catch { + return ProcessResult(status: -1, stderr: String(describing: error), timedOut: false) + } + + let exited = DispatchSemaphore(value: 0) + DispatchQueue.global(qos: .userInitiated).async { + process.waitUntilExit() + exited.signal() + } + let timedOut = exited.wait(timeout: .now() + 5) == .timedOut + if timedOut { + process.terminate() + _ = exited.wait(timeout: .now() + 1) + } + let stderr = String( + data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), + encoding: .utf8 + ) ?? "" + return ProcessResult(status: process.terminationStatus, stderr: stderr, timedOut: timedOut) + } +} From 7cc29bbee7b4cfd43972db1a88cbf87960f97dfb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 18:09:28 -0700 Subject: [PATCH 04/37] fix: stop zero-progress SSH PTY attach loops --- CLI/CMUXCLI+SSHPTYAttachBridge.swift | 54 ++++++++++- CLI/SSHPTYAttachExitCode.swift | 8 +- CLI/SSHPTYAttachRetryLoop.swift | 78 ++++++++++++++++ CLI/cmux.swift | 79 +++++++++------- Resources/Localizable.xcstrings | 51 ++++++++++ .../SSHPTYAttachStartupCommandBuilder.swift | 40 +------- cmux.xcodeproj/project.pbxproj | 6 ++ ...ifyProcessIntegrationRegressionTests.swift | 25 ++++- .../SSHPTYAttachNoProgressRetryTests.swift | 92 +++++++++++++++++++ 9 files changed, 351 insertions(+), 82 deletions(-) create mode 100644 CLI/SSHPTYAttachRetryLoop.swift diff --git a/CLI/CMUXCLI+SSHPTYAttachBridge.swift b/CLI/CMUXCLI+SSHPTYAttachBridge.swift index 72de0090fac0..03acc0834421 100644 --- a/CLI/CMUXCLI+SSHPTYAttachBridge.swift +++ b/CLI/CMUXCLI+SSHPTYAttachBridge.swift @@ -8,7 +8,7 @@ extension CLIError { } extension CMUXCLI { - /// True when a persistent attach wrapper owns retrying a 254|255 failure. + /// True when a persistent attach wrapper has another general retry available. /// Persistent wrappers export `CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=1`; /// direct invocations leave it unset, so failures there always clean up. func sshPTYAttachWrapperRetryPending() -> Bool { @@ -16,6 +16,42 @@ extension CMUXCLI { .trimmingCharacters(in: .whitespacesAndNewlines) == "1" } + func sshPTYAttachWrapperWillRetry(_ exitCode: SSHPTYAttachExitCode) -> Bool { + guard sshPTYAttachWrapperRetryPending() else { return false } + if exitCode == .bridgeClosedWithoutProgress { + let environment = ProcessInfo.processInfo.environment + guard let retry = Int(environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] ?? ""), + retry >= 0, + let limit = Int(environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] ?? ""), + limit > 0 else { + return false + } + return SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining( + currentRetry: retry, + limit: limit + ) + } + return exitCode.isWrapperRetryable + } + + func sshPTYAttachBridgeClosedExitCode( + receivedOutput: Bool, + readyUptime: TimeInterval + ) -> SSHPTYAttachExitCode { + let environment = ProcessInfo.processInfo.environment + let bridgeUptime = ProcessInfo.processInfo.systemUptime - readyUptime + guard sshPTYAttachWrapperRetryPending(), + environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] != nil, + environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] != nil, + SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + receivedOutput: receivedOutput, + bridgeUptime: bridgeUptime + ) else { + return .bridgeClosedSessionRunning + } + return .bridgeClosedWithoutProgress + } + func cleanupFailedSSHPTYAttach( client: SocketClient, workspaceId: String, @@ -93,7 +129,8 @@ extension CMUXCLI { surfaceID: String?, sessionID: String, lifecycleID: String, - intentionalOnly: Bool + intentionalOnly: Bool, + sessionRunningExitCode: SSHPTYAttachExitCode = .bridgeClosedSessionRunning ) throws -> Bool { let reconciliationFailure = "ssh-pty-attach: bridge closed before remote PTY exit could be confirmed" let response: [String: Any] @@ -144,9 +181,18 @@ extension CMUXCLI { (($0["session_id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "") == sessionID } if !intentionalCleanup, sessionStillRunning { + let message: String + if sessionRunningExitCode == .bridgeClosedWithoutProgress { + message = String( + localized: "cli.sshPtyAttach.bridgeClosedWithoutProgress", + defaultValue: "ssh-pty-attach: bridge closed without receiving output while the remote PTY session is still running" + ) + } else { + message = "ssh-pty-attach: bridge closed while remote PTY session is still running" + } throw CLIError( - message: "ssh-pty-attach: bridge closed while remote PTY session is still running", - exitCode: SSHPTYAttachExitCode.bridgeClosedSessionRunning + message: message, + exitCode: sessionRunningExitCode ) } guard let surfaceID else { return true } diff --git a/CLI/SSHPTYAttachExitCode.swift b/CLI/SSHPTYAttachExitCode.swift index e79e043f4f5a..f86e84da29f2 100644 --- a/CLI/SSHPTYAttachExitCode.swift +++ b/CLI/SSHPTYAttachExitCode.swift @@ -2,13 +2,13 @@ import Foundation /// Owns ssh-pty-attach exit-code semantics. /// -/// Exit codes 254 and 255 are the only retryable statuses recognized by the -/// embedded wrapper loops in `SSHPTYAttachStartupCommandBuilder.retryingAttachLines` -/// and `CMUXCLI.sshPTYAttachRetryLoopLines`; keep those shell contracts in sync -/// with this taxonomy. The classifier patterns mirror +/// Exit codes 252, 254, and 255 are handled by `SSHPTYAttachRetryLoop`. +/// Status 252 has its own bounded consecutive-failure budget; 254 and 255 use +/// the general reconnect budget. The classifier patterns mirror /// `userFacingRemotePTYErrorMessage` in `CLI/CMUXCLI+RemotePTYErrors.swift`. enum SSHPTYAttachExitCode: Int32 { case fatal = 1 + case bridgeClosedWithoutProgress = 252 case sessionNotFound = 253 case bridgeClosedSessionRunning = 254 case retryableTransient = 255 diff --git a/CLI/SSHPTYAttachRetryLoop.swift b/CLI/SSHPTYAttachRetryLoop.swift new file mode 100644 index 000000000000..b624bc0a69a5 --- /dev/null +++ b/CLI/SSHPTYAttachRetryLoop.swift @@ -0,0 +1,78 @@ +import Foundation + +enum SSHPTYAttachRetryLoop { + private static let healthyBridgeUptime: TimeInterval = 30 + + static func bridgeClosureMadeNoProgress( + receivedOutput: Bool, + bridgeUptime: TimeInterval + ) -> Bool { + // A bridge that remains connected through an ordinary idle interval is + // healthy even when the remote shell has not emitted output. + !receivedOutput && bridgeUptime >= 0 && bridgeUptime < healthyBridgeUptime + } + + static func hasNoProgressRetryRemaining(currentRetry: Int, limit: Int) -> Bool { + currentRetry >= 0 && limit > 0 && currentRetry + 1 < limit + } + + static func lines(command: String, reauthenticates: Bool) -> [String] { + let reauthenticate = reauthenticates ? "cmux_ssh_attach_reauth_required=1" : ":" + let reattachingFormat = shellQuote( + String( + localized: "cli.sshPtyAttach.bridgeClosedReattaching", + defaultValue: "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." + ) + ) + let noProgressFormat = shellQuote( + String( + localized: "cli.sshPtyAttach.noProgressRetryLimitReached", + defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." + ) + ) + let noProgressStatus = SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue + + return [ + "cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"", + "case \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac", + "cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"", + "case \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac", + "cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"", + "case \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", + "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", + "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", + "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", + "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", + "cmux_ssh_attach_no_progress_retry=0", + "cmux_ssh_attach_retry=0", + "cmux_ssh_attach_reauth_required=0", + "while :; do", + " if [ \"$cmux_ssh_attach_reauth_required\" -eq 1 ]; then", + " cmux_ssh_attach_foreground_auth", + " cmux_ssh_attach_status=$?", + " if [ \"$cmux_ssh_attach_status\" -eq 0 ]; then cmux_ssh_attach_reauth_required=0; elif [ \"$cmux_ssh_attach_status\" -ne 255 ]; then exit \"$cmux_ssh_attach_status\"; fi", + " fi", + " if [ \"$cmux_ssh_attach_reauth_required\" -eq 0 ]; then", + " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi", + " CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY=\"$cmux_ssh_attach_no_progress_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT=\"$cmux_ssh_attach_no_progress_limit\" \(command)", + " cmux_ssh_attach_status=$?", + " case \"$cmux_ssh_attach_status\" in", + " \(noProgressStatus)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(noProgressFormat) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi ;;", + " 254) cmux_ssh_attach_no_progress_retry=0; cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;;", + " 255) cmux_ssh_attach_no_progress_retry=0; \(reauthenticate) ;;", + " *) exit \"$cmux_ssh_attach_status\" ;;", + " esac", + " fi", + " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi", + " cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))", + " if [ -t 2 ]; then printf '\\n\\033[33m%s\\033[0m\\n' \"$(printf \(reattachingFormat) \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\")\" >&2 || true; fi", + " if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi", + " if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi", + "done", + ] + } + + private static func shellQuote(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'" + } +} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 13c7c3bd4a6a..e94c9d471c98 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -12422,31 +12422,13 @@ struct CMUXCLI { "trap 'cmux_ssh_attach_signal_exit 129' HUP", "trap 'cmux_ssh_attach_signal_exit 130' INT", "trap 'cmux_ssh_attach_signal_exit 143' TERM", - ] + sshPTYAttachRetryLoopLines(command: attachCommand)).joined(separator: "\n") + ] + SSHPTYAttachRetryLoop.lines( + command: attachCommand, + reauthenticates: false + )).joined(separator: "\n") return "/bin/sh -c \(shellQuote(script))" } - private func sshPTYAttachRetryLoopLines(command: String) -> [String] { - // Retryable 254|255 is owned by SSHPTYAttachExitCode; keep in sync with SSHPTYAttachStartupCommandBuilder.retryingAttachLines. - [ - "cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"\ncase \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac", - "cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"\ncase \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac", - "cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"\ncase \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", - "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", - "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", - "cmux_ssh_attach_retry=0", - "while :; do", - " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi\n CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" \(command)", - " cmux_ssh_attach_status=$?", - " case \"$cmux_ssh_attach_status\" in 254) cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;; 255) ;; *) exit \"$cmux_ssh_attach_status\" ;; esac\n if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi", - " cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))", - " if [ -t 2 ]; then printf '\\n\\033[33m[cmux] remote PTY bridge closed; reattaching (attempt %s/%s).\\033[0m\\n' \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\" >&2 || true; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi", - "done", - ] - } - private func sshSessionTargetParams( commandName: String, workspaceOpt: String?, @@ -12514,18 +12496,28 @@ struct CMUXCLI { var bridgeReachedReady = false var sessionLostWillRespawn = false var wrapperWillRetrySameSurface = false + var noProgressRetryExhausted = false var attachFinished = false var attachmentToken = "" - func reconcileBridgeEnd(intentionalOnly: Bool) throws -> Bool { + func reconcileBridgeEnd( + intentionalOnly: Bool, + sessionRunningExitCode: SSHPTYAttachExitCode = .bridgeClosedSessionRunning + ) throws -> Bool { do { return try reconcileSSHPTYBridgeEnd( client: client, workspaceId: workspaceId, surfaceID: surfaceID, - sessionID: sessionID, lifecycleID: lifecycleID, intentionalOnly: intentionalOnly + sessionID: sessionID, + lifecycleID: lifecycleID, + intentionalOnly: intentionalOnly, + sessionRunningExitCode: sessionRunningExitCode ) } catch let error as CLIError { - if SSHPTYAttachExitCode(rawValue: error.exitCode)?.isWrapperRetryable == true, - sshPTYAttachWrapperRetryPending() { - wrapperWillRetrySameSurface = true + if let exitCode = SSHPTYAttachExitCode(rawValue: error.exitCode) { + if sshPTYAttachWrapperWillRetry(exitCode) { + wrapperWillRetrySameSurface = true + } else if exitCode == .bridgeClosedWithoutProgress { + noProgressRetryExhausted = true + } } throw error } @@ -12541,7 +12533,8 @@ struct CMUXCLI { attachmentID: attachmentID, attachmentToken: attachmentToken, retireLifecycle: !sessionLostWillRespawn && !wrapperWillRetrySameSurface, - clearLocalSurface: !bridgeReachedReady && !sessionLostWillRespawn + clearLocalSurface: (!bridgeReachedReady || noProgressRetryExhausted) + && !sessionLostWillRespawn && !wrapperWillRetrySameSurface ) } @@ -12579,7 +12572,7 @@ struct CMUXCLI { exitCode = SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure(String(describing: error)) } let closedGeneration = (error as? CLIError)?.v2Code == "pty_lifecycle_closed" - if !closedGeneration, exitCode.isWrapperRetryable, sshPTYAttachWrapperRetryPending() { + if !closedGeneration, sshPTYAttachWrapperWillRetry(exitCode) { wrapperWillRetrySameSurface = true } if closedGeneration { @@ -12618,6 +12611,7 @@ struct CMUXCLI { } var connectedFD: Int32? var bridgeHandshakeSize = Self.currentCLITerminalSize() + var bridgeReadyUptime: TimeInterval = 0 do { let host = (bridge["host"] as? String) ?? "127.0.0.1" guard let port = cliStrictInt(bridge["port"]), port > 0, port <= 65535 else { @@ -12641,15 +12635,18 @@ struct CMUXCLI { try Self.writeAll(fd: fd, data: handshakeData) attachmentToken = try readSSHPTYBridgeReady(fd: fd) bridgeReachedReady = true + bridgeReadyUptime = ProcessInfo.processInfo.systemUptime } catch { let sessionNotFound = requireExisting && (error as? CLIError)?.exitCode == SSHPTYAttachExitCode.sessionNotFound.rawValue if sessionNotFound { sessionLostWillRespawn = true } - let preReadyRetryable = (error as? CLIError) - .flatMap { SSHPTYAttachExitCode(rawValue: $0.exitCode) }?.isWrapperRetryable == true - if preReadyRetryable, sshPTYAttachWrapperRetryPending() { + let preReadyExitCode = (error as? CLIError) + .flatMap { SSHPTYAttachExitCode(rawValue: $0.exitCode) } + let preReadyRetryable = preReadyExitCode?.isWrapperRetryable == true + if let preReadyExitCode, + sshPTYAttachWrapperWillRetry(preReadyExitCode) { wrapperWillRetrySameSurface = true } if let connectedFD { Darwin.close(connectedFD) } @@ -12697,22 +12694,36 @@ struct CMUXCLI { throw CLIError(message: "ssh-pty-attach: bridge write failed") } var reconnectInputFilterStopRequested = false + var receivedOutput = false var outputBuffer = [UInt8](repeating: 0, count: 32768) while true { let count = Darwin.read(fd, &outputBuffer, outputBuffer.count) if count > 0 { + receivedOutput = true reconnectInputFilterControl?.stopFilteringBeforeFirstOutput(unlessAlreadyRequested: &reconnectInputFilterStopRequested) cliWriteStdout(Data(outputBuffer.prefix(count))) } else if count == 0 { resizeMonitor.cancel() - _ = try reconcileBridgeEnd(intentionalOnly: false) + _ = try reconcileBridgeEnd( + intentionalOnly: false, + sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode( + receivedOutput: receivedOutput, + readyUptime: bridgeReadyUptime + ) + ) attachFinished = true return } else if errno != EINTR { if sshPTYBridgeReadErrorIsEOF(errno) { resizeMonitor.cancel() - _ = try reconcileBridgeEnd(intentionalOnly: false) + _ = try reconcileBridgeEnd( + intentionalOnly: false, + sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode( + receivedOutput: receivedOutput, + readyUptime: bridgeReadyUptime + ) + ) attachFinished = true return } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 40590e122216..046cbfc37579 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -50463,6 +50463,57 @@ } } }, + "cli.sshPtyAttach.bridgeClosedReattaching": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "[cmux] リモート PTY ブリッジが閉じました。再接続しています(試行 %s/%s)。" + } + } + } + }, + "cli.sshPtyAttach.bridgeClosedWithoutProgress": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "ssh-pty-attach: bridge closed without receiving output while the remote PTY session is still running" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ssh-pty-attach: 出力を受信しないままブリッジが閉じましたが、リモート PTY セッションは引き続き実行中です" + } + } + } + }, + "cli.sshPtyAttach.noProgressRetryLimitReached": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "[cmux] リモート PTY ブリッジは %s 回試行しても進行しなかったため、再試行を停止します。" + } + } + } + }, "cli.sshPtyAttach.remoteSessionLostRespawn": { "extractionState": "manual", "localizations": { diff --git a/Sources/SSHPTYAttachStartupCommandBuilder.swift b/Sources/SSHPTYAttachStartupCommandBuilder.swift index 753998d2766d..0d19449b5688 100644 --- a/Sources/SSHPTYAttachStartupCommandBuilder.swift +++ b/Sources/SSHPTYAttachStartupCommandBuilder.swift @@ -49,7 +49,10 @@ enum SSHPTYAttachStartupCommandBuilder { " --command-b64 \(shellQuote(Data($0.utf8).base64EncodedString()))" } ?? "" let attachCommand = "\"$cmux_ssh_attach_cli\" --socket \"$CMUX_SOCKET_PATH\" ssh-pty-attach --wait\(requireExistingFlag) --workspace \"$CMUX_WORKSPACE_ID\" --session-id \"$cmux_ssh_attach_session_id\" --lifecycle-id \"$cmux_ssh_attach_lifecycle_id\" --attachment-id \"${CMUX_SURFACE_ID:-}\"\(commandB64Flag)" - lines += retryingAttachLines(command: attachCommand, reauthenticates: foregroundAuth != nil) + lines += SSHPTYAttachRetryLoop.lines( + command: attachCommand, + reauthenticates: foregroundAuth != nil + ) return "/bin/sh -c \(shellQuote(lines.joined(separator: "\n")))" } @@ -67,41 +70,6 @@ enum SSHPTYAttachStartupCommandBuilder { ) } - private static func retryingAttachLines(command: String, reauthenticates: Bool) -> [String] { - // Retryable 254|255 is owned by SSHPTYAttachExitCode in the CLI target; keep in sync with CMUXCLI.sshPTYAttachRetryLoopLines. - let reauthenticate = reauthenticates ? "cmux_ssh_attach_reauth_required=1" : ":" - return [ - "cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"", - "case \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac", - "cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"", - "case \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac", - "cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"", - "case \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", - "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", - "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", - "cmux_ssh_attach_retry=0", - "cmux_ssh_attach_reauth_required=0", - "while :; do", - " if [ \"$cmux_ssh_attach_reauth_required\" -eq 1 ]; then", - " cmux_ssh_attach_foreground_auth", - " cmux_ssh_attach_status=$?", - " if [ \"$cmux_ssh_attach_status\" -eq 0 ]; then cmux_ssh_attach_reauth_required=0; elif [ \"$cmux_ssh_attach_status\" -ne 255 ]; then exit \"$cmux_ssh_attach_status\"; fi", - " fi", - " if [ \"$cmux_ssh_attach_reauth_required\" -eq 0 ]; then", - " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi", - " CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" \(command)", - " cmux_ssh_attach_status=$?", - " case \"$cmux_ssh_attach_status\" in 254) cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;; 255) \(reauthenticate) ;; *) exit \"$cmux_ssh_attach_status\" ;; esac", - " fi", - " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi", - " cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))", - " if [ -t 2 ]; then printf '\\n\\033[33m[cmux] remote PTY bridge closed; reattaching (attempt %s/%s).\\033[0m\\n' \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\" >&2 || true; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi", - "done", - ] - } - private static func foregroundAuthLines(_ auth: ForegroundAuth) -> [String] { let sshCommand = sshForegroundAuthCommand(auth) let quotedToken = shellQuote(auth.token) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index df2abace74cd..9854db983a37 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1942,6 +1942,8 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources E60610300000000000000002 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */; }; E60610300000000000000003 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */; }; B6285B71BA6F82AF8F945E00 /* SSHPTYAttachReconnectInputFilterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C4AD348F196FBBEE52D53A7 /* SSHPTYAttachReconnectInputFilterTests.swift */; }; + A87500100000000000000001 /* SSHPTYAttachRetryLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */; }; + A87500100000000000000002 /* SSHPTYAttachRetryLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */; }; E30780000000000000000012 /* SSHPTYAttachStartupCommandBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30780000000000000000011 /* SSHPTYAttachStartupCommandBuilder.swift */; }; 6379A0046379A0046379A004 /* SSHPTYResizeMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6379A0036379A0036379A003 /* SSHPTYResizeMonitor.swift */; }; EF70B7123200D1FB6F03DB26 /* SSHStartupManualReconnectTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F73A5C0BB93507E18261385 /* SSHStartupManualReconnectTests.swift */; }; @@ -4340,6 +4342,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = E60610100000000000000001 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterSequenceMatch.swift; sourceTree = ""; }; E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterState.swift; sourceTree = ""; }; 0C4AD348F196FBBEE52D53A7 /* SSHPTYAttachReconnectInputFilterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterTests.swift; sourceTree = ""; }; + A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachRetryLoop.swift; sourceTree = ""; }; E30780000000000000000011 /* SSHPTYAttachStartupCommandBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachStartupCommandBuilder.swift; sourceTree = ""; }; 6379A0036379A0036379A003 /* SSHPTYResizeMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYResizeMonitor.swift; sourceTree = ""; }; 4F73A5C0BB93507E18261385 /* SSHStartupManualReconnectTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHStartupManualReconnectTests.swift; sourceTree = ""; }; @@ -6624,6 +6627,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B9000001A1B2C3D4E5F60719 /* cmux.swift */, REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */, C77070000000000000000001 /* SSHPTYAttachExitCode.swift */, + A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */, 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */, E60610200000000000000001 /* SSHPTYAttachReconnectInputFilterControl.swift */, E60610100000000000000001 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift */, @@ -9008,6 +9012,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 5B11E5A100000000000000A1 /* SpinnerGalleryDebugWindowController.swift in Sources */, A6AC72060000000000000001 /* SpinnerGalleryRootView.swift in Sources */, A6AC72070000000000000001 /* SpinnerSpec.swift in Sources */, + A87500100000000000000001 /* SSHPTYAttachRetryLoop.swift in Sources */, E30780000000000000000012 /* SSHPTYAttachStartupCommandBuilder.swift in Sources */, D35B71010000000000000001 /* StartupBreadcrumbLog.swift in Sources */, D7AB00000000000000B041 /* SupersededPhoneDismissBuffer.swift in Sources */, @@ -9474,6 +9479,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = E60610400000000000000002 /* SSHPTYAttachReconnectInputFilterPumpIO.swift in Sources */, E60610100000000000000002 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift in Sources */, E60610300000000000000002 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */, + A87500100000000000000002 /* SSHPTYAttachRetryLoop.swift in Sources */, 6379A0046379A0046379A004 /* SSHPTYResizeMonitor.swift in Sources */, A6AC720A0000000000000001 /* WorkspaceLoadingArguments.swift in Sources */, ); diff --git a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift index cb76c6873fba..93e193c0fbc2 100644 --- a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift +++ b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift @@ -3900,7 +3900,7 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { XCTAssertEqual(methods, ["workspace.remote.pty_bridge", "workspace.remote.pty_sessions", "workspace.remote.pty_attach_end"]) } - func testSSHPTYAttachBridgeEOFWhileSessionRunsPreservesLifecycleForRetry() throws { + func testSSHPTYAttachExhaustedZeroOutputBridgeEOFReleasesSurface() throws { let cliPath = try bundledCLIPath() let socketPath = makeSocketPath("sshptyeof") let listenerFD = try bindUnixSocket(at: socketPath) @@ -3971,6 +3971,11 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { "detached": true, ] ) + case "workspace.remote.pty_attach_end": + XCTAssertEqual(params["workspace_id"] as? String, workspaceId) + XCTAssertEqual(params["surface_id"] as? String, surfaceId) + XCTAssertEqual(params["session_id"] as? String, sessionId) + return self.v2Response(id: id, ok: true, result: ["ended": true]) default: return self.v2Response( id: id, @@ -3985,6 +3990,8 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { environment["CMUX_SOCKET_PATH"] = socketPath environment["CMUX_CLI_SENTRY_DISABLED"] = "1" environment["CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY"] = "1" + environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] = "2" + environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] = "3" let result = runProcess( executablePath: cliPath, @@ -4001,13 +4008,23 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { wait(for: [socketHandled, bridgeHandled], timeout: 5) XCTAssertFalse(result.timedOut, result.stderr) - XCTAssertEqual(result.status, 254, result.stderr) + XCTAssertEqual(result.status, 252, result.stderr) XCTAssertTrue( - result.stderr.contains("ssh-pty-attach: bridge closed while remote PTY session is still running"), + result.stderr.contains("bridge closed without receiving output"), result.stderr ) let methods = state.snapshot().compactMap { self.jsonObject($0)?["method"] as? String } - XCTAssertEqual(methods, ["workspace.remote.pty_bridge", "workspace.remote.pty_resize", "workspace.remote.pty_sessions", "workspace.remote.pty_detach"]) + XCTAssertEqual( + methods, + [ + "workspace.remote.pty_bridge", + "workspace.remote.pty_resize", + "workspace.remote.pty_sessions", + "workspace.remote.pty_detach", + "workspace.remote.pty_sessions", + "workspace.remote.pty_attach_end", + ] + ) } func testSSHPTYAttachBridgeEOFWhenSessionGoneClearsLocalState() throws { diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift index e824784aeb75..17995e9014b3 100644 --- a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -15,6 +15,35 @@ struct SSHPTYAttachNoProgressRetryTests { let timedOut: Bool } + @Test("Only pre-limit no-progress attempts preserve the surface for another retry") + func noProgressRetryBoundary() { + #expect(SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 0, limit: 3)) + #expect(SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 1, limit: 3)) + #expect(!SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 2, limit: 3)) + } + + @Test("Output or a sustained connection proves bridge progress") + func bridgeProgressClassification() { + #expect( + SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + receivedOutput: false, + bridgeUptime: 1 + ) + ) + #expect( + !SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + receivedOutput: true, + bridgeUptime: 1 + ) + ) + #expect( + !SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + receivedOutput: false, + bridgeUptime: 30 + ) + ) + } + @Test("Repeated zero-progress bridge closures stop after the health budget") func repeatedZeroProgressClosuresStop() throws { let fileManager = FileManager.default @@ -76,6 +105,69 @@ struct SSHPTYAttachNoProgressRetryTests { #expect(result.stderr.contains("made no progress after 3 attempts"), Comment(rawValue: result.stderr)) } + @Test("A normal retryable closure resets the no-progress streak") + func normalRetryableClosureResetsNoProgressStreak() throws { + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-ssh-pty-progress-reset-\(UUID().uuidString)", isDirectory: true) + let fakeCLI = root.appendingPathComponent("cmux") + let fakeSleep = root.appendingPathComponent("sleep") + let attemptFile = root.appendingPathComponent("attempts") + let policyLog = root.appendingPathComponent("policy-log") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + try Self.writeShellFile(at: fakeCLI, lines: [ + "#!/bin/sh", + "case \" $* \" in", + " *\" ssh-pty-attach \"*)", + " count=$(cat \"$CMUX_TEST_ATTEMPT_FILE\" 2>/dev/null || printf 0)", + " count=$((count + 1))", + " printf '%s' \"$count\" > \"$CMUX_TEST_ATTEMPT_FILE\"", + " printf '%s/%s\\n' \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY:-missing}\" \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT:-missing}\" >> \"$CMUX_TEST_POLICY_LOG\"", + " if [ \"$count\" -eq 2 ]; then exit 254; fi", + " exit 252", + " ;;", + " *) exit 0 ;;", + "esac", + ]) + try Self.writeShellFile(at: fakeSleep, lines: ["#!/bin/sh", "exit 0"]) + for executable in [fakeCLI, fakeSleep] { + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + } + + var environment = ProcessInfo.processInfo.environment + environment["PATH"] = "\(root.path):\(environment["PATH"] ?? "/usr/bin:/bin")" + environment["CMUX_BUNDLED_CLI_PATH"] = fakeCLI.path + environment["CMUX_SOCKET_PATH"] = "/tmp/cmux-debug-test.sock" + environment["CMUX_WORKSPACE_ID"] = "11111111-1111-1111-1111-111111111111" + environment["CMUX_SURFACE_ID"] = "22222222-2222-2222-2222-222222222222" + environment["CMUX_TEST_ATTEMPT_FILE"] = attemptFile.path + environment["CMUX_TEST_POLICY_LOG"] = policyLog.path + environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = "3" + environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" + environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" + + let result = Self.run( + command: SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), + environment: environment + ) + + #expect(!result.timedOut, Comment(rawValue: result.stderr)) + #expect(result.status == 1, Comment(rawValue: result.stderr)) + #expect(try String(contentsOf: attemptFile, encoding: .utf8) == "5") + #expect( + try String(contentsOf: policyLog, encoding: .utf8) == """ + 0/3 + 1/3 + 0/3 + 1/3 + 2/3 + + """ + ) + } + private static func writeShellFile(at url: URL, lines: [String]) throws { try (lines.joined(separator: "\n") + "\n").write(to: url, atomically: true, encoding: .utf8) } From 3343a179544bf6d6172b8e6434c9fabeec27fdb7 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 20:10:58 -0700 Subject: [PATCH 05/37] test: prove concurrent PTY starts coalesce --- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index 1b1596d5ffb8..eecf21d46405 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -28,6 +28,19 @@ import ( "nhooyr.io/websocket" ) +type doneObservedContext struct { + context.Context + observed chan<- struct{} +} + +func (c doneObservedContext) Done() <-chan struct{} { + select { + case c.observed <- struct{}{}: + default: + } + return c.Context.Done() +} + func newTestWebSocketPTYServer(t *testing.T, leasePath string) (*httptest.Server, *wsPTYHub) { t.Helper() stderr := &bytes.Buffer{} @@ -234,11 +247,11 @@ func TestAttachRPCConcurrentSameSessionStartsOnce(t *testing.T) { return openPTY() } - attach := func(attachmentID string) <-chan error { + attach := func(ctx context.Context, attachmentID string) <-chan error { result := make(chan error, 1) go func() { _, _, _, err := hub.attachRPC( - context.Background(), + ctx, "shared-session", attachmentID, 80, @@ -253,13 +266,32 @@ func TestAttachRPCConcurrentSameSessionStartsOnce(t *testing.T) { return result } - firstResult := attach("first-attachment") + firstResult := attach(context.Background(), "first-attachment") select { case <-startEntered: case <-time.After(5 * time.Second): t.Fatal("first attach never attempted PTY allocation") } - secondResult := attach("second-attachment") + + secondWaiting := make(chan struct{}, 1) + secondResult := attach( + doneObservedContext{Context: context.Background(), observed: secondWaiting}, + "second-attachment", + ) + select { + case <-secondWaiting: + case <-time.After(time.Second): + close(releaseStart) + <-firstResult + <-secondResult + t.Fatal("second attach did not join the in-flight session start") + } + if got := startCount.Load(); got != 1 { + close(releaseStart) + <-firstResult + <-secondResult + t.Fatalf("PTY start count before release = %d, want 1", got) + } close(releaseStart) if err := <-firstResult; err != nil { From 9b158333fbabc2393a6edc5b53deef099dbfb553 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 21:10:18 -0700 Subject: [PATCH 06/37] Fix SSH PTY retry policy target ownership --- CLI/CMUXCLI+SSHPTYAttachBridge.swift | 5 +- CLI/SSHPTYAttachExitCode.swift | 68 ------- CLI/SSHPTYAttachRetryLoop.swift | 78 -------- CLI/cmux.swift | 2 +- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 176 ++++++++++++++++++ .../SSHPTYAttachStartupCommandBuilder.swift | 2 +- cmux.xcodeproj/project.pbxproj | 12 -- .../SSHPTYAttachExitCodeClassifierTests.swift | 1 + .../SSHPTYAttachNoProgressRetryTests.swift | 128 ++++++------- 9 files changed, 241 insertions(+), 231 deletions(-) delete mode 100644 CLI/SSHPTYAttachExitCode.swift delete mode 100644 CLI/SSHPTYAttachRetryLoop.swift create mode 100644 Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift diff --git a/CLI/CMUXCLI+SSHPTYAttachBridge.swift b/CLI/CMUXCLI+SSHPTYAttachBridge.swift index 03acc0834421..96e4f1d76258 100644 --- a/CLI/CMUXCLI+SSHPTYAttachBridge.swift +++ b/CLI/CMUXCLI+SSHPTYAttachBridge.swift @@ -1,5 +1,6 @@ import Darwin import Foundation +import CmuxFoundation extension CLIError { init(message: String, exitCode: SSHPTYAttachExitCode) { @@ -26,7 +27,7 @@ extension CMUXCLI { limit > 0 else { return false } - return SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining( + return SSHPTYAttachExitCode.hasNoProgressRetryRemaining( currentRetry: retry, limit: limit ) @@ -43,7 +44,7 @@ extension CMUXCLI { guard sshPTYAttachWrapperRetryPending(), environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] != nil, environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] != nil, - SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( receivedOutput: receivedOutput, bridgeUptime: bridgeUptime ) else { diff --git a/CLI/SSHPTYAttachExitCode.swift b/CLI/SSHPTYAttachExitCode.swift deleted file mode 100644 index f86e84da29f2..000000000000 --- a/CLI/SSHPTYAttachExitCode.swift +++ /dev/null @@ -1,68 +0,0 @@ -import Foundation - -/// Owns ssh-pty-attach exit-code semantics. -/// -/// Exit codes 252, 254, and 255 are handled by `SSHPTYAttachRetryLoop`. -/// Status 252 has its own bounded consecutive-failure budget; 254 and 255 use -/// the general reconnect budget. The classifier patterns mirror -/// `userFacingRemotePTYErrorMessage` in `CLI/CMUXCLI+RemotePTYErrors.swift`. -enum SSHPTYAttachExitCode: Int32 { - case fatal = 1 - case bridgeClosedWithoutProgress = 252 - case sessionNotFound = 253 - case bridgeClosedSessionRunning = 254 - case retryableTransient = 255 - - /// Statuses the embedded wrapper loops (`case 254|255`) re-run instead of - /// surfacing. Failures exiting with these codes must keep app-side surface - /// tracking intact: the wrapper immediately reattaches on the same surface, - /// and a successful retry never re-tracks a surface that pty_attach_end - /// already untracked. - var isWrapperRetryable: Bool { - self == .bridgeClosedSessionRunning || self == .retryableTransient - } - - static func classifyBridgeEstablishmentFailure(_ rawDescription: String) -> SSHPTYAttachExitCode { - classifyNormalized(rawDescription.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) - } - - static func classifyBridgeEstablishmentFailure(code: String?, message: String) -> SSHPTYAttachExitCode { - let normalizedCode = code?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - if normalizedCode == "pty_session_not_found" { - return .sessionNotFound - } - if normalizedCode == "pty_lifecycle_closed" { - return .fatal - } - let rawDescription = [normalizedCode, message] - .compactMap { $0 } - .joined(separator: " ") - return classifyBridgeEstablishmentFailure(rawDescription) - } - - private static func classifyNormalized(_ description: String) -> SSHPTYAttachExitCode { - if description.contains("pty_session_not_found") || - ((description.contains("persistent ssh pty session") || - description.contains("persistent pty session")) && - (description.contains("not running") || - description.contains("no longer running"))) { - return .sessionNotFound - } - - if description.contains("timed out") || - description.contains("timeout") || - description.contains("did not respond in time") || - description.contains("remote connection is not active") || - description.contains("remote daemon is not ready") || - description.contains("remote daemon tunnel is not ready") || - description.contains("pty_input_queue_full") || - description.contains("pty input queue is full") || - description.contains("input is temporarily backed up") || - description.contains("connection refused") || - description.contains("connection reset") { - return .retryableTransient - } - - return .fatal - } -} diff --git a/CLI/SSHPTYAttachRetryLoop.swift b/CLI/SSHPTYAttachRetryLoop.swift deleted file mode 100644 index b624bc0a69a5..000000000000 --- a/CLI/SSHPTYAttachRetryLoop.swift +++ /dev/null @@ -1,78 +0,0 @@ -import Foundation - -enum SSHPTYAttachRetryLoop { - private static let healthyBridgeUptime: TimeInterval = 30 - - static func bridgeClosureMadeNoProgress( - receivedOutput: Bool, - bridgeUptime: TimeInterval - ) -> Bool { - // A bridge that remains connected through an ordinary idle interval is - // healthy even when the remote shell has not emitted output. - !receivedOutput && bridgeUptime >= 0 && bridgeUptime < healthyBridgeUptime - } - - static func hasNoProgressRetryRemaining(currentRetry: Int, limit: Int) -> Bool { - currentRetry >= 0 && limit > 0 && currentRetry + 1 < limit - } - - static func lines(command: String, reauthenticates: Bool) -> [String] { - let reauthenticate = reauthenticates ? "cmux_ssh_attach_reauth_required=1" : ":" - let reattachingFormat = shellQuote( - String( - localized: "cli.sshPtyAttach.bridgeClosedReattaching", - defaultValue: "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." - ) - ) - let noProgressFormat = shellQuote( - String( - localized: "cli.sshPtyAttach.noProgressRetryLimitReached", - defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." - ) - ) - let noProgressStatus = SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue - - return [ - "cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"", - "case \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac", - "cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"", - "case \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac", - "cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"", - "case \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", - "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", - "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", - "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", - "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", - "cmux_ssh_attach_no_progress_retry=0", - "cmux_ssh_attach_retry=0", - "cmux_ssh_attach_reauth_required=0", - "while :; do", - " if [ \"$cmux_ssh_attach_reauth_required\" -eq 1 ]; then", - " cmux_ssh_attach_foreground_auth", - " cmux_ssh_attach_status=$?", - " if [ \"$cmux_ssh_attach_status\" -eq 0 ]; then cmux_ssh_attach_reauth_required=0; elif [ \"$cmux_ssh_attach_status\" -ne 255 ]; then exit \"$cmux_ssh_attach_status\"; fi", - " fi", - " if [ \"$cmux_ssh_attach_reauth_required\" -eq 0 ]; then", - " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi", - " CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY=\"$cmux_ssh_attach_no_progress_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT=\"$cmux_ssh_attach_no_progress_limit\" \(command)", - " cmux_ssh_attach_status=$?", - " case \"$cmux_ssh_attach_status\" in", - " \(noProgressStatus)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(noProgressFormat) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi ;;", - " 254) cmux_ssh_attach_no_progress_retry=0; cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;;", - " 255) cmux_ssh_attach_no_progress_retry=0; \(reauthenticate) ;;", - " *) exit \"$cmux_ssh_attach_status\" ;;", - " esac", - " fi", - " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi", - " cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))", - " if [ -t 2 ]; then printf '\\n\\033[33m%s\\033[0m\\n' \"$(printf \(reattachingFormat) \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\")\" >&2 || true; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi", - " if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi", - "done", - ] - } - - private static func shellQuote(_ value: String) -> String { - "'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'" - } -} diff --git a/CLI/cmux.swift b/CLI/cmux.swift index e94c9d471c98..12bd807b2a1d 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -12422,7 +12422,7 @@ struct CMUXCLI { "trap 'cmux_ssh_attach_signal_exit 129' HUP", "trap 'cmux_ssh_attach_signal_exit 130' INT", "trap 'cmux_ssh_attach_signal_exit 143' TERM", - ] + SSHPTYAttachRetryLoop.lines( + ] + SSHPTYAttachExitCode.retryLoopLines( command: attachCommand, reauthenticates: false )).joined(separator: "\n") diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift new file mode 100644 index 000000000000..e4e48edda85c --- /dev/null +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -0,0 +1,176 @@ +import Foundation + +/// Describes the process exit status and retry policy for an SSH PTY attach. +/// +/// Status 252 has a bounded consecutive-failure budget, while statuses 254 +/// and 255 use the general reconnect budget. +public enum SSHPTYAttachExitCode: Int32 { + private static let healthyBridgeUptime: Double = 30 + + /// A non-retryable attach failure. + case fatal = 1 + + /// A rapidly closed bridge that produced no remote PTY output. + case bridgeClosedWithoutProgress = 252 + + /// A persistent PTY session that no longer exists and must be respawned. + case sessionNotFound = 253 + + /// A closed bridge whose persistent PTY session is still running. + case bridgeClosedSessionRunning = 254 + + /// A transient transport or daemon failure that may succeed after reconnecting. + case retryableTransient = 255 + + /// Whether the general persistent-attach wrapper retries this status. + /// + /// Failures with these statuses keep app-side surface tracking intact + /// because the wrapper immediately reattaches on the same surface. + public var isWrapperRetryable: Bool { + self == .bridgeClosedSessionRunning || self == .retryableTransient + } + + /// Determines whether a bridge closed before demonstrating useful progress. + /// + /// - Parameters: + /// - receivedOutput: Whether the bridge delivered any remote PTY output. + /// - bridgeUptime: The number of seconds the ready bridge remained open. + /// - Returns: `true` for a rapid, zero-output closure. + public static func bridgeClosureMadeNoProgress( + receivedOutput: Bool, + bridgeUptime: Double + ) -> Bool { + // A bridge that remains connected through an ordinary idle interval is + // healthy even when the remote shell has not emitted output. + !receivedOutput && bridgeUptime >= 0 && bridgeUptime < healthyBridgeUptime + } + + /// Determines whether another no-progress retry remains in the bounded budget. + /// + /// - Parameters: + /// - currentRetry: The zero-based number of prior no-progress retries. + /// - limit: The maximum number of consecutive no-progress attempts. + /// - Returns: `true` when another attempt is allowed. + public static func hasNoProgressRetryRemaining(currentRetry: Int, limit: Int) -> Bool { + currentRetry >= 0 && limit > 0 && currentRetry + 1 < limit + } + + /// Builds the POSIX shell loop shared by persistent SSH PTY attach entry points. + /// + /// - Parameters: + /// - command: The shell command that performs one attach attempt. + /// - reauthenticates: Whether transient failures should request foreground authentication. + /// - Returns: Shell source lines implementing reconnect and no-progress budgets. + public static func retryLoopLines(command: String, reauthenticates: Bool) -> [String] { + let reauthenticate = reauthenticates ? "cmux_ssh_attach_reauth_required=1" : ":" + let reattachingFormat = String( + localized: "cli.sshPtyAttach.bridgeClosedReattaching", + defaultValue: "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." + ).remoteCommandShellQuoted + let noProgressFormat = String( + localized: "cli.sshPtyAttach.noProgressRetryLimitReached", + defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." + ).remoteCommandShellQuoted + let noProgressStatus = bridgeClosedWithoutProgress.rawValue + let sessionRunningStatus = bridgeClosedSessionRunning.rawValue + let transientStatus = retryableTransient.rawValue + + return [ + "cmux_ssh_attach_reconnect_limit=\"${CMUX_SSH_RECONNECT_LIMIT:-}\"", + "case \"$cmux_ssh_attach_reconnect_limit\" in '') cmux_ssh_attach_reconnect_limit='∞'; cmux_ssh_attach_reconnect_unbounded=1 ;; *[!0-9]*) cmux_ssh_attach_reconnect_limit=20; cmux_ssh_attach_reconnect_unbounded=0 ;; *) cmux_ssh_attach_reconnect_unbounded=0 ;; esac", + "cmux_ssh_attach_reconnect_delay=\"${CMUX_SSH_RECONNECT_DELAY_SECONDS:-2}\"", + "case \"$cmux_ssh_attach_reconnect_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_delay=2 ;; esac", + "cmux_ssh_attach_reconnect_max_delay=\"${CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS:-30}\"", + "case \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", + "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", + "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", + "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", + "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", + "cmux_ssh_attach_no_progress_retry=0", + "cmux_ssh_attach_retry=0", + "cmux_ssh_attach_reauth_required=0", + "while :; do", + " if [ \"$cmux_ssh_attach_reauth_required\" -eq 1 ]; then", + " cmux_ssh_attach_foreground_auth", + " cmux_ssh_attach_status=$?", + " if [ \"$cmux_ssh_attach_status\" -eq 0 ]; then cmux_ssh_attach_reauth_required=0; elif [ \"$cmux_ssh_attach_status\" -ne \(transientStatus) ]; then exit \"$cmux_ssh_attach_status\"; fi", + " fi", + " if [ \"$cmux_ssh_attach_reauth_required\" -eq 0 ]; then", + " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 1 ] || [ \"$cmux_ssh_attach_retry\" -lt \"$cmux_ssh_attach_reconnect_limit\" ]; then cmux_ssh_attach_can_retry=1; else cmux_ssh_attach_can_retry=0; fi", + " CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY=\"$cmux_ssh_attach_no_progress_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT=\"$cmux_ssh_attach_no_progress_limit\" \(command)", + " cmux_ssh_attach_status=$?", + " case \"$cmux_ssh_attach_status\" in", + " \(noProgressStatus)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(noProgressFormat) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi ;;", + " \(sessionRunningStatus)) cmux_ssh_attach_no_progress_retry=0; cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;;", + " \(transientStatus)) cmux_ssh_attach_no_progress_retry=0; \(reauthenticate) ;;", + " *) exit \"$cmux_ssh_attach_status\" ;;", + " esac", + " fi", + " if [ \"$cmux_ssh_attach_reconnect_unbounded\" -eq 0 ] && [ \"$cmux_ssh_attach_retry\" -ge \"$cmux_ssh_attach_reconnect_limit\" ]; then exit \"$cmux_ssh_attach_status\"; fi", + " cmux_ssh_attach_retry=$((cmux_ssh_attach_retry + 1))", + " if [ -t 2 ]; then printf '\\n\\033[33m%s\\033[0m\\n' \"$(printf \(reattachingFormat) \"$cmux_ssh_attach_retry\" \"$cmux_ssh_attach_reconnect_limit\")\" >&2 || true; fi", + " if [ \"$cmux_ssh_attach_reconnect_delay\" -gt 0 ]; then sleep \"$cmux_ssh_attach_reconnect_delay\"; fi", + " if [ \"$cmux_ssh_attach_reconnect_delay\" -lt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=$((cmux_ssh_attach_reconnect_delay * 2)); if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi; fi", + "done", + ] + } + + /// Classifies a textual bridge-establishment failure into its attach exit status. + /// + /// - Parameter rawDescription: The daemon or transport failure description. + /// - Returns: The exit status that drives wrapper retry or respawn behavior. + public static func classifyBridgeEstablishmentFailure( + _ rawDescription: String + ) -> SSHPTYAttachExitCode { + classifyNormalized(rawDescription.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) + } + + /// Classifies a structured bridge-establishment failure into its attach exit status. + /// + /// - Parameters: + /// - code: The structured daemon error code, when supplied. + /// - message: The daemon or transport failure message. + /// - Returns: The exit status that drives wrapper retry or respawn behavior. + public static func classifyBridgeEstablishmentFailure( + code: String?, + message: String + ) -> SSHPTYAttachExitCode { + let normalizedCode = code?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + if normalizedCode == "pty_session_not_found" { + return .sessionNotFound + } + if normalizedCode == "pty_lifecycle_closed" { + return .fatal + } + let rawDescription = [normalizedCode, message] + .compactMap { $0 } + .joined(separator: " ") + return classifyBridgeEstablishmentFailure(rawDescription) + } + + private static func classifyNormalized(_ description: String) -> SSHPTYAttachExitCode { + if description.contains("pty_session_not_found") || + ((description.contains("persistent ssh pty session") || + description.contains("persistent pty session")) && + (description.contains("not running") || + description.contains("no longer running"))) { + return .sessionNotFound + } + + if description.contains("timed out") || + description.contains("timeout") || + description.contains("did not respond in time") || + description.contains("remote connection is not active") || + description.contains("remote daemon is not ready") || + description.contains("remote daemon tunnel is not ready") || + description.contains("pty_input_queue_full") || + description.contains("pty input queue is full") || + description.contains("input is temporarily backed up") || + description.contains("connection refused") || + description.contains("connection reset") { + return .retryableTransient + } + + return .fatal + } +} diff --git a/Sources/SSHPTYAttachStartupCommandBuilder.swift b/Sources/SSHPTYAttachStartupCommandBuilder.swift index 0d19449b5688..9f5559dd913e 100644 --- a/Sources/SSHPTYAttachStartupCommandBuilder.swift +++ b/Sources/SSHPTYAttachStartupCommandBuilder.swift @@ -49,7 +49,7 @@ enum SSHPTYAttachStartupCommandBuilder { " --command-b64 \(shellQuote(Data($0.utf8).base64EncodedString()))" } ?? "" let attachCommand = "\"$cmux_ssh_attach_cli\" --socket \"$CMUX_SOCKET_PATH\" ssh-pty-attach --wait\(requireExistingFlag) --workspace \"$CMUX_WORKSPACE_ID\" --session-id \"$cmux_ssh_attach_session_id\" --lifecycle-id \"$cmux_ssh_attach_lifecycle_id\" --attachment-id \"${CMUX_SURFACE_ID:-}\"\(commandB64Flag)" - lines += SSHPTYAttachRetryLoop.lines( + lines += SSHPTYAttachExitCode.retryLoopLines( command: attachCommand, reauthenticates: foregroundAuth != nil ) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 9854db983a37..6e749ddd0437 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1927,8 +1927,6 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources 797800040000000000000001 /* SSHDeepSleepReattachTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 797800040000000000000002 /* SSHDeepSleepReattachTests.swift */; }; 8410A0020000000000000002 /* SSHForegroundAuthenticationMarkerCleanupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8410A0010000000000000001 /* SSHForegroundAuthenticationMarkerCleanupTests.swift */; }; 797800050000000000000001 /* SSHPersistentPTYRetryLifecycleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 797800050000000000000002 /* SSHPersistentPTYRetryLifecycleTests.swift */; }; - C77070000000000000000002 /* SSHPTYAttachExitCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000001 /* SSHPTYAttachExitCode.swift */; }; - C77070000000000000000003 /* SSHPTYAttachExitCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000001 /* SSHPTYAttachExitCode.swift */; }; C77070000000000000000006 /* SSHPTYAttachExitCodeClassifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C77070000000000000000007 /* SSHPTYAttachExitCodeClassifierTests.swift */; }; A87500010000000000000001 /* SSHPTYAttachNoProgressRetryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500010000000000000002 /* SSHPTYAttachNoProgressRetryTests.swift */; }; 6E8B6A69A468EF938B9AD8C2 /* SSHPTYAttachReconnectInputFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */; }; @@ -1942,8 +1940,6 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources E60610300000000000000002 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */; }; E60610300000000000000003 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */; }; B6285B71BA6F82AF8F945E00 /* SSHPTYAttachReconnectInputFilterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C4AD348F196FBBEE52D53A7 /* SSHPTYAttachReconnectInputFilterTests.swift */; }; - A87500100000000000000001 /* SSHPTYAttachRetryLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */; }; - A87500100000000000000002 /* SSHPTYAttachRetryLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */; }; E30780000000000000000012 /* SSHPTYAttachStartupCommandBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30780000000000000000011 /* SSHPTYAttachStartupCommandBuilder.swift */; }; 6379A0046379A0046379A004 /* SSHPTYResizeMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6379A0036379A0036379A003 /* SSHPTYResizeMonitor.swift */; }; EF70B7123200D1FB6F03DB26 /* SSHStartupManualReconnectTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F73A5C0BB93507E18261385 /* SSHStartupManualReconnectTests.swift */; }; @@ -4333,7 +4329,6 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 797800040000000000000002 /* SSHDeepSleepReattachTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHDeepSleepReattachTests.swift; sourceTree = ""; }; 8410A0010000000000000001 /* SSHForegroundAuthenticationMarkerCleanupTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHForegroundAuthenticationMarkerCleanupTests.swift; sourceTree = ""; }; 797800050000000000000002 /* SSHPersistentPTYRetryLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPersistentPTYRetryLifecycleTests.swift; sourceTree = ""; }; - C77070000000000000000001 /* SSHPTYAttachExitCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachExitCode.swift; sourceTree = ""; }; C77070000000000000000007 /* SSHPTYAttachExitCodeClassifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachExitCodeClassifierTests.swift; sourceTree = ""; }; A87500010000000000000002 /* SSHPTYAttachNoProgressRetryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachNoProgressRetryTests.swift; sourceTree = ""; }; 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilter.swift; sourceTree = ""; }; @@ -4342,7 +4337,6 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = E60610100000000000000001 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterSequenceMatch.swift; sourceTree = ""; }; E60610300000000000000001 /* SSHPTYAttachReconnectInputFilterState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterState.swift; sourceTree = ""; }; 0C4AD348F196FBBEE52D53A7 /* SSHPTYAttachReconnectInputFilterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachReconnectInputFilterTests.swift; sourceTree = ""; }; - A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachRetryLoop.swift; sourceTree = ""; }; E30780000000000000000011 /* SSHPTYAttachStartupCommandBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYAttachStartupCommandBuilder.swift; sourceTree = ""; }; 6379A0036379A0036379A003 /* SSHPTYResizeMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHPTYResizeMonitor.swift; sourceTree = ""; }; 4F73A5C0BB93507E18261385 /* SSHStartupManualReconnectTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHStartupManualReconnectTests.swift; sourceTree = ""; }; @@ -6626,8 +6620,6 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 805500000000000000000003 /* BrowserValueTextFormatter.swift */, B9000001A1B2C3D4E5F60719 /* cmux.swift */, REE0CA0000000000000000C1 /* CMUXCLI+Remotes.swift */, - C77070000000000000000001 /* SSHPTYAttachExitCode.swift */, - A87500100000000000000003 /* SSHPTYAttachRetryLoop.swift */, 1E4DB33FA55F1B13C60EFFC8 /* SSHPTYAttachReconnectInputFilter.swift */, E60610200000000000000001 /* SSHPTYAttachReconnectInputFilterControl.swift */, E60610100000000000000001 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift */, @@ -9012,7 +9004,6 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 5B11E5A100000000000000A1 /* SpinnerGalleryDebugWindowController.swift in Sources */, A6AC72060000000000000001 /* SpinnerGalleryRootView.swift in Sources */, A6AC72070000000000000001 /* SpinnerSpec.swift in Sources */, - A87500100000000000000001 /* SSHPTYAttachRetryLoop.swift in Sources */, E30780000000000000000012 /* SSHPTYAttachStartupCommandBuilder.swift in Sources */, D35B71010000000000000001 /* StartupBreadcrumbLog.swift in Sources */, D7AB00000000000000B041 /* SupersededPhoneDismissBuffer.swift in Sources */, @@ -9473,13 +9464,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B9000027A1B2C3D4E5F60719 /* RemoteRelayZshBootstrap.swift in Sources */, 5E2701020000000000000003 /* SentryEventScrubber.swift in Sources */, C510C1E00000000000000002 /* SocketOperationTelemetry.swift in Sources */, - C77070000000000000000002 /* SSHPTYAttachExitCode.swift in Sources */, B816E948EC5E42AF967648AC /* SSHPTYAttachReconnectInputFilter.swift in Sources */, E60610200000000000000002 /* SSHPTYAttachReconnectInputFilterControl.swift in Sources */, E60610400000000000000002 /* SSHPTYAttachReconnectInputFilterPumpIO.swift in Sources */, E60610100000000000000002 /* SSHPTYAttachReconnectInputFilterSequenceMatch.swift in Sources */, E60610300000000000000002 /* SSHPTYAttachReconnectInputFilterState.swift in Sources */, - A87500100000000000000002 /* SSHPTYAttachRetryLoop.swift in Sources */, 6379A0046379A0046379A004 /* SSHPTYResizeMonitor.swift in Sources */, A6AC720A0000000000000001 /* WorkspaceLoadingArguments.swift in Sources */, ); @@ -10074,7 +10063,6 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 797800040000000000000001 /* SSHDeepSleepReattachTests.swift in Sources */, 8410A0020000000000000002 /* SSHForegroundAuthenticationMarkerCleanupTests.swift in Sources */, 797800050000000000000001 /* SSHPersistentPTYRetryLifecycleTests.swift in Sources */, - C77070000000000000000003 /* SSHPTYAttachExitCode.swift in Sources */, C77070000000000000000006 /* SSHPTYAttachExitCodeClassifierTests.swift in Sources */, A87500010000000000000001 /* SSHPTYAttachNoProgressRetryTests.swift in Sources */, 6E8B6A69A468EF938B9AD8C2 /* SSHPTYAttachReconnectInputFilter.swift in Sources */, diff --git a/cmuxTests/SSHPTYAttachExitCodeClassifierTests.swift b/cmuxTests/SSHPTYAttachExitCodeClassifierTests.swift index de3671cdd44f..8fa372ed9c31 100644 --- a/cmuxTests/SSHPTYAttachExitCodeClassifierTests.swift +++ b/cmuxTests/SSHPTYAttachExitCodeClassifierTests.swift @@ -1,3 +1,4 @@ +import CmuxFoundation import Testing @Suite struct SSHPTYAttachExitCodeClassifierTests { diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift index 17995e9014b3..f3d3d9ed228a 100644 --- a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -1,3 +1,4 @@ +import CmuxFoundation import Foundation import Testing @@ -15,29 +16,35 @@ struct SSHPTYAttachNoProgressRetryTests { let timedOut: Bool } + private struct ScenarioResult { + let attempts: String + let policyLog: String + let process: ProcessResult + } + @Test("Only pre-limit no-progress attempts preserve the surface for another retry") func noProgressRetryBoundary() { - #expect(SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 0, limit: 3)) - #expect(SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 1, limit: 3)) - #expect(!SSHPTYAttachRetryLoop.hasNoProgressRetryRemaining(currentRetry: 2, limit: 3)) + #expect(SSHPTYAttachExitCode.hasNoProgressRetryRemaining(currentRetry: 0, limit: 3)) + #expect(SSHPTYAttachExitCode.hasNoProgressRetryRemaining(currentRetry: 1, limit: 3)) + #expect(!SSHPTYAttachExitCode.hasNoProgressRetryRemaining(currentRetry: 2, limit: 3)) } @Test("Output or a sustained connection proves bridge progress") func bridgeProgressClassification() { #expect( - SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( receivedOutput: false, bridgeUptime: 1 ) ) #expect( - !SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + !SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( receivedOutput: true, bridgeUptime: 1 ) ) #expect( - !SSHPTYAttachRetryLoop.bridgeClosureMadeNoProgress( + !SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( receivedOutput: false, bridgeUptime: 30 ) @@ -46,70 +53,62 @@ struct SSHPTYAttachNoProgressRetryTests { @Test("Repeated zero-progress bridge closures stop after the health budget") func repeatedZeroProgressClosuresStop() throws { - let fileManager = FileManager.default - let root = fileManager.temporaryDirectory - .appendingPathComponent("cmux-ssh-pty-no-progress-\(UUID().uuidString)", isDirectory: true) - let fakeCLI = root.appendingPathComponent("cmux") - let fakeSleep = root.appendingPathComponent("sleep") - let attemptFile = root.appendingPathComponent("attempts") - let policyLog = root.appendingPathComponent("policy-log") - try fileManager.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? fileManager.removeItem(at: root) } + let scenario = try Self.runNoProgressScenario( + namePrefix: "no-progress", + decisionLines: [ + " exit \(SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue)", + ] + ) - try Self.writeShellFile(at: fakeCLI, lines: [ - "#!/bin/sh", - "case \" $* \" in", - " *\" ssh-pty-attach \"*)", - " count=$(cat \"$CMUX_TEST_ATTEMPT_FILE\" 2>/dev/null || printf 0)", - " count=$((count + 1))", - " printf '%s' \"$count\" > \"$CMUX_TEST_ATTEMPT_FILE\"", - " printf '%s/%s\\n' \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY:-missing}\" \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT:-missing}\" >> \"$CMUX_TEST_POLICY_LOG\"", - " exit 252", - " ;;", - " *) exit 0 ;;", - "esac", - ]) - try Self.writeShellFile(at: fakeSleep, lines: ["#!/bin/sh", "exit 0"]) - for executable in [fakeCLI, fakeSleep] { - try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) - } + #expect(!scenario.process.timedOut, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.process.status == 1, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.attempts == "3") + #expect( + scenario.policyLog == """ + 0/3 + 1/3 + 2/3 - var environment = ProcessInfo.processInfo.environment - environment["PATH"] = "\(root.path):\(environment["PATH"] ?? "/usr/bin:/bin")" - environment["CMUX_BUNDLED_CLI_PATH"] = fakeCLI.path - environment["CMUX_SOCKET_PATH"] = "/tmp/cmux-debug-test.sock" - environment["CMUX_WORKSPACE_ID"] = "11111111-1111-1111-1111-111111111111" - environment["CMUX_SURFACE_ID"] = "22222222-2222-2222-2222-222222222222" - environment["CMUX_TEST_ATTEMPT_FILE"] = attemptFile.path - environment["CMUX_TEST_POLICY_LOG"] = policyLog.path - environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = "3" - environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" - environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" + """ + ) + #expect( + scenario.process.stderr.contains("made no progress after 3 attempts"), + Comment(rawValue: scenario.process.stderr) + ) + } - let result = Self.run( - command: SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), - environment: environment + @Test("A normal retryable closure resets the no-progress streak") + func normalRetryableClosureResetsNoProgressStreak() throws { + let scenario = try Self.runNoProgressScenario( + namePrefix: "progress-reset", + decisionLines: [ + " if [ \"$count\" -eq 2 ]; then exit \(SSHPTYAttachExitCode.bridgeClosedSessionRunning.rawValue); fi", + " exit \(SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue)", + ] ) - #expect(!result.timedOut, Comment(rawValue: result.stderr)) - #expect(result.status == 1, Comment(rawValue: result.stderr)) - #expect(try String(contentsOf: attemptFile, encoding: .utf8) == "3") + #expect(!scenario.process.timedOut, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.process.status == 1, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.attempts == "5") #expect( - try String(contentsOf: policyLog, encoding: .utf8) == """ + scenario.policyLog == """ + 0/3 + 1/3 0/3 1/3 2/3 """ ) - #expect(result.stderr.contains("made no progress after 3 attempts"), Comment(rawValue: result.stderr)) } - @Test("A normal retryable closure resets the no-progress streak") - func normalRetryableClosureResetsNoProgressStreak() throws { + private static func runNoProgressScenario( + namePrefix: String, + decisionLines: [String] + ) throws -> ScenarioResult { let fileManager = FileManager.default let root = fileManager.temporaryDirectory - .appendingPathComponent("cmux-ssh-pty-progress-reset-\(UUID().uuidString)", isDirectory: true) + .appendingPathComponent("cmux-ssh-pty-\(namePrefix)-\(UUID().uuidString)", isDirectory: true) let fakeCLI = root.appendingPathComponent("cmux") let fakeSleep = root.appendingPathComponent("sleep") let attemptFile = root.appendingPathComponent("attempts") @@ -125,8 +124,7 @@ struct SSHPTYAttachNoProgressRetryTests { " count=$((count + 1))", " printf '%s' \"$count\" > \"$CMUX_TEST_ATTEMPT_FILE\"", " printf '%s/%s\\n' \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY:-missing}\" \"${CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT:-missing}\" >> \"$CMUX_TEST_POLICY_LOG\"", - " if [ \"$count\" -eq 2 ]; then exit 254; fi", - " exit 252", + ] + decisionLines + [ " ;;", " *) exit 0 ;;", "esac", @@ -148,23 +146,15 @@ struct SSHPTYAttachNoProgressRetryTests { environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" - let result = Self.run( + let process = Self.run( command: SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), environment: environment ) - #expect(!result.timedOut, Comment(rawValue: result.stderr)) - #expect(result.status == 1, Comment(rawValue: result.stderr)) - #expect(try String(contentsOf: attemptFile, encoding: .utf8) == "5") - #expect( - try String(contentsOf: policyLog, encoding: .utf8) == """ - 0/3 - 1/3 - 0/3 - 1/3 - 2/3 - - """ + return ScenarioResult( + attempts: try String(contentsOf: attemptFile, encoding: .utf8), + policyLog: try String(contentsOf: policyLog, encoding: .utf8), + process: process ) } From 4f7fca69422c4d4e3a88ad1a58f1dcd0e8027074 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 21:40:54 -0700 Subject: [PATCH 07/37] fix: bound managed SSH PTY retry churn --- CLI/cmux.swift | 6 +- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 55 +++++++++++++--- .../SSHPTYAttachNoProgressRetryTests.swift | 65 ++++++++++++++++++- 3 files changed, 115 insertions(+), 11 deletions(-) diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 12bd807b2a1d..aec392cfad40 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -10259,9 +10259,13 @@ struct CMUXCLI { var authArguments = sshArgumentsOverridingHostRemoteCommand(baseSSHArguments(options)) authArguments += ["-T", options.destination, "true"] let authCommand = authArguments.map(shellQuote).joined(separator: " ") - let attachScript = buildSSHPTYAttachScriptBody( + let attachAttemptScript = buildSSHPTYAttachScriptBody( remoteShellCommand: remoteShellCommand ) + let attachAttemptCommand = "/bin/sh -c \(shellQuote(attachAttemptScript))" + let attachScript = SSHPTYAttachExitCode.noProgressRetryLoopLines( + command: attachAttemptCommand + ).joined(separator: "\n") var authScriptLines: [String] = [] let sharingOptions = SSHConnectionSharingOptions() let authenticationLockPath = sharingOptions.foregroundAuthenticationLockPath( diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift index e4e48edda85c..95d4c1f15f4b 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -63,15 +63,11 @@ public enum SSHPTYAttachExitCode: Int32 { /// - Returns: Shell source lines implementing reconnect and no-progress budgets. public static func retryLoopLines(command: String, reauthenticates: Bool) -> [String] { let reauthenticate = reauthenticates ? "cmux_ssh_attach_reauth_required=1" : ":" + let noProgressPolicy = noProgressShellPolicy() let reattachingFormat = String( localized: "cli.sshPtyAttach.bridgeClosedReattaching", defaultValue: "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." ).remoteCommandShellQuoted - let noProgressFormat = String( - localized: "cli.sshPtyAttach.noProgressRetryLimitReached", - defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." - ).remoteCommandShellQuoted - let noProgressStatus = bridgeClosedWithoutProgress.rawValue let sessionRunningStatus = bridgeClosedSessionRunning.rawValue let transientStatus = retryableTransient.rawValue @@ -84,8 +80,7 @@ public enum SSHPTYAttachExitCode: Int32 { "case \"$cmux_ssh_attach_reconnect_max_delay\" in ''|*[!0-9]*|0*) cmux_ssh_attach_reconnect_max_delay=30 ;; esac", "if [ \"$cmux_ssh_attach_reconnect_delay\" -gt \"$cmux_ssh_attach_reconnect_max_delay\" ]; then cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_max_delay\"; fi", "cmux_ssh_attach_reconnect_initial_delay=\"$cmux_ssh_attach_reconnect_delay\"", - "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", - "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", + ] + noProgressPolicy.configurationLines + [ "cmux_ssh_attach_no_progress_retry=0", "cmux_ssh_attach_retry=0", "cmux_ssh_attach_reauth_required=0", @@ -100,7 +95,7 @@ public enum SSHPTYAttachExitCode: Int32 { " CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY=\"$cmux_ssh_attach_can_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY=\"$cmux_ssh_attach_no_progress_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT=\"$cmux_ssh_attach_no_progress_limit\" \(command)", " cmux_ssh_attach_status=$?", " case \"$cmux_ssh_attach_status\" in", - " \(noProgressStatus)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(noProgressFormat) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi ;;", + " \(noProgressPolicy.status)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; \(noProgressPolicy.limitReachedCommand) ;;", " \(sessionRunningStatus)) cmux_ssh_attach_no_progress_retry=0; cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;;", " \(transientStatus)) cmux_ssh_attach_no_progress_retry=0; \(reauthenticate) ;;", " *) exit \"$cmux_ssh_attach_status\" ;;", @@ -115,6 +110,50 @@ public enum SSHPTYAttachExitCode: Int32 { ] } + /// Builds a bounded no-progress sub-loop for a wrapper that already owns + /// general reconnect and foreground-authentication policy. + /// + /// Status 252 is consumed until its health budget is exhausted. All other + /// statuses, including 254 and 255, return unchanged to the enclosing + /// wrapper so its existing reconnect and reauthentication behavior remains + /// the single owner of those transitions. + /// + /// - Parameter command: The shell command that performs one attach attempt. + /// - Returns: Shell source lines implementing the no-progress budget. + public static func noProgressRetryLoopLines(command: String) -> [String] { + let policy = noProgressShellPolicy() + + return policy.configurationLines + [ + "cmux_ssh_attach_no_progress_retry=0", + "while :; do", + " CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY=\"$cmux_ssh_attach_no_progress_retry\" CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT=\"$cmux_ssh_attach_no_progress_limit\" \(command)", + " cmux_ssh_attach_status=$?", + " if [ \"$cmux_ssh_attach_status\" -ne \(policy.status) ]; then exit \"$cmux_ssh_attach_status\"; fi", + " cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1))", + " \(policy.limitReachedCommand)", + "done", + ] + } + + private static func noProgressShellPolicy() -> ( + configurationLines: [String], + status: Int32, + limitReachedCommand: String + ) { + let format = String( + localized: "cli.sshPtyAttach.noProgressRetryLimitReached", + defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." + ).remoteCommandShellQuoted + return ( + configurationLines: [ + "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", + "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", + ], + status: bridgeClosedWithoutProgress.rawValue, + limitReachedCommand: "if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(format) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi" + ) + } + /// Classifies a textual bridge-establishment failure into its attach exit status. /// /// - Parameter rawDescription: The daemon or transport failure description. diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift index f3d3d9ed228a..d1cce01d7e95 100644 --- a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -102,9 +102,56 @@ struct SSHPTYAttachNoProgressRetryTests { ) } + @Test("A nested no-progress policy returns general retry statuses to its owner") + func nestedPolicyReturnsGeneralRetryStatus() throws { + let scenario = try Self.runNoProgressScenario( + namePrefix: "nested-boundary", + decisionLines: [ + " if [ \"$count\" -eq 3 ]; then exit \(SSHPTYAttachExitCode.bridgeClosedSessionRunning.rawValue); fi", + " exit \(SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue)", + ], + commandBuilder: Self.nestedPolicyCommand + ) + + #expect(!scenario.process.timedOut, Comment(rawValue: scenario.process.stderr)) + #expect( + scenario.process.status == SSHPTYAttachExitCode.bridgeClosedSessionRunning.rawValue, + Comment(rawValue: scenario.process.stderr) + ) + #expect(scenario.attempts == "3") + #expect( + scenario.policyLog == """ + 0/3 + 1/3 + 2/3 + + """ + ) + } + + @Test("A nested no-progress policy stops at the shared health budget") + func nestedPolicyStopsRepeatedNoProgress() throws { + let scenario = try Self.runNoProgressScenario( + namePrefix: "nested-exhaustion", + decisionLines: [ + " exit \(SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue)", + ], + commandBuilder: Self.nestedPolicyCommand + ) + + #expect(!scenario.process.timedOut, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.process.status == 1, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.attempts == "3") + #expect( + scenario.process.stderr.contains("made no progress after 3 attempts"), + Comment(rawValue: scenario.process.stderr) + ) + } + private static func runNoProgressScenario( namePrefix: String, - decisionLines: [String] + decisionLines: [String], + commandBuilder: ((URL) -> String)? = nil ) throws -> ScenarioResult { let fileManager = FileManager.default let root = fileManager.temporaryDirectory @@ -145,9 +192,11 @@ struct SSHPTYAttachNoProgressRetryTests { environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = "3" environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" + environment["CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY"] = "1" let process = Self.run( - command: SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), + command: commandBuilder?(fakeCLI) ?? + SSHPTYAttachStartupCommandBuilder.command(sessionID: "ssh-test-session"), environment: environment ) @@ -158,6 +207,18 @@ struct SSHPTYAttachNoProgressRetryTests { ) } + private static func shellQuote(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'" + } + + private static func nestedPolicyCommand(fakeCLI: URL) -> String { + let attachCommand = "\(shellQuote(fakeCLI.path)) ssh-pty-attach" + let script = SSHPTYAttachExitCode.noProgressRetryLoopLines( + command: attachCommand + ).joined(separator: "\n") + return "/bin/sh -c \(shellQuote(script))" + } + private static func writeShellFile(at url: URL, lines: [String]) throws { try (lines.joined(separator: "\n") + "\n").write(to: url, atomically: true, encoding: .utf8) } From a541bf5ea9b8ce803f1c79512ab10c78b8e3c389 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 22:17:38 -0700 Subject: [PATCH 08/37] fix: isolate stalled remote PTY attaches --- daemon/remote/cmd/cmuxd-remote/main.go | 151 +++++++++++- daemon/remote/cmd/cmuxd-remote/main_test.go | 229 ++++++++++++++++++ daemon/remote/cmd/cmuxd-remote/ws_pty.go | 86 ++++--- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 211 ++++++++++++++++ 4 files changed, 638 insertions(+), 39 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index daf99dc1b695..a9a2166a3cd9 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -100,7 +100,10 @@ type stdioFrameWriter struct { } type rpcServer struct { - mu sync.Mutex + mu sync.Mutex + // closed prevents an asynchronous attach from becoming owned after the + // connection teardown snapshot has already been drained. + closed bool nextStreamID uint64 nextSessionID uint64 streams map[string]*streamState @@ -112,6 +115,79 @@ type rpcServer struct { cliBridge *cloudCLIBridge } +type rpcRequestDispatcher struct { + ctx context.Context + cancelConnection context.CancelFunc + interruptRead func() + server *rpcServer + ptyAttachSlots chan struct{} + asyncErrors chan error +} + +func newRPCRequestDispatcher( + ctx context.Context, + cancelConnection context.CancelFunc, + interruptRead func(), + server *rpcServer, +) *rpcRequestDispatcher { + return &rpcRequestDispatcher{ + ctx: ctx, + cancelConnection: cancelConnection, + interruptRead: interruptRead, + server: server, + ptyAttachSlots: make(chan struct{}, maxConcurrentPTYAttachRPCsPerConnection), + asyncErrors: make(chan error, 1), + } +} + +func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { + // PTY allocation can block inside the operating system. Only pty.attach is + // allowed to overtake the otherwise-serialized request stream; both frame + // writers serialize the resulting concurrent response writes. + if req.Method != "pty.attach" { + return d.server.handleRequestAndWriteResponse(req) + } + + select { + case <-d.ctx.Done(): + return d.ctx.Err() + case d.ptyAttachSlots <- struct{}{}: + default: + return d.server.frameWriter.writeResponse(rpcResponse{ + ID: req.ID, + OK: false, + Error: &rpcError{ + Code: "unavailable", + Message: "too many PTY attach requests are already in progress", + }, + }) + } + + go func() { + defer func() { <-d.ptyAttachSlots }() + if err := d.server.handlePTYAttachAndWriteResponse(d.ctx, req); err != nil { + select { + case d.asyncErrors <- err: + default: + } + d.cancelConnection() + if d.interruptRead != nil { + d.interruptRead() + } + } + }() + return nil +} + +func (d *rpcRequestDispatcher) takeAsyncError() error { + select { + case err := <-d.asyncErrors: + return err + default: + return nil + } +} + type sessionAttachment struct { Cols int Rows int @@ -126,7 +202,10 @@ type sessionState struct { lastKnownRows int } -const maxRPCFrameBytes = 4 * 1024 * 1024 +const ( + maxRPCFrameBytes = 4 * 1024 * 1024 + maxConcurrentPTYAttachRPCsPerConnection = 32 +) func main() { if shouldRunCLIForInvocation(os.Args[0], os.Args[1:]) { @@ -306,6 +385,14 @@ func runRPCServer(stdin io.Reader, stdout io.Writer, ptyHub *wsPTYHub, ownsPTYHu frameWriter: writer, } defer server.closeAll() + connectionCtx, cancelConnection := context.WithCancel(context.Background()) + defer cancelConnection() + interruptRead := func() { + if closer, ok := stdin.(io.Closer); ok { + _ = closer.Close() + } + } + dispatcher := newRPCRequestDispatcher(connectionCtx, cancelConnection, interruptRead, server) reader := bufio.NewReaderSize(stdin, 64*1024) defer writer.flush() @@ -313,6 +400,9 @@ func runRPCServer(stdin io.Reader, stdout io.Writer, ptyHub *wsPTYHub, ownsPTYHu for { line, oversized, readErr := readRPCFrame(reader, maxRPCFrameBytes) if readErr != nil { + if asyncErr := dispatcher.takeAsyncError(); asyncErr != nil { + return asyncErr + } if errors.Is(readErr, io.EOF) { return nil } @@ -350,7 +440,7 @@ func runRPCServer(stdin io.Reader, stdout io.Writer, ptyHub *wsPTYHub, ownsPTYHu continue } - if err := server.handleRequestAndWriteResponse(req); err != nil { + if err := dispatcher.dispatch(req); err != nil { return err } } @@ -1131,7 +1221,9 @@ func handlePersistentDaemonConnWithAuthTimeout( return } } - _ = runRPCServerWithReader(reader, writer, hub, false, requestShutdown) + _ = runRPCServerWithReader(reader, writer, hub, false, requestShutdown, func() { + _ = conn.Close() + }) } func authenticatePersistentDaemonConn(reader *bufio.Reader, writer *stdioFrameWriter, verifier persistentDaemonTokenVerifier) error { @@ -1211,6 +1303,7 @@ func runRPCServerWithReader( ptyHub *wsPTYHub, ownsPTYHub bool, requestShutdown func(), + interruptRead func(), ) error { server := &rpcServer{ nextStreamID: 1, @@ -1222,11 +1315,17 @@ func runRPCServerWithReader( frameWriter: writer, } defer server.closeAll() + connectionCtx, cancelConnection := context.WithCancel(context.Background()) + defer cancelConnection() + dispatcher := newRPCRequestDispatcher(connectionCtx, cancelConnection, interruptRead, server) defer writer.flush() for { line, oversized, readErr := readRPCFrame(reader, maxRPCFrameBytes) if readErr != nil { + if asyncErr := dispatcher.takeAsyncError(); asyncErr != nil { + return asyncErr + } if errors.Is(readErr, io.EOF) { return nil } @@ -1277,7 +1376,7 @@ func runRPCServerWithReader( return nil } - if err := server.handleRequestAndWriteResponse(req); err != nil { + if err := dispatcher.dispatch(req); err != nil { return err } } @@ -1532,6 +1631,10 @@ func (s *rpcServer) handleRequestAndWriteResponse(req rpcRequest) error { return s.frameWriter.writeResponse(resp) } +func (s *rpcServer) handlePTYAttachAndWriteResponse(ctx context.Context, req rpcRequest) error { + return s.frameWriter.writeResponse(s.handlePTYAttachContext(ctx, req)) +} + func rpcRequestExpectsResponse(req rpcRequest) bool { // Only selected PTY attachment operations use JSON-RPC notification // semantics; all other id-less requests still get a response for compatibility. @@ -2079,6 +2182,10 @@ func (s *rpcServer) handleSessionStatus(req rpcRequest) rpcResponse { } func (s *rpcServer) handlePTYAttach(req rpcRequest) rpcResponse { + return s.handlePTYAttachContext(context.Background(), req) +} + +func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) rpcResponse { sessionID, ok := getStringParam(req.Params, "session_id") if !ok || strings.TrimSpace(sessionID) == "" { return rpcResponse{ @@ -2134,7 +2241,7 @@ func (s *rpcServer) handlePTYAttach(req rpcRequest) rpcResponse { } } attachment, attachmentCtx, sessionDone, err := hub.attachRPC( - context.Background(), + ctx, sessionID, attachmentID, cols, @@ -2154,7 +2261,28 @@ func (s *rpcServer) handlePTYAttach(req rpcRequest) rpcResponse { }, } } - s.trackPTYAttachment(attachment) + if err := ctx.Err(); err != nil { + hub.dropAttachment(attachment) + return rpcResponse{ + ID: req.ID, + OK: false, + Error: &rpcError{ + Code: ptyAttachErrorCode(requireExisting), + Message: err.Error(), + }, + } + } + if !s.trackPTYAttachment(attachment) { + hub.dropAttachment(attachment) + return rpcResponse{ + ID: req.ID, + OK: false, + Error: &rpcError{ + Code: ptyAttachErrorCode(requireExisting), + Message: "RPC connection closed before PTY attachment completed", + }, + } + } go s.ptyAttachmentPump(attachmentCtx, attachment, sessionDone) return rpcResponse{ @@ -2406,16 +2534,20 @@ func (s *rpcServer) ptyAttachmentPump(ctx context.Context, attachment *wsPTYAtta } } -func (s *rpcServer) trackPTYAttachment(attachment *wsPTYAttachment) { +func (s *rpcServer) trackPTYAttachment(attachment *wsPTYAttachment) bool { if attachment == nil { - return + return false } s.mu.Lock() defer s.mu.Unlock() + if s.closed { + return false + } if s.ptyAttachments == nil { s.ptyAttachments = map[string]*wsPTYAttachment{} } s.ptyAttachments[rpcPTYAttachmentKey(attachment)] = attachment + return true } func (s *rpcServer) untrackPTYAttachment(attachment *wsPTYAttachment) { @@ -2591,6 +2723,7 @@ func (s *rpcServer) dropStream(streamID string) { func (s *rpcServer) closeAll() { s.mu.Lock() + s.closed = true streams := make([]net.Conn, 0, len(s.streams)) for id, state := range s.streams { delete(s.streams, id) diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index fb9f1ca7d784..1e52d8ccb9e6 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -66,6 +66,31 @@ func (b *notifyingBuffer) String() string { return b.buffer.String() } +func waitForRPCResponseID(t *testing.T, output *notifyingBuffer, id float64, timeout time.Duration) map[string]any { + t.Helper() + deadline := time.NewTimer(timeout) + defer deadline.Stop() + for { + for _, line := range strings.Split(output.String(), "\n") { + if strings.TrimSpace(line) == "" { + continue + } + var frame map[string]any + if err := json.Unmarshal([]byte(line), &frame); err != nil { + continue + } + if frame["id"] == id { + return frame + } + } + select { + case <-output.notify: + case <-deadline.C: + t.Fatalf("timed out waiting for RPC response id %.0f; output=%q", id, output.String()) + } + } +} + func startPersistentDaemonForTest(t *testing.T, token string) (string, func()) { return startPersistentDaemonWithVerifierForTest(t, persistentDaemonFixedTokenVerifier(token)) } @@ -1148,6 +1173,210 @@ func TestAuthenticatePersistentDaemonServerReadDeadline(t *testing.T) { } } +func TestStdioRPCStalledPTYAttachDoesNotBlockHealthyAttach(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + const healthySessionID = "transport-healthy" + if _, _, _, err := hub.attachRPC( + context.Background(), + healthySessionID, + "seed", + 80, + 24, + "sleep 30", + "seed-token", + false, + false, + ); err != nil { + t.Fatalf("seed healthy PTY session: %v", err) + } + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { + _ = stdinWriter.Close() + select { + case <-releaseStart: + default: + close(releaseStart) + } + }) + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "transport-stalled", + "attachment_id": "stalled", + "client_attachment_token": "stalled-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("stalled PTY attach never reached PTY allocation") + } + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 2, + Method: "pty.attach", + Params: map[string]any{ + "session_id": healthySessionID, + "attachment_id": "healthy", + "client_attachment_token": "healthy-token", + "cols": 80, + "rows": 24, + "require_existing": true, + }, + }) + response := waitForRPCResponseID(t, output, 2, time.Second) + if ok, _ := response["ok"].(bool); !ok { + t.Fatalf("healthy attach behind stalled attach failed: %v", response) + } + if strings.Contains(output.String(), `"id":1`) { + t.Fatalf("stalled attach unexpectedly completed before release: %q", output.String()) + } +} + +func TestStdioRPCDisconnectCancelsSameSessionAttachWaiter(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { + _ = stdinWriter.Close() + select { + case <-releaseStart: + default: + close(releaseStart) + } + }) + + writer := bufio.NewWriter(stdinWriter) + attachRequest := func(id int, attachmentID string) { + writePersistentTestFrame(t, writer, rpcRequest{ + ID: id, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "disconnect-stalled", + "attachment_id": attachmentID, + "client_attachment_token": attachmentID + "-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + } + attachRequest(1, "owner") + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("owner attach never reached PTY allocation") + } + attachRequest(2, "waiter") + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 3, + Method: "ping", + }) + ping := waitForRPCResponseID(t, output, 3, time.Second) + if ok, _ := ping["ok"].(bool); !ok { + t.Fatalf("ping behind same-session waiter failed: %v", ping) + } + + if err := stdinWriter.Close(); err != nil { + t.Fatalf("close RPC input: %v", err) + } + select { + case err := <-serverDone: + if err != nil { + t.Fatalf("stdio RPC server returned error after EOF: %v", err) + } + case <-time.After(time.Second): + t.Fatal("stdio RPC server did not return after EOF") + } + + close(releaseStart) + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(5 * time.Millisecond) + defer ticker.Stop() + for { + hub.mu.Lock() + _, starting := hub.startingSessions[persistentPTYSessionKey("disconnect-stalled")] + _, published := hub.sessions[persistentPTYSessionKey("disconnect-stalled")] + hub.mu.Unlock() + if !starting { + if published { + t.Fatal("PTY session was published after its RPC connection closed") + } + return + } + select { + case <-ticker.C: + case <-deadline.C: + t.Fatal("stalled PTY start did not finish after release") + } + } +} + +func TestStdioRPCAsyncAttachWriteFailureInterruptsReadLoop(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + stdinReader, stdinWriter := io.Pipe() + t.Cleanup(func() { _ = stdinWriter.Close() }) + writeErr := errors.New("async attach response write failed") + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, authErrorWriter{err: writeErr}, hub, false) + }() + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{}, + }) + select { + case err := <-serverDone: + if !errors.Is(err, writeErr) { + t.Fatalf("stdio RPC server error = %v, want async write error", err) + } + case <-time.After(time.Second): + t.Fatal("async attach write failure did not interrupt the stdio read loop") + } +} + func TestPersistentStdioProxyReturnsWhenDaemonClosesFirst(t *testing.T) { client, server := net.Pipe() stdinReader, stdinWriter := io.Pipe() diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 052fd939ec45..4638568b6a22 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -98,17 +98,18 @@ var ( ) const ( - defaultPTYCols = 80 - defaultPTYRows = 24 - maxPTYDimension = 65535 - defaultWebSocketScrollbackCap = 1 << 20 - defaultWebSocketReplayChunkBytes = 48 * 1024 - defaultWebSocketWriteQueueCap = 256 - defaultPTYInputQueueCap = 256 - defaultPTYInputChunkBytes = 16 * 1024 - defaultWebSocketWriteTimeout = 10 * time.Second - defaultWebSocketSessionIdleTTL = 24 * time.Hour - standardExecutablePath = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" + defaultPTYCols = 80 + defaultPTYRows = 24 + maxPTYDimension = 65535 + defaultWebSocketScrollbackCap = 1 << 20 + defaultWebSocketReplayChunkBytes = 48 * 1024 + defaultWebSocketWriteQueueCap = 256 + defaultPTYInputQueueCap = 256 + defaultPTYInputChunkBytes = 16 * 1024 + defaultWebSocketWriteTimeout = 10 * time.Second + defaultWebSocketSessionIdleTTL = 24 * time.Hour + maxConcurrentPTYSessionStartOwnersPerHub = 16 + standardExecutablePath = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" ) type wsPTYOutgoingFrame struct { @@ -210,14 +211,17 @@ type wsPTYHub struct { // startup run without mu. Callers for the same key join that start; callers // for healthy or unrelated sessions never wait behind it. startingSessions map[wsPTYSessionKey]*wsPTYSessionStart - closed bool - closedCh chan struct{} - nextAttachmentID uint64 - nextAnonymousID uint64 - shell string - stderr io.Writer - scrollbackLimit int - sessionIdleTTL time.Duration + // PTY startup is not context-cancellable once inside the operating system, + // so bound the number of start owners that can survive client teardown. + sessionStartSlots chan struct{} + closed bool + closedCh chan struct{} + nextAttachmentID uint64 + nextAnonymousID uint64 + shell string + stderr io.Writer + scrollbackLimit int + sessionIdleTTL time.Duration // openPTY allocates a PTY master/slave pair. It defaults to creack/pty.Open // (which opens /dev/ptmx) and exists as a field so tests can simulate a // hardened devpts where allocation is denied. @@ -238,14 +242,15 @@ func newWebSocketPTYHub(cfg wsPTYServerConfig, stderr io.Writer) *wsPTYHub { idleTTL = defaultWebSocketSessionIdleTTL } return &wsPTYHub{ - sessions: map[wsPTYSessionKey]*wsPTYSession{}, - startingSessions: map[wsPTYSessionKey]*wsPTYSessionStart{}, - closedCh: make(chan struct{}), - shell: strings.TrimSpace(cfg.Shell), - stderr: stderr, - scrollbackLimit: limit, - sessionIdleTTL: idleTTL, - openPTY: pty.Open, + sessions: map[wsPTYSessionKey]*wsPTYSession{}, + startingSessions: map[wsPTYSessionKey]*wsPTYSessionStart{}, + sessionStartSlots: make(chan struct{}, maxConcurrentPTYSessionStartOwnersPerHub), + closedCh: make(chan struct{}), + shell: strings.TrimSpace(cfg.Shell), + stderr: stderr, + scrollbackLimit: limit, + sessionIdleTTL: idleTTL, + openPTY: pty.Open, } } @@ -623,6 +628,7 @@ func handleWebSocketRPC(w http.ResponseWriter, r *http.Request, cfg wsPTYServerC return } + connectionCtx, cancelConnection := context.WithCancel(r.Context()) server := &rpcServer{ nextStreamID: 1, nextSessionID: 1, @@ -634,19 +640,25 @@ func handleWebSocketRPC(w http.ResponseWriter, r *http.Request, cfg wsPTYServerC frameWriter: &wsRPCFrameWriter{ conn: conn, writeMu: writeMu, - ctx: r.Context(), + ctx: connectionCtx, }, } + dispatcher := newRPCRequestDispatcher(connectionCtx, cancelConnection, nil, server) unregisterCLI := func() {} if cfg.CLIBridge != nil { unregisterCLI = cfg.CLIBridge.register(server) } defer unregisterCLI() defer server.closeAll() + defer cancelConnection() for { - msgType, payload, err := conn.Read(r.Context()) + msgType, payload, err := conn.Read(connectionCtx) if err != nil { + if dispatcher.takeAsyncError() != nil { + _ = conn.Close(websocket.StatusInternalError, "write failed") + return + } _ = conn.Close(websocket.StatusNormalClosure, "closed") return } @@ -675,7 +687,7 @@ func handleWebSocketRPC(w http.ResponseWriter, r *http.Request, cfg wsPTYServerC continue } - if err := server.handleRequestAndWriteResponse(req); err != nil { + if err := dispatcher.dispatch(req); err != nil { _ = conn.Close(websocket.StatusInternalError, "write failed") return } @@ -877,11 +889,18 @@ func (h *wsPTYHub) prepareAttachment( return nil, nil, nil, fmt.Errorf("persistent PTY session %q is not running", sessionID) } + select { + case h.sessionStartSlots <- struct{}{}: + default: + h.mu.Unlock() + return nil, nil, nil, errors.New("too many PTY sessions are already starting") + } start := &wsPTYSessionStart{done: make(chan struct{})} h.startingSessions[sessionKey] = start h.mu.Unlock() startedSession, startErr := h.startSession(sessionKey, sessionID, cols, rows, command) + <-h.sessionStartSlots discardStartedSession := false h.mu.Lock() @@ -891,6 +910,9 @@ func (h *wsPTYHub) prepareAttachment( case h.closed: startErr = errWSPTYHubClosed discardStartedSession = true + case ctx.Err() != nil: + startErr = ctx.Err() + discardStartedSession = true case existingSession != nil && !existingSession.closed: discardStartedSession = true default: @@ -913,6 +935,10 @@ func (h *wsPTYHub) prepareAttachment( } } + if err := ctx.Err(); err != nil { + h.mu.Unlock() + return nil, nil, nil, err + } if attachmentID == "" { attachmentID = fmt.Sprintf("att-%d", h.nextAttachmentID) h.nextAttachmentID++ diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index eecf21d46405..d72ba07d978c 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -320,6 +320,80 @@ func TestAttachRPCConcurrentSameSessionStartsOnce(t *testing.T) { } } +func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + startEntered := make(chan struct{}, maxConcurrentPTYSessionStartOwnersPerHub) + releaseStarts := make(chan struct{}) + released := false + t.Cleanup(func() { + if !released { + close(releaseStarts) + } + }) + hub.openPTY = func() (*os.File, *os.File, error) { + startEntered <- struct{}{} + <-releaseStarts + return nil, nil, errors.New("test PTY start released") + } + + results := make(chan error, maxConcurrentPTYSessionStartOwnersPerHub) + for i := 0; i < maxConcurrentPTYSessionStartOwnersPerHub; i++ { + go func(index int) { + _, _, _, err := hub.attachRPC( + context.Background(), + "bounded-start-"+strconv.Itoa(index), + "attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + results <- err + }(i) + } + for i := 0; i < maxConcurrentPTYSessionStartOwnersPerHub; i++ { + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatalf("PTY start %d did not enter allocation", i+1) + } + } + + excessResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + context.Background(), + "bounded-start-excess", + "attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + excessResult <- err + }() + select { + case err := <-excessResult: + if err == nil || !strings.Contains(err.Error(), "too many PTY sessions") { + t.Fatalf("excess PTY start error = %v, want bounded unavailable error", err) + } + case <-time.After(time.Second): + t.Fatal("excess PTY start blocked instead of failing immediately") + } + + released = true + close(releaseStarts) + for i := 0; i < maxConcurrentPTYSessionStartOwnersPerHub; i++ { + <-results + } +} + func TestCloseAllDoesNotWaitForStalledSessionStart(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) @@ -385,6 +459,143 @@ func TestCloseAllDoesNotWaitForStalledSessionStart(t *testing.T) { } } +func TestWebSocketRPCStalledPTYAttachDoesNotBlockHealthyAttach(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + const healthySessionID = "ws-rpc-healthy" + if _, _, _, err := hub.attachRPC( + context.Background(), + healthySessionID, + "seed", + 80, + 24, + "sleep 30", + "seed-token", + false, + false, + ); err != nil { + t.Fatalf("seed healthy PTY session: %v", err) + } + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + t.Cleanup(func() { + select { + case <-releaseStart: + default: + close(releaseStart) + } + }) + + rpcLeasePath := filepath.Join(t.TempDir(), "rpc-lease.json") + const authToken = "ws-rpc-token" + const authSessionID = "ws-rpc-client" + writeTestLease(t, rpcLeasePath, authToken, authSessionID, true, time.Now().Add(time.Minute)) + server := httptest.NewServer(newWebSocketPTYHandler(wsPTYServerConfig{ + PTYAuthLeaseFile: filepath.Join(t.TempDir(), "unused-pty-lease.json"), + RPCAuthLeaseFile: rpcLeasePath, + Shell: "/bin/sh", + PTYHub: hub, + }, io.Discard)) + t.Cleanup(server.Close) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/rpc" + conn, _, err := websocket.Dial(ctx, wsURL, nil) + if err != nil { + t.Fatalf("dial WebSocket RPC: %v", err) + } + t.Cleanup(func() { _ = conn.Close(websocket.StatusNormalClosure, "done") }) + + authPayload, err := json.Marshal(wsAuthFrame{ + Type: "auth", + Token: authToken, + SessionID: authSessionID, + }) + if err != nil { + t.Fatalf("marshal WebSocket RPC auth: %v", err) + } + if err := conn.Write(ctx, websocket.MessageText, authPayload); err != nil { + t.Fatalf("write WebSocket RPC auth: %v", err) + } + if _, payload, err := conn.Read(ctx); err != nil { + t.Fatalf("read WebSocket RPC ready: %v", err) + } else if !strings.Contains(string(payload), `"ready"`) { + t.Fatalf("unexpected WebSocket RPC ready frame: %s", payload) + } + + writeRequest := func(req rpcRequest) { + t.Helper() + payload, err := json.Marshal(req) + if err != nil { + t.Fatalf("marshal WebSocket RPC request: %v", err) + } + if err := conn.Write(ctx, websocket.MessageText, payload); err != nil { + t.Fatalf("write WebSocket RPC request: %v", err) + } + } + writeRequest(rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "ws-rpc-stalled", + "attachment_id": "stalled", + "client_attachment_token": "stalled-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("stalled WebSocket RPC attach never reached PTY allocation") + } + writeRequest(rpcRequest{ + ID: 2, + Method: "pty.attach", + Params: map[string]any{ + "session_id": healthySessionID, + "attachment_id": "healthy", + "client_attachment_token": "healthy-token", + "cols": 80, + "rows": 24, + "require_existing": true, + }, + }) + + for { + msgType, payload, err := conn.Read(ctx) + if err != nil { + t.Fatalf("read WebSocket RPC response: %v", err) + } + if msgType != websocket.MessageText { + continue + } + var frame map[string]any + if err := json.Unmarshal(payload, &frame); err != nil { + t.Fatalf("decode WebSocket RPC frame %q: %v", payload, err) + } + if frame["id"] == float64(1) { + t.Fatalf("stalled WebSocket RPC attach completed before release: %v", frame) + } + if frame["id"] == float64(2) { + if ok, _ := frame["ok"].(bool); !ok { + t.Fatalf("healthy WebSocket RPC attach failed: %v", frame) + } + return + } + } +} + func TestServeWSRequiresExplicitLeaseFile(t *testing.T) { var stderr bytes.Buffer code := run([]string{"serve", "--ws", "--listen", "127.0.0.1:0"}, strings.NewReader(""), &bytes.Buffer{}, &stderr) From 77e3de70f02952994ac6d00548f96c26f6c96488 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 22:44:50 -0700 Subject: [PATCH 09/37] fix: close remote PTY attach teardown races --- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 10 +- Resources/Localizable.xcstrings | 19 ++- ...SHPTYAttachProbeReplyRegressionTests.swift | 1 + ...ISSHPTYAttachSessionLostRespawnTests.swift | 1 + .../SSHPTYAttachNoProgressRetryTests.swift | 24 ++- daemon/remote/cmd/cmuxd-remote/main.go | 36 +++-- daemon/remote/cmd/cmuxd-remote/main_test.go | 59 ++++++++ daemon/remote/cmd/cmuxd-remote/ws_pty.go | 20 ++- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 139 ++++++++++++++++++ 9 files changed, 292 insertions(+), 17 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift index 95d4c1f15f4b..fb51169bf54e 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -140,17 +140,21 @@ public enum SSHPTYAttachExitCode: Int32 { status: Int32, limitReachedCommand: String ) { - let format = String( - localized: "cli.sshPtyAttach.noProgressRetryLimitReached", + let pluralFormat = String( + localized: "cli.sshPtyAttach.noProgressRetryLimitReached.other", defaultValue: "[cmux] remote PTY bridge made no progress after %s attempts; stopping retries." ).remoteCommandShellQuoted + let singularFormat = String( + localized: "cli.sshPtyAttach.noProgressRetryLimitReached.one", + defaultValue: "[cmux] remote PTY bridge made no progress after %s attempt; stopping retries." + ).remoteCommandShellQuoted return ( configurationLines: [ "cmux_ssh_attach_no_progress_limit=\"${CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT:-3}\"", "case \"$cmux_ssh_attach_no_progress_limit\" in ''|*[!0-9]*|0*) cmux_ssh_attach_no_progress_limit=3 ;; esac", ], status: bridgeClosedWithoutProgress.rawValue, - limitReachedCommand: "if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \(format) \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi" + limitReachedCommand: "if [ \"$cmux_ssh_attach_no_progress_retry\" -ge \"$cmux_ssh_attach_no_progress_limit\" ]; then if [ \"$cmux_ssh_attach_no_progress_limit\" -eq 1 ]; then cmux_ssh_attach_limit_format=\(singularFormat); else cmux_ssh_attach_limit_format=\(pluralFormat); fi; printf '\\n\\033[31m%s\\033[0m\\n' \"$(printf \"$cmux_ssh_attach_limit_format\" \"$cmux_ssh_attach_no_progress_limit\")\" >&2 || true; exit 1; fi" ) } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 046cbfc37579..44333db577fd 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -50497,7 +50497,24 @@ } } }, - "cli.sshPtyAttach.noProgressRetryLimitReached": { + "cli.sshPtyAttach.noProgressRetryLimitReached.one": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "[cmux] remote PTY bridge made no progress after %s attempt; stopping retries." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "[cmux] リモート PTY ブリッジは %s 回試行しても進行しなかったため、再試行を停止します。" + } + } + } + }, + "cli.sshPtyAttach.noProgressRetryLimitReached.other": { "extractionState": "manual", "localizations": { "en": { diff --git a/cmuxTests/CLISSHPTYAttachProbeReplyRegressionTests.swift b/cmuxTests/CLISSHPTYAttachProbeReplyRegressionTests.swift index a4753961b391..541bb21f1422 100644 --- a/cmuxTests/CLISSHPTYAttachProbeReplyRegressionTests.swift +++ b/cmuxTests/CLISSHPTYAttachProbeReplyRegressionTests.swift @@ -1,4 +1,5 @@ import Darwin +import CmuxFoundation import Foundation import Testing diff --git a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift index faa6dbd39583..c67b353bca5c 100644 --- a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift +++ b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift @@ -1,4 +1,5 @@ import Darwin +import CmuxFoundation import Foundation import XCTest diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift index d1cce01d7e95..59e37c21a453 100644 --- a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -148,9 +148,31 @@ struct SSHPTYAttachNoProgressRetryTests { ) } + @Test("A one-attempt health budget uses a singular diagnostic") + func oneAttemptBudgetUsesSingularDiagnostic() throws { + let scenario = try Self.runNoProgressScenario( + namePrefix: "singular-exhaustion", + decisionLines: [ + " exit \(SSHPTYAttachExitCode.bridgeClosedWithoutProgress.rawValue)", + ], + retryLimit: 1, + commandBuilder: Self.nestedPolicyCommand + ) + + #expect(!scenario.process.timedOut, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.process.status == 1, Comment(rawValue: scenario.process.stderr)) + #expect(scenario.attempts == "1") + #expect( + scenario.process.stderr.contains("made no progress after 1 attempt;"), + Comment(rawValue: scenario.process.stderr) + ) + #expect(!scenario.process.stderr.contains("1 attempts")) + } + private static func runNoProgressScenario( namePrefix: String, decisionLines: [String], + retryLimit: Int = 3, commandBuilder: ((URL) -> String)? = nil ) throws -> ScenarioResult { let fileManager = FileManager.default @@ -189,7 +211,7 @@ struct SSHPTYAttachNoProgressRetryTests { environment["CMUX_SURFACE_ID"] = "22222222-2222-2222-2222-222222222222" environment["CMUX_TEST_ATTEMPT_FILE"] = attemptFile.path environment["CMUX_TEST_POLICY_LOG"] = policyLog.path - environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = "3" + environment["CMUX_SSH_PTY_NO_PROGRESS_RETRY_LIMIT"] = String(retryLimit) environment["CMUX_SSH_RECONNECT_DELAY_SECONDS"] = "1" environment["CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS"] = "1" environment["CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY"] = "1" diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index a9a2166a3cd9..8ff3cb077db8 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -384,9 +384,12 @@ func runRPCServer(stdin io.Reader, stdout io.Writer, ptyHub *wsPTYHub, ownsPTYHu ownsPTYHub: ownsPTYHub, frameWriter: writer, } - defer server.closeAll() connectionCtx, cancelConnection := context.WithCancel(context.Background()) - defer cancelConnection() + defer func() { + cancelConnection() + server.closeAll() + _ = writer.flush() + }() interruptRead := func() { if closer, ok := stdin.(io.Closer); ok { _ = closer.Close() @@ -395,7 +398,6 @@ func runRPCServer(stdin io.Reader, stdout io.Writer, ptyHub *wsPTYHub, ownsPTYHu dispatcher := newRPCRequestDispatcher(connectionCtx, cancelConnection, interruptRead, server) reader := bufio.NewReaderSize(stdin, 64*1024) - defer writer.flush() for { line, oversized, readErr := readRPCFrame(reader, maxRPCFrameBytes) @@ -1314,11 +1316,13 @@ func runRPCServerWithReader( ownsPTYHub: ownsPTYHub, frameWriter: writer, } - defer server.closeAll() connectionCtx, cancelConnection := context.WithCancel(context.Background()) - defer cancelConnection() + defer func() { + cancelConnection() + server.closeAll() + _ = writer.flush() + }() dispatcher := newRPCRequestDispatcher(connectionCtx, cancelConnection, interruptRead, server) - defer writer.flush() for { line, oversized, readErr := readRPCFrame(reader, maxRPCFrameBytes) @@ -1632,7 +1636,11 @@ func (s *rpcServer) handleRequestAndWriteResponse(req rpcRequest) error { } func (s *rpcServer) handlePTYAttachAndWriteResponse(ctx context.Context, req rpcRequest) error { - return s.frameWriter.writeResponse(s.handlePTYAttachContext(ctx, req)) + response := s.handlePTYAttachContext(ctx, req) + if ctx.Err() != nil { + return nil + } + return s.frameWriter.writeResponse(response) } func rpcRequestExpectsResponse(req rpcRequest) bool { @@ -2257,7 +2265,7 @@ func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) OK: false, Error: &rpcError{ Code: ptyAttachErrorCode(requireExisting), - Message: err.Error(), + Message: ptyAttachErrorMessage(err), }, } } @@ -2268,7 +2276,7 @@ func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) OK: false, Error: &rpcError{ Code: ptyAttachErrorCode(requireExisting), - Message: err.Error(), + Message: ptyAttachErrorMessage(err), }, } } @@ -2297,6 +2305,13 @@ func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) } } +func ptyAttachErrorMessage(err error) string { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return "RPC connection closed before PTY attachment completed" + } + return err.Error() +} + func ptyAttachErrorCode(requireExisting bool) string { if requireExisting { return "pty_session_not_found" @@ -2506,6 +2521,9 @@ func (s *rpcServer) ptyAttachmentPump(ctx context.Context, attachment *wsPTYAtta for { select { case <-ctx.Done(): + if s.ptyHub != nil { + s.ptyHub.dropAttachment(attachment) + } _ = s.frameWriter.writeEvent(rpcPTYExitEvent(attachment)) return case <-sessionDone: diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index 1e52d8ccb9e6..8cf91b17b36d 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1377,6 +1377,65 @@ func TestStdioRPCAsyncAttachWriteFailureInterruptsReadLoop(t *testing.T) { } } +func TestPTYAttachmentPumpCancellationDropsHubAttachment(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{ + Shell: "/bin/sh", + SessionIdleTTL: time.Hour, + }, io.Discard) + t.Cleanup(hub.closeAll) + + ctx, cancel := context.WithCancel(context.Background()) + attachment, attachmentCtx, sessionDone, err := hub.attachRPC( + ctx, + "pump-canceled-session", + "pump-canceled-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + if err != nil { + t.Fatalf("attach PTY: %v", err) + } + server := &rpcServer{ + ptyHub: hub, + frameWriter: &stdioFrameWriter{writer: bufio.NewWriter(io.Discard)}, + } + if !server.trackPTYAttachment(attachment) { + t.Fatal("track PTY attachment") + } + pumpDone := make(chan struct{}) + go func() { + server.ptyAttachmentPump(attachmentCtx, attachment, sessionDone) + close(pumpDone) + }() + + cancel() + select { + case <-pumpDone: + case <-time.After(time.Second): + t.Fatal("PTY attachment pump did not stop after context cancellation") + } + + hub.mu.Lock() + session := hub.sessions[persistentPTYSessionKey("pump-canceled-session")] + attachmentCount := 0 + hasIdleTimer := false + if session != nil { + attachmentCount = len(session.attachments) + hasIdleTimer = session.idleTimer != nil + } + hub.mu.Unlock() + if attachmentCount != 0 { + t.Fatalf("hub attachments after pump cancellation = %d, want 0", attachmentCount) + } + if !hasIdleTimer { + t.Fatal("pump cancellation did not schedule the empty session for idle reaping") + } +} + func TestPersistentStdioProxyReturnsWhenDaemonClosesFirst(t *testing.T) { client, server := net.Pipe() stdinReader, stdinWriter := io.Pipe() diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 4638568b6a22..e6f15e900248 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -200,8 +200,11 @@ type wsPTYSession struct { } type wsPTYSessionStart struct { - done chan struct{} - err error + done chan struct{} + err error + // waiters counts joiners only until the owner publishes or discards the + // completed start; the count is never consulted after done closes. + waiters int } type wsPTYHub struct { @@ -870,6 +873,7 @@ func (h *wsPTYHub) prepareAttachment( break } if start := h.startingSessions[sessionKey]; start != nil { + start.waiters++ closedCh := h.closedCh h.mu.Unlock() select { @@ -878,8 +882,14 @@ func (h *wsPTYHub) prepareAttachment( return nil, nil, nil, start.err } case <-closedCh: + h.mu.Lock() + start.waiters-- + h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed case <-ctx.Done(): + h.mu.Lock() + start.waiters-- + h.mu.Unlock() return nil, nil, nil, ctx.Err() } continue @@ -910,13 +920,14 @@ func (h *wsPTYHub) prepareAttachment( case h.closed: startErr = errWSPTYHubClosed discardStartedSession = true - case ctx.Err() != nil: + case ctx.Err() != nil && start.waiters == 0: startErr = ctx.Err() discardStartedSession = true case existingSession != nil && !existingSession.closed: discardStartedSession = true default: h.sessions[sessionKey] = startedSession + h.scheduleIdleReapLocked(startedSession) } } start.err = startErr @@ -936,6 +947,9 @@ func (h *wsPTYHub) prepareAttachment( } if err := ctx.Err(); err != nil { + if len(session.attachments) == 0 { + h.scheduleIdleReapLocked(session) + } h.mu.Unlock() return nil, nil, nil, err } diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index d72ba07d978c..e6384d9e1cab 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -41,6 +41,22 @@ func (c doneObservedContext) Done() <-chan struct{} { return c.Context.Done() } +type cancelAfterFirstErrContext struct { + context.Context + cancel context.CancelFunc + calls atomic.Int32 +} + +func (c *cancelAfterFirstErrContext) Err() error { + if err := c.Context.Err(); err != nil { + return err + } + if c.calls.Add(1) == 1 { + c.cancel() + } + return nil +} + func newTestWebSocketPTYServer(t *testing.T, leasePath string) (*httptest.Server, *wsPTYHub) { t.Helper() stderr := &bytes.Buffer{} @@ -320,6 +336,129 @@ func TestAttachRPCConcurrentSameSessionStartsOnce(t *testing.T) { } } +func TestAttachRPCSharedStartSurvivesOwnerCancellation(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + ownerCtx, cancelOwner := context.WithCancel(context.Background()) + ownerResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + ownerCtx, + "owner-canceled-session", + "owner", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + ownerResult <- err + }() + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("start owner never attempted PTY allocation") + } + + waiterJoined := make(chan struct{}, 1) + waiterResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + doneObservedContext{Context: context.Background(), observed: waiterJoined}, + "owner-canceled-session", + "waiter", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + waiterResult <- err + }() + select { + case <-waiterJoined: + case <-time.After(time.Second): + close(releaseStart) + t.Fatal("live waiter did not join the owner's in-flight start") + } + + cancelOwner() + close(releaseStart) + if err := <-ownerResult; !errors.Is(err, context.Canceled) { + t.Fatalf("canceled start owner error = %v, want context canceled", err) + } + if err := <-waiterResult; err != nil { + t.Fatalf("live waiter failed after start owner cancellation: %v", err) + } + + hub.mu.Lock() + session := hub.sessions[persistentPTYSessionKey("owner-canceled-session")] + attachmentCount := 0 + if session != nil { + attachmentCount = len(session.attachments) + } + hub.mu.Unlock() + if attachmentCount != 1 { + t.Fatalf("shared session attachments = %d, want live waiter only", attachmentCount) + } +} + +func TestAttachRPCLateCancellationSchedulesPublishedSessionReap(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{ + Shell: "/bin/sh", + SessionIdleTTL: time.Hour, + }, io.Discard) + t.Cleanup(hub.closeAll) + + baseCtx, cancel := context.WithCancel(context.Background()) + ctx := &cancelAfterFirstErrContext{Context: baseCtx, cancel: cancel} + _, _, _, err := hub.attachRPC( + ctx, + "late-canceled-session", + "late-canceled-attachment", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + if !errors.Is(err, context.Canceled) { + t.Fatalf("late-canceled attach error = %v, want context canceled", err) + } + + hub.mu.Lock() + session := hub.sessions[persistentPTYSessionKey("late-canceled-session")] + attachmentCount := 0 + hasIdleTimer := false + if session != nil { + attachmentCount = len(session.attachments) + hasIdleTimer = session.idleTimer != nil + } + hub.mu.Unlock() + if session == nil { + t.Fatal("late-canceled published session was not retained for idle reaping") + } + if attachmentCount != 0 { + t.Fatalf("late-canceled session attachments = %d, want 0", attachmentCount) + } + if !hasIdleTimer { + t.Fatal("late-canceled published session has no idle reap timer") + } +} + func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) From 10aacca0a1ac4a30dfb539e8a6750ba042447079 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 23:09:44 -0700 Subject: [PATCH 10/37] fix: preserve remote PTY session generations --- daemon/remote/cmd/cmuxd-remote/main_test.go | 118 +++++++++++++++++ daemon/remote/cmd/cmuxd-remote/ws_pty.go | 123 +++++++++++++++++- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 87 +++++++++++++ 3 files changed, 321 insertions(+), 7 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index 8cf91b17b36d..6b84aa7741c0 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -17,6 +17,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "syscall" "testing" "time" @@ -1255,6 +1256,123 @@ func TestStdioRPCStalledPTYAttachDoesNotBlockHealthyAttach(t *testing.T) { } } +func TestStdioRPCCloseOvertakesStalledPTYStart(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { + _ = stdinWriter.Close() + select { + case <-releaseStart: + default: + close(releaseStart) + } + }) + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "close-stalled-start", + "attachment_id": "stalled", + "client_attachment_token": "stalled-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("PTY attach never reached its stalled allocation") + } + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 2, + Method: "pty.close", + Params: map[string]any{ + "session_id": "close-stalled-start", + }, + }) + closeResponse := waitForRPCResponseID(t, output, 2, time.Second) + if ok, _ := closeResponse["ok"].(bool); !ok { + t.Fatalf("close pending PTY start failed: %v", closeResponse) + } + + close(releaseStart) + attachResponse := waitForRPCResponseID(t, output, 1, 5*time.Second) + if ok, _ := attachResponse["ok"].(bool); ok { + t.Fatalf("closed pending PTY start unexpectedly attached: %v", attachResponse) + } + hub.mu.Lock() + _, published := hub.sessions[persistentPTYSessionKey("close-stalled-start")] + hub.mu.Unlock() + if published { + t.Fatal("closed pending PTY start was published") + } +} + +func TestStdioRPCShortCommandStartsExactlyOnce(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + var startCount atomic.Int32 + hub.openPTY = func() (*os.File, *os.File, error) { + startCount.Add(1) + return openPTY() + } + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { _ = stdinWriter.Close() }) + + writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "short-command", + "attachment_id": "short", + "client_attachment_token": "short-token", + "cols": 80, + "rows": 24, + "command": "exit 0", + }, + }) + response := waitForRPCResponseID(t, output, 1, 5*time.Second) + if ok, _ := response["ok"].(bool); !ok { + t.Fatalf("short command attach failed: %v", response) + } + exitEvent := waitForRPCEvent(t, output, 0, func(event map[string]any) bool { + return event["event"] == "pty.exit" + }) + if exitEvent["session_id"] != "short-command" { + t.Fatalf("short command exit event = %v", exitEvent) + } + if got := startCount.Load(); got != 1 { + t.Fatalf("short command PTY start count = %d, want exactly 1", got) + } +} + func TestStdioRPCDisconnectCancelsSameSessionAttachWaiter(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index e6f15e900248..67c557dbcfb9 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -165,6 +165,16 @@ const ( wsPTYAnonymousSession ) +type wsPTYSessionInitialPhase uint8 + +// The initial phase keeps a process that exits during attach startup visible +// until every caller coalesced onto that generation can observe ready + exit. +const ( + wsPTYSessionInitialActive wsPTYSessionInitialPhase = iota + wsPTYSessionAwaitingInitialAttachment + wsPTYSessionFinishedBeforeInitialAttachment +) + func persistentPTYSessionKey(sessionID string) wsPTYSessionKey { return wsPTYSessionKey{kind: wsPTYPersistentSession, sessionID: sessionID} } @@ -197,14 +207,20 @@ type wsPTYSession struct { closeTTYOnce sync.Once closePTYOnce sync.Once terminateOnce sync.Once + initialPhase wsPTYSessionInitialPhase + // initialClaims counts the start owner and live joiners that must consume + // this exact generation rather than interpreting an early exit as absence. + initialClaims int } type wsPTYSessionStart struct { done chan struct{} err error + session *wsPTYSession // waiters counts joiners only until the owner publishes or discards the // completed start; the count is never consulted after done closes. - waiters int + waiters int + closeRequested bool } type wsPTYHub struct { @@ -862,14 +878,29 @@ func (h *wsPTYHub) prepareAttachment( h.mu.Unlock() var session *wsPTYSession + var claimedSession *wsPTYSession + ownsInitialClaim := false for { h.mu.Lock() if h.closed { h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed } + if claimedSession != nil { + session = claimedSession + if h.sessions[sessionKey] != session || session.closed { + h.releaseInitialClaimLocked(session) + h.mu.Unlock() + return nil, nil, nil, fmt.Errorf("persistent PTY session %q closed before attachment completed", sessionID) + } + break + } session = h.sessions[sessionKey] if session != nil && !session.closed { + if session.initialPhase == wsPTYSessionFinishedBeforeInitialAttachment { + h.mu.Unlock() + return nil, nil, nil, fmt.Errorf("persistent PTY session %q is no longer running", sessionID) + } break } if start := h.startingSessions[sessionKey]; start != nil { @@ -881,14 +912,24 @@ func (h *wsPTYHub) prepareAttachment( if start.err != nil { return nil, nil, nil, start.err } + claimedSession = start.session + ownsInitialClaim = claimedSession != nil case <-closedCh: h.mu.Lock() - start.waiters-- + if start.session != nil { + h.releaseInitialClaimLocked(start.session) + } else { + start.waiters-- + } h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed case <-ctx.Done(): h.mu.Lock() - start.waiters-- + if start.session != nil { + h.releaseInitialClaimLocked(start.session) + } else { + start.waiters-- + } h.mu.Unlock() return nil, nil, nil, ctx.Err() } @@ -912,22 +953,35 @@ func (h *wsPTYHub) prepareAttachment( startedSession, startErr := h.startSession(sessionKey, sessionID, cols, rows, command) <-h.sessionStartSlots discardStartedSession := false + publishedStartedSession := false h.mu.Lock() delete(h.startingSessions, sessionKey) if startErr == nil { + ownerContextErr := ctx.Err() switch existingSession := h.sessions[sessionKey]; { case h.closed: startErr = errWSPTYHubClosed discardStartedSession = true - case ctx.Err() != nil && start.waiters == 0: - startErr = ctx.Err() + case start.closeRequested: + startErr = fmt.Errorf("persistent PTY session %q was closed while starting", sessionID) + discardStartedSession = true + case ownerContextErr != nil && start.waiters == 0: + startErr = ownerContextErr discardStartedSession = true case existingSession != nil && !existingSession.closed: discardStartedSession = true default: + startedSession.initialClaims = start.waiters + if ownerContextErr == nil { + startedSession.initialClaims++ + claimedSession = startedSession + ownsInitialClaim = true + } h.sessions[sessionKey] = startedSession h.scheduleIdleReapLocked(startedSession) + start.session = startedSession + publishedStartedSession = true } } start.err = startErr @@ -944,9 +998,18 @@ func (h *wsPTYHub) prepareAttachment( if startErr != nil { return nil, nil, nil, startErr } + if publishedStartedSession && !ownsInitialClaim { + return nil, nil, nil, ctx.Err() + } + if publishedStartedSession { + continue + } } if err := ctx.Err(); err != nil { + if ownsInitialClaim { + h.releaseInitialClaimLocked(session) + } if len(session.attachments) == 0 { h.scheduleIdleReapLocked(session) } @@ -989,6 +1052,9 @@ func (h *wsPTYHub) prepareAttachment( replay := append([]byte(nil), session.scrollback...) if ok := attachment.enqueueReady(sessionID); !ok { cancel() + if ownsInitialClaim { + h.releaseInitialClaimLocked(session) + } h.mu.Unlock() if superseded != nil { superseded.closeNow() @@ -997,14 +1063,25 @@ func (h *wsPTYHub) prepareAttachment( } if ok := enqueuePTYReplay(attachment, replay); !ok { cancel() + if ownsInitialClaim { + h.releaseInitialClaimLocked(session) + } h.mu.Unlock() if superseded != nil { superseded.closeNow() } return nil, nil, nil, errors.New("failed to queue replay frame") } - session.attachments[attachmentID] = attachment - shouldApplySize := h.recomputeSessionSizeLocked(session) + finishedBeforeInitialAttachment := session.initialPhase == wsPTYSessionFinishedBeforeInitialAttachment + shouldApplySize := false + if !finishedBeforeInitialAttachment { + session.attachments[attachmentID] = attachment + session.initialPhase = wsPTYSessionInitialActive + shouldApplySize = h.recomputeSessionSizeLocked(session) + } + if ownsInitialClaim { + h.releaseInitialClaimLocked(session) + } sessionDone := session.done h.mu.Unlock() @@ -1017,6 +1094,21 @@ func (h *wsPTYHub) prepareAttachment( return attachment, attachmentCtx, sessionDone, nil } +func (h *wsPTYHub) releaseInitialClaimLocked(session *wsPTYSession) { + if session == nil || session.initialClaims <= 0 { + return + } + session.initialClaims-- + if session.initialClaims != 0 || + session.initialPhase != wsPTYSessionFinishedBeforeInitialAttachment || + h.sessions[session.key] != session { + return + } + delete(h.sessions, session.key) + h.cancelIdleReapLocked(session) + session.closed = true +} + func (h *wsPTYHub) startSession(sessionKey wsPTYSessionKey, sessionID string, cols int, rows int, command string) (*wsPTYSession, error) { shellPath := resolvePTYShell(h.shell) trimmedCommand := strings.TrimSpace(command) @@ -1078,6 +1170,7 @@ func (h *wsPTYHub) startSession(sessionKey wsPTYSessionKey, sessionID string, co lastKnownRows: rows, input: make(chan wsPTYInputChunk, defaultPTYInputQueueCap), done: make(chan struct{}), + initialPhase: wsPTYSessionAwaitingInitialAttachment, } return session, nil } @@ -1375,6 +1468,11 @@ func (h *wsPTYHub) closeSessionByID(sessionID string) bool { sessionKey := persistentPTYSessionKey(sessionID) h.mu.Lock() + if start := h.startingSessions[sessionKey]; start != nil { + start.closeRequested = true + h.mu.Unlock() + return true + } session := h.sessions[sessionKey] if session == nil || session.closed { h.mu.Unlock() @@ -1650,6 +1748,17 @@ func (h *wsPTYHub) finishSession(session *wsPTYSession) { session.closePTYFiles() h.mu.Lock() + if session.initialPhase == wsPTYSessionAwaitingInitialAttachment { + session.initialPhase = wsPTYSessionFinishedBeforeInitialAttachment + close(session.done) + if session.initialClaims == 0 && h.sessions[session.key] == session { + delete(h.sessions, session.key) + h.cancelIdleReapLocked(session) + session.closed = true + } + h.mu.Unlock() + return + } if h.sessions[session.key] == session { delete(h.sessions, session.key) } diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index e6384d9e1cab..a09cefc66d4f 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -415,6 +415,89 @@ func TestAttachRPCSharedStartSurvivesOwnerCancellation(t *testing.T) { } } +func TestAttachRPCFastExitCoalescedWaitersShareGeneration(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + var startCount atomic.Int32 + hub.openPTY = func() (*os.File, *os.File, error) { + startCount.Add(1) + close(startEntered) + <-releaseStart + return openPTY() + } + + type attachResult struct { + attachment *wsPTYAttachment + sessionDone <-chan struct{} + err error + } + attach := func(ctx context.Context, attachmentID string) <-chan attachResult { + result := make(chan attachResult, 1) + go func() { + attachment, _, sessionDone, err := hub.attachRPC( + ctx, + "coalesced-fast-exit", + attachmentID, + 80, + 24, + "exit 0", + "", + false, + false, + ) + result <- attachResult{attachment: attachment, sessionDone: sessionDone, err: err} + }() + return result + } + + firstResult := attach(context.Background(), "first") + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("first fast-exit attach never attempted PTY allocation") + } + waiterJoined := make(chan struct{}, 1) + secondResult := attach( + doneObservedContext{Context: context.Background(), observed: waiterJoined}, + "second", + ) + select { + case <-waiterJoined: + case <-time.After(time.Second): + close(releaseStart) + t.Fatal("second fast-exit attach did not join the in-flight generation") + } + close(releaseStart) + + results := []attachResult{<-firstResult, <-secondResult} + for index, result := range results { + if result.err != nil { + t.Fatalf("coalesced fast-exit attach %d: %v", index+1, result.err) + } + if result.attachment == nil || result.sessionDone == nil { + t.Fatalf("coalesced fast-exit attach %d returned incomplete attachment", index+1) + } + select { + case <-result.sessionDone: + case <-time.After(5 * time.Second): + t.Fatalf("coalesced fast-exit attach %d did not observe session exit", index+1) + } + } + if got := startCount.Load(); got != 1 { + t.Fatalf("coalesced fast-exit PTY start count = %d, want exactly 1", got) + } + hub.mu.Lock() + _, retained := hub.sessions[persistentPTYSessionKey("coalesced-fast-exit")] + hub.mu.Unlock() + if retained { + t.Fatal("fast-exit generation remained after its final initial claim") + } +} + func TestAttachRPCLateCancellationSchedulesPublishedSessionReap(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{ Shell: "/bin/sh", @@ -457,6 +540,10 @@ func TestAttachRPCLateCancellationSchedulesPublishedSessionReap(t *testing.T) { if !hasIdleTimer { t.Fatal("late-canceled published session has no idle reap timer") } + + session.terminateProcesses() + session.closePTYFiles() + waitForHubSessionCount(t, hub, 0, 5*time.Second) } func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { From d96bc694fda276a3a5cae81ccee67712c04f5317 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 28 Jul 2026 23:47:20 -0700 Subject: [PATCH 11/37] fix: harden remote PTY lifecycle handoffs --- daemon/remote/cmd/cmuxd-remote/main.go | 49 +++++- daemon/remote/cmd/cmuxd-remote/main_test.go | 36 +++- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 100 ++++++++++- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 159 +++++++++++++++++- 4 files changed, 321 insertions(+), 23 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 8ff3cb077db8..95a57df2aba2 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -143,7 +143,9 @@ func newRPCRequestDispatcher( func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { // PTY allocation can block inside the operating system. Only pty.attach is // allowed to overtake the otherwise-serialized request stream; both frame - // writers serialize the resulting concurrent response writes. + // writers serialize the resulting concurrent response writes. Before + // reading the next request, wait only until the attach has reserved or + // selected its hub generation so a following pty.close cannot overtake it. if req.Method != "pty.attach" { return d.server.handleRequestAndWriteResponse(req) } @@ -163,9 +165,12 @@ func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { }) } + reservationReady := make(chan struct{}) go func() { defer func() { <-d.ptyAttachSlots }() - if err := d.server.handlePTYAttachAndWriteResponse(d.ctx, req); err != nil { + if err := d.server.handlePTYAttachAndWriteResponseWithReservation(d.ctx, req, func() { + close(reservationReady) + }); err != nil { select { case d.asyncErrors <- err: default: @@ -176,7 +181,12 @@ func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { } } }() - return nil + select { + case <-reservationReady: + return nil + case <-d.ctx.Done(): + return d.ctx.Err() + } } func (d *rpcRequestDispatcher) takeAsyncError() error { @@ -1636,7 +1646,15 @@ func (s *rpcServer) handleRequestAndWriteResponse(req rpcRequest) error { } func (s *rpcServer) handlePTYAttachAndWriteResponse(ctx context.Context, req rpcRequest) error { - response := s.handlePTYAttachContext(ctx, req) + return s.handlePTYAttachAndWriteResponseWithReservation(ctx, req, nil) +} + +func (s *rpcServer) handlePTYAttachAndWriteResponseWithReservation( + ctx context.Context, + req rpcRequest, + reservationReady func(), +) error { + response := s.handlePTYAttachContextWithReservation(ctx, req, reservationReady) if ctx.Err() != nil { return nil } @@ -2194,6 +2212,26 @@ func (s *rpcServer) handlePTYAttach(req rpcRequest) rpcResponse { } func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) rpcResponse { + return s.handlePTYAttachContextWithReservation(ctx, req, nil) +} + +func (s *rpcServer) handlePTYAttachContextWithReservation( + ctx context.Context, + req rpcRequest, + reservationReady func(), +) rpcResponse { + var reservationOnce sync.Once + notifyReservationReady := func() { + reservationOnce.Do(func() { + if reservationReady != nil { + reservationReady() + } + }) + } + // Validation and other errors before the hub owns a generation still need + // to release the serialized request reader. + defer notifyReservationReady() + sessionID, ok := getStringParam(req.Params, "session_id") if !ok || strings.TrimSpace(sessionID) == "" { return rpcResponse{ @@ -2248,7 +2286,7 @@ func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) }, } } - attachment, attachmentCtx, sessionDone, err := hub.attachRPC( + attachment, attachmentCtx, sessionDone, err := hub.attachRPCWithReservation( ctx, sessionID, attachmentID, @@ -2258,6 +2296,7 @@ func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) attachmentToken, requireExisting, inputSeqAck, + notifyReservationReady, ) if err != nil { return rpcResponse{ diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index 6b84aa7741c0..5970f7d0057e 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1296,12 +1296,6 @@ func TestStdioRPCCloseOvertakesStalledPTYStart(t *testing.T) { "command": "sleep 30", }, }) - select { - case <-startEntered: - case <-time.After(5 * time.Second): - t.Fatal("PTY attach never reached its stalled allocation") - } - writePersistentTestFrame(t, bufio.NewWriter(stdinWriter), rpcRequest{ ID: 2, Method: "pty.close", @@ -1309,6 +1303,11 @@ func TestStdioRPCCloseOvertakesStalledPTYStart(t *testing.T) { "session_id": "close-stalled-start", }, }) + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("PTY attach never reached its stalled allocation") + } closeResponse := waitForRPCResponseID(t, output, 2, time.Second) if ok, _ := closeResponse["ok"].(bool); !ok { t.Fatalf("close pending PTY start failed: %v", closeResponse) @@ -1355,13 +1354,24 @@ func TestStdioRPCShortCommandStartsExactlyOnce(t *testing.T) { "client_attachment_token": "short-token", "cols": 80, "rows": 24, - "command": "exit 0", + "command": "printf 'MARKER\\n'; exit 0", }, }) response := waitForRPCResponseID(t, output, 1, 5*time.Second) if ok, _ := response["ok"].(bool); !ok { t.Fatalf("short command attach failed: %v", response) } + dataEvent := waitForRPCEvent(t, output, 0, func(event map[string]any) bool { + if event["event"] != "pty.data" { + return false + } + encoded, _ := event["data_base64"].(string) + decoded, err := base64.StdEncoding.DecodeString(encoded) + return err == nil && bytes.Contains(decoded, []byte("MARKER")) + }) + if dataEvent["session_id"] != "short-command" { + t.Fatalf("short command data event = %v", dataEvent) + } exitEvent := waitForRPCEvent(t, output, 0, func(event map[string]any) bool { return event["event"] == "pty.exit" }) @@ -1371,6 +1381,18 @@ func TestStdioRPCShortCommandStartsExactlyOnce(t *testing.T) { if got := startCount.Load(); got != 1 { t.Fatalf("short command PTY start count = %d, want exactly 1", got) } + exitCount := 0 + for _, line := range rpcEventLines(output) { + var event map[string]any + if err := json.Unmarshal([]byte(line), &event); err == nil && + event["event"] == "pty.exit" && + event["session_id"] == "short-command" { + exitCount++ + } + } + if exitCount != 1 { + t.Fatalf("short command exit event count = %d, want exactly 1; output=%q", exitCount, output.String()) + } } func TestStdioRPCDisconnectCancelsSameSessionAttachWaiter(t *testing.T) { diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 67c557dbcfb9..e74fa9c06070 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -842,6 +842,32 @@ func (h *wsPTYHub) attachRPC( clientToken string, requireExisting bool, inputSeqAck bool, +) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { + return h.attachRPCWithReservation( + ctx, + sessionID, + attachmentID, + cols, + rows, + command, + clientToken, + requireExisting, + inputSeqAck, + nil, + ) +} + +func (h *wsPTYHub) attachRPCWithReservation( + ctx context.Context, + sessionID string, + attachmentID string, + cols int, + rows int, + command string, + clientToken string, + requireExisting bool, + inputSeqAck bool, + reservationReady func(), ) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { sessionID = strings.TrimSpace(sessionID) if sessionID == "" { @@ -849,7 +875,20 @@ func (h *wsPTYHub) attachRPC( } attachmentID = strings.TrimSpace(attachmentID) cols, rows = normalizePTYSize(cols, rows) - return h.prepareAttachment(ctx, nil, sessionID, attachmentID, cols, rows, true, command, clientToken, requireExisting, inputSeqAck) + return h.prepareAttachmentWithReservation( + ctx, + nil, + sessionID, + attachmentID, + cols, + rows, + true, + command, + clientToken, + requireExisting, + inputSeqAck, + reservationReady, + ) } func (h *wsPTYHub) prepareAttachment( @@ -864,6 +903,36 @@ func (h *wsPTYHub) prepareAttachment( clientToken string, requireExisting bool, inputSeqAck bool, +) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { + return h.prepareAttachmentWithReservation( + ctx, + conn, + sessionID, + attachmentID, + cols, + rows, + persistent, + command, + clientToken, + requireExisting, + inputSeqAck, + nil, + ) +} + +func (h *wsPTYHub) prepareAttachmentWithReservation( + ctx context.Context, + conn *websocket.Conn, + sessionID string, + attachmentID string, + cols int, + rows int, + persistent bool, + command string, + clientToken string, + requireExisting bool, + inputSeqAck bool, + reservationReady func(), ) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { h.mu.Lock() if h.closed { @@ -901,10 +970,16 @@ func (h *wsPTYHub) prepareAttachment( h.mu.Unlock() return nil, nil, nil, fmt.Errorf("persistent PTY session %q is no longer running", sessionID) } + if reservationReady != nil { + reservationReady() + } break } if start := h.startingSessions[sessionKey]; start != nil { start.waiters++ + if reservationReady != nil { + reservationReady() + } closedCh := h.closedCh h.mu.Unlock() select { @@ -948,6 +1023,9 @@ func (h *wsPTYHub) prepareAttachment( } start := &wsPTYSessionStart{done: make(chan struct{})} h.startingSessions[sessionKey] = start + if reservationReady != nil { + reservationReady() + } h.mu.Unlock() startedSession, startErr := h.startSession(sessionKey, sessionID, cols, rows, command) @@ -1076,7 +1154,7 @@ func (h *wsPTYHub) prepareAttachment( shouldApplySize := false if !finishedBeforeInitialAttachment { session.attachments[attachmentID] = attachment - session.initialPhase = wsPTYSessionInitialActive + h.activateInitialSessionIfReadyLocked(session) shouldApplySize = h.recomputeSessionSizeLocked(session) } if ownsInitialClaim { @@ -1099,6 +1177,7 @@ func (h *wsPTYHub) releaseInitialClaimLocked(session *wsPTYSession) { return } session.initialClaims-- + h.activateInitialSessionIfReadyLocked(session) if session.initialClaims != 0 || session.initialPhase != wsPTYSessionFinishedBeforeInitialAttachment || h.sessions[session.key] != session { @@ -1109,6 +1188,15 @@ func (h *wsPTYHub) releaseInitialClaimLocked(session *wsPTYSession) { session.closed = true } +func (h *wsPTYHub) activateInitialSessionIfReadyLocked(session *wsPTYSession) { + if session != nil && + session.initialPhase == wsPTYSessionAwaitingInitialAttachment && + session.initialClaims == 0 && + len(session.attachments) > 0 { + session.initialPhase = wsPTYSessionInitialActive + } +} + func (h *wsPTYHub) startSession(sessionKey wsPTYSessionKey, sessionID string, cols int, rows int, command string) (*wsPTYSession, error) { shellPath := resolvePTYShell(h.shell) trimmedCommand := strings.TrimSpace(command) @@ -1176,8 +1264,8 @@ func (h *wsPTYHub) startSession(sessionKey wsPTYSessionKey, sessionID string, co } func (h *wsPTYHub) runSession(session *wsPTYSession) { - go h.waitSessionProcess(session) go h.pumpSession(session) + go h.waitSessionProcess(session) go h.writeInputLoop(session) } @@ -1572,9 +1660,11 @@ func (h *wsPTYHub) waitSessionProcess(session *wsPTYSession) { // The process created by startPTYCommand is the POSIX session leader. Its // exit ends the terminal session even when a shielded background job still // holds the PTY slave open, so tear down every remaining member before - // closing the master and allowing pumpSession to finalize hub state. + // closing our slave. pumpSession exclusively owns the master on normal + // process exit so it can drain buffered output before EOF and finalization. + // Explicit hub teardown still closes both sides to interrupt a stuck pump. session.terminateProcesses() - session.closePTYFiles() + session.closeTTYFile() } func (session *wsPTYSession) closePTYFiles() { diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index a09cefc66d4f..7f98a5c10391 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -57,6 +57,21 @@ func (c *cancelAfterFirstErrContext) Err() error { return nil } +type gatedDoneContext struct { + context.Context + observed chan<- struct{} + release <-chan struct{} +} + +func (c gatedDoneContext) Done() <-chan struct{} { + select { + case c.observed <- struct{}{}: + default: + } + <-c.release + return c.Context.Done() +} + func newTestWebSocketPTYServer(t *testing.T, leasePath string) (*httptest.Server, *wsPTYHub) { t.Helper() stderr := &bytes.Buffer{} @@ -461,19 +476,65 @@ func TestAttachRPCFastExitCoalescedWaitersShareGeneration(t *testing.T) { t.Fatal("first fast-exit attach never attempted PTY allocation") } waiterJoined := make(chan struct{}, 1) + releaseWaiter := make(chan struct{}) secondResult := attach( - doneObservedContext{Context: context.Background(), observed: waiterJoined}, + gatedDoneContext{ + Context: context.Background(), + observed: waiterJoined, + release: releaseWaiter, + }, "second", ) select { case <-waiterJoined: case <-time.After(time.Second): close(releaseStart) + close(releaseWaiter) t.Fatal("second fast-exit attach did not join the in-flight generation") } close(releaseStart) - results := []attachResult{<-firstResult, <-secondResult} + first := <-firstResult + if first.err != nil { + close(releaseWaiter) + t.Fatalf("first coalesced fast-exit attach: %v", first.err) + } + if first.attachment == nil || first.sessionDone == nil { + close(releaseWaiter) + t.Fatal("first coalesced fast-exit attach returned incomplete attachment") + } + select { + case <-first.sessionDone: + case <-time.After(5 * time.Second): + close(releaseWaiter) + t.Fatal("fast-exit process did not finish while its final claimant was pending") + } + + hub.mu.Lock() + session := hub.sessions[persistentPTYSessionKey("coalesced-fast-exit")] + remainingClaims := 0 + initialPhase := wsPTYSessionInitialActive + if session != nil { + remainingClaims = session.initialClaims + initialPhase = session.initialPhase + } + hub.mu.Unlock() + if session == nil { + close(releaseWaiter) + t.Fatal("fast-exit generation was removed before its final claimant consumed it") + } + if remainingClaims != 1 { + close(releaseWaiter) + t.Fatalf("fast-exit generation claims = %d, want final pending claimant", remainingClaims) + } + if initialPhase != wsPTYSessionFinishedBeforeInitialAttachment { + close(releaseWaiter) + t.Fatalf("fast-exit generation phase = %d, want finished-before-initial-attachment", initialPhase) + } + + close(releaseWaiter) + second := <-secondResult + results := []attachResult{first, second} for index, result := range results { if result.err != nil { t.Fatalf("coalesced fast-exit attach %d: %v", index+1, result.err) @@ -481,10 +542,8 @@ func TestAttachRPCFastExitCoalescedWaitersShareGeneration(t *testing.T) { if result.attachment == nil || result.sessionDone == nil { t.Fatalf("coalesced fast-exit attach %d returned incomplete attachment", index+1) } - select { - case <-result.sessionDone: - case <-time.After(5 * time.Second): - t.Fatalf("coalesced fast-exit attach %d did not observe session exit", index+1) + if result.sessionDone != first.sessionDone { + t.Fatalf("coalesced fast-exit attach %d received a different generation", index+1) } } if got := startCount.Load(); got != 1 { @@ -541,6 +600,45 @@ func TestAttachRPCLateCancellationSchedulesPublishedSessionReap(t *testing.T) { t.Fatal("late-canceled published session has no idle reap timer") } + reattached, _, _, err := hub.attachRPC( + context.Background(), + "late-canceled-session", + "replacement-attachment", + 80, + 24, + "", + "", + true, + false, + ) + if err != nil { + t.Fatalf("reattach retained late-canceled session: %v", err) + } + hub.mu.Lock() + session = hub.sessions[persistentPTYSessionKey("late-canceled-session")] + attachmentCount = 0 + hasIdleTimer = false + initialPhase := wsPTYSessionAwaitingInitialAttachment + if session != nil { + attachmentCount = len(session.attachments) + hasIdleTimer = session.idleTimer != nil + initialPhase = session.initialPhase + } + hub.mu.Unlock() + if session == nil { + t.Fatal("late-canceled session disappeared before replacement attach") + } + if attachmentCount != 1 { + t.Fatalf("reattached late-canceled session attachments = %d, want 1", attachmentCount) + } + if hasIdleTimer { + t.Fatal("reattached late-canceled session retained its idle reap timer") + } + if initialPhase != wsPTYSessionInitialActive { + t.Fatalf("reattached late-canceled session phase = %d, want active", initialPhase) + } + + hub.dropAttachment(reattached) session.terminateProcesses() session.closePTYFiles() waitForHubSessionCount(t, hub, 0, 5*time.Second) @@ -1533,6 +1631,55 @@ func TestTerminateProcessesRunsOnlyOnce(t *testing.T) { } } +func TestWaitSessionProcessLeavesBufferedMasterOutputForPump(t *testing.T) { + master, slave, err := os.Pipe() + if err != nil { + t.Fatalf("open buffered output pipe: %v", err) + } + t.Cleanup(func() { + _ = master.Close() + _ = slave.Close() + }) + + const marker = "CMUX_BUFFERED_FAST_EXIT_OUTPUT\n" + if _, err := slave.Write([]byte(marker)); err != nil { + t.Fatalf("buffer fast-exit output: %v", err) + } + command := exec.Command("/bin/sh", "-c", "exit 0") + if err := command.Start(); err != nil { + t.Fatalf("start fast-exit command: %v", err) + } + + hub := newWebSocketPTYHub(wsPTYServerConfig{}, io.Discard) + t.Cleanup(hub.closeAll) + session := &wsPTYSession{ + id: "buffered-fast-exit", + key: persistentPTYSessionKey("buffered-fast-exit"), + cmd: command, + ptyFile: master, + ttyFile: slave, + attachments: map[string]*wsPTYAttachment{}, + done: make(chan struct{}), + initialPhase: wsPTYSessionInitialActive, + } + hub.sessions[session.key] = session + + // Deliberately reap the process before starting the pump. The process + // waiter may close the slave, but the pump must retain ownership of the + // master long enough to drain output already buffered by the terminal. + hub.waitSessionProcess(session) + hub.pumpSession(session) + + if got := string(session.scrollback); got != marker { + t.Fatalf("drained buffered output = %q, want %q", got, marker) + } + select { + case <-session.done: + default: + t.Fatal("buffered fast-exit session did not finish after its output drained") + } +} + func TestWebSocketPTYReplacedAttachmentCannotWriteInput(t *testing.T) { leasePath := filepath.Join(t.TempDir(), "lease.json") server, hub := newTestWebSocketPTYServer(t, leasePath) From b39e24df3a7db677d12e16eabc1daa1faf840f5d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 00:05:41 -0700 Subject: [PATCH 12/37] fix: bound PTY exit output draining --- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 22 +++++++++++ daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 38 ++++++++++++++----- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index e74fa9c06070..0373a2b06cbd 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -108,6 +108,7 @@ const ( defaultPTYInputChunkBytes = 16 * 1024 defaultWebSocketWriteTimeout = 10 * time.Second defaultWebSocketSessionIdleTTL = 24 * time.Hour + defaultPTYExitDrainTimeout = time.Second maxConcurrentPTYSessionStartOwnersPerHub = 16 standardExecutablePath = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" ) @@ -1665,6 +1666,27 @@ func (h *wsPTYHub) waitSessionProcess(session *wsPTYSession) { // Explicit hub teardown still closes both sides to interrupt a stuck pump. session.terminateProcesses() session.closeTTYFile() + + drainTimer := time.NewTimer(defaultPTYExitDrainTimeout) + defer func() { + if !drainTimer.Stop() { + select { + case <-drainTimer.C: + default: + } + } + }() + select { + case <-session.done: + return + case <-drainTimer.C: + // A child that deliberately escaped into a new POSIX session may still + // hold an inherited slave descriptor. It is outside this session's + // process ownership boundary, so bound output draining and force the + // pump to finalize rather than retaining the session indefinitely. + session.closePTYFile() + return + } } func (session *wsPTYSession) closePTYFiles() { diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index 7f98a5c10391..3da3ac36ede6 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -1631,14 +1631,22 @@ func TestTerminateProcessesRunsOnlyOnce(t *testing.T) { } } -func TestWaitSessionProcessLeavesBufferedMasterOutputForPump(t *testing.T) { +func TestWaitSessionProcessDrainsBufferedOutputBeforeForcedMasterClose(t *testing.T) { master, slave, err := os.Pipe() if err != nil { t.Fatalf("open buffered output pipe: %v", err) } + heldSlaveFD, err := syscall.Dup(int(slave.Fd())) + if err != nil { + _ = master.Close() + _ = slave.Close() + t.Fatalf("duplicate escaped slave holder: %v", err) + } + heldSlave := os.NewFile(uintptr(heldSlaveFD), "escaped-slave-holder") t.Cleanup(func() { _ = master.Close() _ = slave.Close() + _ = heldSlave.Close() }) const marker = "CMUX_BUFFERED_FAST_EXIT_OUTPUT\n" @@ -1664,19 +1672,29 @@ func TestWaitSessionProcessLeavesBufferedMasterOutputForPump(t *testing.T) { } hub.sessions[session.key] = session - // Deliberately reap the process before starting the pump. The process - // waiter may close the slave, but the pump must retain ownership of the - // master long enough to drain output already buffered by the terminal. - hub.waitSessionProcess(session) - hub.pumpSession(session) + go hub.pumpSession(session) + waiterDone := make(chan struct{}) + go func() { + hub.waitSessionProcess(session) + close(waiterDone) + }() - if got := string(session.scrollback); got != marker { - t.Fatalf("drained buffered output = %q, want %q", got, marker) + select { + case <-waiterDone: + case <-time.After(defaultPTYExitDrainTimeout + 2*time.Second): + t.Fatal("process waiter did not force-close the master after its drain deadline") } select { case <-session.done: - default: - t.Fatal("buffered fast-exit session did not finish after its output drained") + case <-time.After(time.Second): + t.Fatal("forced master close did not finish the escaped-holder session") + } + + if got := string(session.scrollback); got != marker { + t.Fatalf("drained buffered output = %q, want %q", got, marker) + } + if _, err := heldSlave.Stat(); err != nil { + t.Fatalf("escaped slave holder closed before the master drain deadline: %v", err) } } From 390cdc3adfba7f9010160914309654588c4b07bf Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 01:19:04 -0700 Subject: [PATCH 13/37] test: preserve remote PTY capacity failures --- .../SSHPTYAttachExitCodeTests.swift | 42 +++++++++ ...oteDaemonRPCClientErrorMetadataTests.swift | 88 +++++++++++++++++++ ...RemotePTYBridgeSessionErrorCodeTests.swift | 26 +++++- ...ISSHPTYAttachSessionLostRespawnTests.swift | 11 ++- daemon/remote/cmd/cmuxd-remote/main_test.go | 22 +++++ daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 37 ++++---- 6 files changed, 204 insertions(+), 22 deletions(-) create mode 100644 Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift create mode 100644 Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientErrorMetadataTests.swift diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift new file mode 100644 index 000000000000..5af0f9b77930 --- /dev/null +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift @@ -0,0 +1,42 @@ +import Testing +@testable import CmuxFoundation + +@Suite("SSH PTY attach exit code") +struct SSHPTYAttachExitCodeTests { + @Test("structured daemon capacity is retryable") + func structuredUnavailableIsRetryable() { + #expect( + SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( + code: "unavailable", + message: "remote PTY attach failed" + ) == .retryableTransient + ) + #expect(SSHPTYAttachExitCode.retryableTransient.rawValue == 255) + } + + @Test("lifecycle codes retain precedence over transient-looking messages") + func lifecycleCodesRetainPrecedence() { + #expect( + SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( + code: "pty_session_not_found", + message: "service unavailable" + ) == .sessionNotFound + ) + #expect( + SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( + code: "pty_lifecycle_closed", + message: "service unavailable" + ) == .fatal + ) + } + + @Test("unrelated codes containing unavailable remain fatal") + func unavailableMustBeExact() { + #expect( + SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( + code: "service_unavailable", + message: "remote PTY attach failed" + ) == .fatal + ) + } +} diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientErrorMetadataTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientErrorMetadataTests.swift new file mode 100644 index 000000000000..537933b9ef8f --- /dev/null +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientErrorMetadataTests.swift @@ -0,0 +1,88 @@ +import Darwin +import Foundation +import Testing +import CmuxCore +@testable import CmuxRemoteDaemon + +@Suite("RemoteDaemonRPCClient error metadata") +struct RemoteDaemonRPCClientErrorMetadataTests { + @Test("daemon RPC errors preserve their structured code") + func structuredCodeIsPreserved() throws { + let executable = try makeErrorTransport() + defer { + try? FileManager.default.removeItem( + at: URL(fileURLWithPath: executable).deletingLastPathComponent() + ) + } + let client = RemoteDaemonRPCClient( + configuration: configuration(), + remotePath: "/fake/cmuxd-remote", + strings: RemoteDaemonStrings( + missingPersistentPTYCapability: "missing persistent PTY", + missingRequiredFunctionality: "missing functionality" + ) + ) { _ in } + defer { client.stop() } + client.transportExecutableOverride = executable + + try client.start() + + do { + _ = try client.call(method: "pty.attach", params: [:], timeout: 1) + Issue.record("pty.attach unexpectedly succeeded") + } catch { + let nsError = error as NSError + #expect(nsError.domain == "cmux.remote.daemon.rpc") + #expect(nsError.code == 14) + #expect( + nsError.localizedDescription == + "pty.attach failed (unavailable): too many PTY sessions are already starting" + ) + #expect( + nsError.userInfo["cmux.remote.daemon.rpc.error_code"] as? String == + "unavailable" + ) + } + } + + private func configuration() -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: "fake-host", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil, + preserveAfterTerminalExit: false, + persistentDaemonSlot: nil + ) + } + + private func makeErrorTransport() throws -> String { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-remote-daemon-rpc-error-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let scriptURL = directory.appendingPathComponent("fake-ssh-error") + let script = """ + #!/bin/sh + if IFS= read -r line; then + id=$(printf '%s\\n' "$line" | sed -n 's/.*"id":\\([0-9][0-9]*\\).*/\\1/p') + printf '{"id":%s,"ok":true,"result":{"capabilities":["proxy.stream.push"]}}\\n' "$id" + else + exit 1 + fi + if IFS= read -r line; then + id=$(printf '%s\\n' "$line" | sed -n 's/.*"id":\\([0-9][0-9]*\\).*/\\1/p') + printf '{"id":%s,"ok":false,"error":{"code":"unavailable","message":"too many PTY sessions are already starting"}}\\n' "$id" + fi + while IFS= read -r _line; do :; done + """ + try Data(script.utf8).write(to: scriptURL, options: .atomic) + chmod(scriptURL.path, 0o755) + return scriptURL.path + } +} diff --git a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeSessionErrorCodeTests.swift b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeSessionErrorCodeTests.swift index 292471361bc8..0fabcea0aa65 100644 --- a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeSessionErrorCodeTests.swift +++ b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeSessionErrorCodeTests.swift @@ -6,10 +6,14 @@ import Testing @Suite("RemotePTYBridgeServer error codes") struct RemotePTYBridgeSessionErrorCodeTests { private func bridgeErrorPayload(for message: String) throws -> [String: Any] { - let rpc = RecordingPTYBridgeRPCClient() - rpc.attachError = NSError(domain: "test", code: 1, userInfo: [ + try bridgeErrorPayload(for: NSError(domain: "test", code: 1, userInfo: [ NSLocalizedDescriptionKey: message, - ]) + ])) + } + + private func bridgeErrorPayload(for error: any Error) throws -> [String: Any] { + let rpc = RecordingPTYBridgeRPCClient() + rpc.attachError = error let server = RemotePTYBridgeServer( rpcClient: rpc, sessionID: "session-1", @@ -40,6 +44,22 @@ struct RemotePTYBridgeSessionErrorCodeTests { #expect(payload["code"] as? String == "pty_session_not_found") } + @Test("structured daemon errors carry their exact code") + func structuredUnavailableCarriesCode() throws { + let payload = try bridgeErrorPayload(for: NSError( + domain: "cmux.remote.daemon.rpc", + code: 14, + userInfo: [ + NSLocalizedDescriptionKey: "pty.attach failed (unavailable): capacity reached", + "cmux.remote.daemon.rpc.error_code": "unavailable", + ] + )) + + #expect(payload["type"] as? String == "error") + #expect(payload["message"] as? String == "test-attach-failed") + #expect(payload["code"] as? String == "unavailable") + } + @Test("generic attach failures omit the bridge error code") func genericFailureOmitsCode() throws { let payload = try bridgeErrorPayload(for: "some generic failure") diff --git a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift index c67b353bca5c..168497acdc52 100644 --- a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift +++ b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift @@ -307,7 +307,7 @@ extension CLINotifyProcessIntegrationRegressionTests { XCTAssertEqual(methods.filter { $0 == "workspace.remote.pty_attach_end" }.count, 1, "\(methods)") } - func testSSHPTYAttachTransientPreReadyFailureKeepsLifecycleForRetry() throws { + func testSSHPTYAttachCapacityFailureKeepsSurfaceForWrapperRetry() throws { let cliPath = try bundledCLIPath() let socketPath = makeSocketPath("sshptypreretry") let listenerFD = try bindUnixSocket(at: socketPath) @@ -365,8 +365,8 @@ extension CLINotifyProcessIntegrationRegressionTests { } let firstBridgeHandled = startBridgeErrorServer( listenerFD: firstBridge.fd, - message: "connection reset", - code: "remote_pty_error" + message: "remote PTY attach failed", + code: "unavailable" ) let secondBridgeHandled = startBridgeReadyThenCloseServer(listenerFD: secondBridge.fd) let arguments = [ @@ -387,6 +387,11 @@ extension CLINotifyProcessIntegrationRegressionTests { ) XCTAssertFalse(first.timedOut, first.stderr) XCTAssertEqual(first.status, SSHPTYAttachExitCode.retryableTransient.rawValue, first.stderr) + let firstMethods = state.snapshot().compactMap { self.jsonObject($0)?["method"] as? String } + XCTAssertFalse( + firstMethods.contains("workspace.remote.pty_attach_end"), + "capacity retry must preserve the surface: \(firstMethods)" + ) environment["CMUX_SSH_PTY_ATTACH_WRAPPER_CAN_RETRY"] = "0" let second = runProcess( diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index 5970f7d0057e..d5afd69bd7af 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1174,6 +1174,28 @@ func TestAuthenticatePersistentDaemonServerReadDeadline(t *testing.T) { } } +func TestRPCDispatcherPTYAttachCapacityReturnsUnavailable(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + output := newNotifyingBuffer() + server := &rpcServer{ + frameWriter: &stdioFrameWriter{writer: bufio.NewWriter(output)}, + } + dispatcher := newRPCRequestDispatcher(ctx, cancel, nil, server) + for i := 0; i < maxConcurrentPTYAttachRPCsPerConnection; i++ { + dispatcher.ptyAttachSlots <- struct{}{} + } + + if err := dispatcher.dispatch(rpcRequest{ID: 1, Method: "pty.attach"}); err != nil { + t.Fatalf("dispatch over-capacity pty.attach: %v", err) + } + response := waitForRPCResponseID(t, output, 1, time.Second) + errorObject, _ := response["error"].(map[string]any) + if got := errorObject["code"]; got != "unavailable" { + t.Fatalf("over-capacity pty.attach error code = %v, want unavailable; response=%v", got, response) + } +} + func TestStdioRPCStalledPTYAttachDoesNotBlockHealthyAttach(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index 3da3ac36ede6..dd72faf19592 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -687,25 +687,30 @@ func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { } } - excessResult := make(chan error, 1) + excessResult := make(chan rpcResponse, 1) + server := &rpcServer{ptyHub: hub} go func() { - _, _, _, err := hub.attachRPC( - context.Background(), - "bounded-start-excess", - "attachment", - 80, - 24, - "sleep 30", - "", - false, - false, - ) - excessResult <- err + excessResult <- server.handleRequest(rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "bounded-start-excess", + "attachment_id": "attachment", + "client_attachment_token": "token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) }() select { - case err := <-excessResult: - if err == nil || !strings.Contains(err.Error(), "too many PTY sessions") { - t.Fatalf("excess PTY start error = %v, want bounded unavailable error", err) + case response := <-excessResult: + if response.Error == nil || response.Error.Code != "unavailable" { + t.Fatalf("excess PTY start response = %+v, want unavailable error", response) + } + const wantMessage = "too many PTY sessions are already starting" + if response.Error.Message != wantMessage { + t.Fatalf("excess PTY start message = %q, want %q", response.Error.Message, wantMessage) } case <-time.After(time.Second): t.Fatal("excess PTY start blocked instead of failing immediately") From 35faab710a9a5158b10e23ea827339b16f5f20ed Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 01:20:55 -0700 Subject: [PATCH 14/37] fix: retry remote PTY capacity failures --- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 3 +++ .../Client/RemoteDaemonRPCClient+RPC.swift | 1 + .../Client/RemoteDaemonRPCClient.swift | 15 +++++++++++++++ .../RemotePTYBridgeSession+ErrorMapping.swift | 3 +++ daemon/remote/cmd/cmuxd-remote/main.go | 11 +++++++---- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 13 +++++++------ 6 files changed, 36 insertions(+), 10 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift index fb51169bf54e..3ea146fc30ca 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -185,6 +185,9 @@ public enum SSHPTYAttachExitCode: Int32 { if normalizedCode == "pty_lifecycle_closed" { return .fatal } + if normalizedCode == "unavailable" { + return .retryableTransient + } let rawDescription = [normalizedCode, message] .compactMap { $0 } .joined(separator: " ") diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift index eaed2ae1df9c..8fdd9f74de31 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift @@ -359,6 +359,7 @@ extension RemoteDaemonRPCClient { let message = (errorObject["message"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "daemon RPC call failed" throw NSError(domain: "cmux.remote.daemon.rpc", code: 14, userInfo: [ NSLocalizedDescriptionKey: "\(method) failed (\(code)): \(message)", + Self.rpcErrorCodeUserInfoKey: code, ]) } diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift index ed29bbf1844d..0296de2fea0e 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift @@ -65,8 +65,23 @@ public final class RemoteDaemonRPCClient: @unchecked Sendable { /// Wire-pinned rpc error code the daemon returns for a sequenced /// `pty.write` whose seq is not exactly last+1. public static let ptyInputSeqGapErrorCode = "pty_input_seq_gap" + /// Package-owned NSError metadata key for the daemon's structured RPC error code. + static let rpcErrorCodeUserInfoKey = "cmux.remote.daemon.rpc.error_code" static let maxCloudCLIRequestsInFlight = 4 + /// Returns the daemon's structured RPC error code preserved on `error`. + /// + /// RPC callers should classify this stable code before consulting the + /// localized description, whose text remains a compatibility surface but + /// is not a reliable error taxonomy. + public static func rpcErrorCode(from error: any Error) -> String? { + guard let rawCode = (error as NSError).userInfo[rpcErrorCodeUserInfoKey] as? String else { + return nil + } + let code = rawCode.trimmingCharacters(in: .whitespacesAndNewlines) + return code.isEmpty ? nil : code + } + // Subscription records pair the caller's delivery queue with its handler. // @unchecked Sendable: the handler is only ever invoked via // `queue.async` on the queue stored beside it (the legacy diff --git a/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession+ErrorMapping.swift b/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession+ErrorMapping.swift index 45270c28ebea..02d30ba8ccaf 100644 --- a/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession+ErrorMapping.swift +++ b/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession+ErrorMapping.swift @@ -35,6 +35,9 @@ extension RemotePTYBridgeServer.Session { } static func bridgeErrorCode(for error: any Error) -> String? { + if let structuredCode = RemoteDaemonRPCClient.rpcErrorCode(from: error) { + return structuredCode + } let lowered = error.localizedDescription .trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 95a57df2aba2..995e4ebdedc7 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -2303,7 +2303,7 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( ID: req.ID, OK: false, Error: &rpcError{ - Code: ptyAttachErrorCode(requireExisting), + Code: ptyAttachErrorCode(err, requireExisting), Message: ptyAttachErrorMessage(err), }, } @@ -2314,7 +2314,7 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( ID: req.ID, OK: false, Error: &rpcError{ - Code: ptyAttachErrorCode(requireExisting), + Code: ptyAttachErrorCode(err, requireExisting), Message: ptyAttachErrorMessage(err), }, } @@ -2325,7 +2325,7 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( ID: req.ID, OK: false, Error: &rpcError{ - Code: ptyAttachErrorCode(requireExisting), + Code: ptyAttachErrorCode(nil, requireExisting), Message: "RPC connection closed before PTY attachment completed", }, } @@ -2351,7 +2351,10 @@ func ptyAttachErrorMessage(err error) string { return err.Error() } -func ptyAttachErrorCode(requireExisting bool) string { +func ptyAttachErrorCode(err error, requireExisting bool) string { + if errors.Is(err, errWSPTYStartOwnersSaturated) { + return "unavailable" + } if requireExisting { return "pty_session_not_found" } diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 0373a2b06cbd..0d84a92a7681 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -90,11 +90,12 @@ type wsPTYLease = wsLease type wsPTYAuthFrame = wsAuthFrame var ( - errWSLeaseMissing = errors.New("attach lease missing") - errWSLeaseExpired = errors.New("attach lease expired") - errWSLeaseForbidden = errors.New("attach lease rejected") - errWSPTYHubClosed = errors.New("PTY hub is closed") - wsLeaseMu sync.Mutex + errWSLeaseMissing = errors.New("attach lease missing") + errWSLeaseExpired = errors.New("attach lease expired") + errWSLeaseForbidden = errors.New("attach lease rejected") + errWSPTYHubClosed = errors.New("PTY hub is closed") + errWSPTYStartOwnersSaturated = errors.New("too many PTY sessions are already starting") + wsLeaseMu sync.Mutex ) const ( @@ -1020,7 +1021,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( case h.sessionStartSlots <- struct{}{}: default: h.mu.Unlock() - return nil, nil, nil, errors.New("too many PTY sessions are already starting") + return nil, nil, nil, errWSPTYStartOwnersSaturated } start := &wsPTYSessionStart{done: make(chan struct{})} h.startingSessions[sessionKey] = start From f334859cb15bee7c8de2c7eb9abadeed29f7abc3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 01:41:39 -0700 Subject: [PATCH 15/37] test: bound remote PTY capacity recovery --- .../SSHPTYAttachExitCodeTests.swift | 74 +++++++++++++-- ...ISSHPTYAttachSessionLostRespawnTests.swift | 2 +- .../TabManagerSessionSnapshotTests.swift | 4 +- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 92 +++++++++++++++++++ 4 files changed, 162 insertions(+), 10 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift index 5af0f9b77930..cc008e5bd70a 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift @@ -1,19 +1,70 @@ +import Foundation import Testing @testable import CmuxFoundation @Suite("SSH PTY attach exit code") struct SSHPTYAttachExitCodeTests { - @Test("structured daemon capacity is retryable") - func structuredUnavailableIsRetryable() { - #expect( - SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( - code: "unavailable", - message: "remote PTY attach failed" - ) == .retryableTransient + @Test("structured daemon capacity retries without requesting authentication") + func structuredUnavailableRetriesWithoutAuthentication() { + let classified = SSHPTYAttachExitCode.classifyBridgeEstablishmentFailure( + code: "unavailable", + message: "remote PTY attach failed" ) + + #expect(classified.rawValue == 251) + #expect(classified.isWrapperRetryable) #expect(SSHPTYAttachExitCode.retryableTransient.rawValue == 255) } + @Test("capacity retries keep authentication ownership idle") + func capacityRetryDoesNotReauthenticate() throws { + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-pty-capacity-\(UUID().uuidString)", isDirectory: true) + let attach = root.appendingPathComponent("attach") + let sleep = root.appendingPathComponent("sleep") + let attempts = root.appendingPathComponent("attempts") + let authAttempts = root.appendingPathComponent("auth-attempts") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + try Self.writeExecutable( + attach, + """ + #!/bin/sh + count=$(cat "$CMUX_TEST_ATTEMPTS" 2>/dev/null || printf 0) + count=$((count + 1)) + printf '%s' "$count" > "$CMUX_TEST_ATTEMPTS" + if [ "$count" -eq 1 ]; then exit 251; fi + exit 1 + """ + ) + try Self.writeExecutable(sleep, "#!/bin/sh\nexit 0") + + let retryScript = ([ + "cmux_ssh_attach_foreground_auth() { printf x >> \"$CMUX_TEST_AUTH_ATTEMPTS\"; }", + ] + SSHPTYAttachExitCode.retryLoopLines( + command: Self.shellQuote(attach.path), + reauthenticates: true + )).joined(separator: "\n") + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = ["-c", retryScript] + process.environment = [ + "PATH": "\(root.path):/usr/bin:/bin", + "CMUX_TEST_ATTEMPTS": attempts.path, + "CMUX_TEST_AUTH_ATTEMPTS": authAttempts.path, + "CMUX_SSH_RECONNECT_DELAY_SECONDS": "1", + "CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS": "1", + ] + try process.run() + process.waitUntilExit() + + #expect(process.terminationStatus == 1) + #expect(try String(contentsOf: attempts, encoding: .utf8) == "2") + #expect(!fileManager.fileExists(atPath: authAttempts.path)) + } + @Test("lifecycle codes retain precedence over transient-looking messages") func lifecycleCodesRetainPrecedence() { #expect( @@ -39,4 +90,13 @@ struct SSHPTYAttachExitCodeTests { ) == .fatal ) } + + private static func writeExecutable(_ url: URL, _ source: String) throws { + try source.write(to: url, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path) + } + + private static func shellQuote(_ value: String) -> String { + "'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'" + } } diff --git a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift index 168497acdc52..d01bfcf9b7df 100644 --- a/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift +++ b/cmuxTests/CLISSHPTYAttachSessionLostRespawnTests.swift @@ -386,7 +386,7 @@ extension CLINotifyProcessIntegrationRegressionTests { timeout: 5 ) XCTAssertFalse(first.timedOut, first.stderr) - XCTAssertEqual(first.status, SSHPTYAttachExitCode.retryableTransient.rawValue, first.stderr) + XCTAssertEqual(first.status, 251, first.stderr) let firstMethods = state.snapshot().compactMap { self.jsonObject($0)?["method"] as? String } XCTAssertFalse( firstMethods.contains("workspace.remote.pty_attach_end"), diff --git a/cmuxTests/TabManagerSessionSnapshotTests.swift b/cmuxTests/TabManagerSessionSnapshotTests.swift index 75660961953e..4ee841cb1d49 100644 --- a/cmuxTests/TabManagerSessionSnapshotTests.swift +++ b/cmuxTests/TabManagerSessionSnapshotTests.swift @@ -2490,7 +2490,7 @@ final class TabManagerSessionSnapshotTests: XCTestCase { XCTAssertFalse(terminalStartupCommand.contains(expectedSessionID), terminalStartupCommand) XCTAssertFalse(terminalStartupCommand.contains("--require-existing"), terminalStartupCommand) XCTAssertTrue(terminalStartupCommand.contains("--command-b64 "), terminalStartupCommand) - XCTAssertTrue(terminalStartupCommand.contains("254|255"), terminalStartupCommand) + XCTAssertTrue(terminalStartupCommand.contains("251|254|255"), terminalStartupCommand) let restoredDefaultRemoteCommand = try XCTUnwrap( Self.decodedSSHPTYCommandB64(in: terminalStartupCommand) ) @@ -2559,7 +2559,7 @@ final class TabManagerSessionSnapshotTests: XCTestCase { XCTAssertTrue(restoredInitialCommand.contains("workspace.remote.foreground_auth_ready"), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains(restoredForegroundAuthToken), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains("--require-existing"), restoredInitialCommand) - XCTAssertTrue(restoredInitialCommand.contains("254|255"), restoredInitialCommand) + XCTAssertTrue(restoredInitialCommand.contains("251|254|255"), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains(expectedSessionID), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains("CMUX_SURFACE_ID"), restoredInitialCommand) XCTAssertFalse(restoredInitialCommand.contains("--command-b64 "), restoredInitialCommand) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index dd72faf19592..e779cf850be2 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -723,6 +723,98 @@ func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { } } +func TestAttachRPCBoundsStalledSessionStartWaitersPerHub(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + const waiterLimit = 64 + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + released := false + t.Cleanup(func() { + if !released { + close(releaseStart) + } + }) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return nil, nil, errors.New("test PTY start released") + } + + results := make(chan error, waiterLimit+1) + attach := func(ctx context.Context, attachmentID string) { + go func() { + _, _, _, err := hub.attachRPC( + ctx, + "bounded-waiters", + attachmentID, + 80, + 24, + "sleep 30", + "", + false, + false, + ) + results <- err + }() + } + attach(context.Background(), "owner") + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("PTY start owner did not enter allocation") + } + + for i := 0; i < waiterLimit; i++ { + waiterJoined := make(chan struct{}, 1) + attach( + doneObservedContext{Context: context.Background(), observed: waiterJoined}, + "waiter-"+strconv.Itoa(i), + ) + select { + case <-waiterJoined: + case <-time.After(time.Second): + t.Fatalf("PTY start waiter %d did not join", i+1) + } + } + + excessResult := make(chan rpcResponse, 1) + server := &rpcServer{ptyHub: hub} + go func() { + excessResult <- server.handleRequest(rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "bounded-waiters", + "attachment_id": "excess", + "client_attachment_token": "token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + }() + select { + case response := <-excessResult: + if response.Error == nil || response.Error.Code != "unavailable" { + t.Fatalf("excess PTY start waiter response = %+v, want unavailable error", response) + } + const wantMessage = "too many PTY session starts are already being awaited" + if response.Error.Message != wantMessage { + t.Fatalf("excess PTY start waiter message = %q, want %q", response.Error.Message, wantMessage) + } + case <-time.After(time.Second): + t.Fatal("excess PTY start waiter blocked instead of failing immediately") + } + + released = true + close(releaseStart) + for i := 0; i < waiterLimit+1; i++ { + <-results + } +} + func TestCloseAllDoesNotWaitForStalledSessionStart(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) From b717dd61af30e6f5e5e2b2b002335a4dbf7780a4 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 01:43:31 -0700 Subject: [PATCH 16/37] fix: bound remote PTY start waiters --- CLI/CMUXCLI+SSHStartupScripts.swift | 4 +- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 17 +++- daemon/remote/cmd/cmuxd-remote/main.go | 3 +- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 95 ++++++++++++------- 4 files changed, 75 insertions(+), 44 deletions(-) diff --git a/CLI/CMUXCLI+SSHStartupScripts.swift b/CLI/CMUXCLI+SSHStartupScripts.swift index 6b408f9d006b..b3a5aa263b7c 100644 --- a/CLI/CMUXCLI+SSHStartupScripts.swift +++ b/CLI/CMUXCLI+SSHStartupScripts.swift @@ -378,7 +378,7 @@ extension CMUXCLI { scriptLines.append(" cmux_ssh_preflight_control_path") } if retryPTYAttachStatus { - // Advertise per attempt whether another 254|255 retry is queued so + // Advertise per attempt whether another 251|254|255 retry is queued so // ssh-pty-attach only suppresses its pty_attach_end cleanup while a // retry is actually pending; see CMUXCLI.sshPTYAttachWrapperRetryPending // and keep in sync with CMUXCLI.sshPTYAttachRetryLoopLines / @@ -397,7 +397,7 @@ extension CMUXCLI { } else { scriptLines.append(" command \(sshCommand) <&0 &") } - let retryableStatusPattern = retryPTYAttachStatus ? "254|255" : "255" + let retryableStatusPattern = retryPTYAttachStatus ? "251|254|255" : "255" scriptLines += [ " CMUX_SSH_CHILD_PID=$!", " if [ -n \"${CMUX_SSH_PENDING_SIGNAL:-}\" ]; then cmux_ssh_signal_exit \"$CMUX_SSH_PENDING_SIGNAL\"; fi", diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift index 3ea146fc30ca..e266f9d868fe 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -2,14 +2,17 @@ import Foundation /// Describes the process exit status and retry policy for an SSH PTY attach. /// -/// Status 252 has a bounded consecutive-failure budget, while statuses 254 -/// and 255 use the general reconnect budget. +/// Status 252 has a bounded consecutive-failure budget, while statuses 251, +/// 254, and 255 use the general reconnect budget. public enum SSHPTYAttachExitCode: Int32 { private static let healthyBridgeUptime: Double = 30 /// A non-retryable attach failure. case fatal = 1 + /// Temporary daemon-side admission pressure that should retry without reauthentication. + case retryableWithoutReauthentication = 251 + /// A rapidly closed bridge that produced no remote PTY output. case bridgeClosedWithoutProgress = 252 @@ -27,7 +30,9 @@ public enum SSHPTYAttachExitCode: Int32 { /// Failures with these statuses keep app-side surface tracking intact /// because the wrapper immediately reattaches on the same surface. public var isWrapperRetryable: Bool { - self == .bridgeClosedSessionRunning || self == .retryableTransient + self == .retryableWithoutReauthentication || + self == .bridgeClosedSessionRunning || + self == .retryableTransient } /// Determines whether a bridge closed before demonstrating useful progress. @@ -68,6 +73,7 @@ public enum SSHPTYAttachExitCode: Int32 { localized: "cli.sshPtyAttach.bridgeClosedReattaching", defaultValue: "[cmux] remote PTY bridge closed; reattaching (attempt %s/%s)." ).remoteCommandShellQuoted + let retryWithoutReauthenticationStatus = retryableWithoutReauthentication.rawValue let sessionRunningStatus = bridgeClosedSessionRunning.rawValue let transientStatus = retryableTransient.rawValue @@ -96,6 +102,7 @@ public enum SSHPTYAttachExitCode: Int32 { " cmux_ssh_attach_status=$?", " case \"$cmux_ssh_attach_status\" in", " \(noProgressPolicy.status)) cmux_ssh_attach_no_progress_retry=$((cmux_ssh_attach_no_progress_retry + 1)); cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\"; \(noProgressPolicy.limitReachedCommand) ;;", + " \(retryWithoutReauthenticationStatus)) cmux_ssh_attach_no_progress_retry=0 ;;", " \(sessionRunningStatus)) cmux_ssh_attach_no_progress_retry=0; cmux_ssh_attach_reconnect_delay=\"$cmux_ssh_attach_reconnect_initial_delay\" ;;", " \(transientStatus)) cmux_ssh_attach_no_progress_retry=0; \(reauthenticate) ;;", " *) exit \"$cmux_ssh_attach_status\" ;;", @@ -114,7 +121,7 @@ public enum SSHPTYAttachExitCode: Int32 { /// general reconnect and foreground-authentication policy. /// /// Status 252 is consumed until its health budget is exhausted. All other - /// statuses, including 254 and 255, return unchanged to the enclosing + /// statuses, including 251, 254, and 255, return unchanged to the enclosing /// wrapper so its existing reconnect and reauthentication behavior remains /// the single owner of those transitions. /// @@ -186,7 +193,7 @@ public enum SSHPTYAttachExitCode: Int32 { return .fatal } if normalizedCode == "unavailable" { - return .retryableTransient + return .retryableWithoutReauthentication } let rawDescription = [normalizedCode, message] .compactMap { $0 } diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 995e4ebdedc7..b2e88afebd3a 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -2352,7 +2352,8 @@ func ptyAttachErrorMessage(err error) string { } func ptyAttachErrorCode(err error, requireExisting bool) string { - if errors.Is(err, errWSPTYStartOwnersSaturated) { + if errors.Is(err, errWSPTYStartOwnersSaturated) || + errors.Is(err, errWSPTYStartWaitersSaturated) { return "unavailable" } if requireExisting { diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 0d84a92a7681..6e1613786d98 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -90,28 +90,30 @@ type wsPTYLease = wsLease type wsPTYAuthFrame = wsAuthFrame var ( - errWSLeaseMissing = errors.New("attach lease missing") - errWSLeaseExpired = errors.New("attach lease expired") - errWSLeaseForbidden = errors.New("attach lease rejected") - errWSPTYHubClosed = errors.New("PTY hub is closed") - errWSPTYStartOwnersSaturated = errors.New("too many PTY sessions are already starting") - wsLeaseMu sync.Mutex + errWSLeaseMissing = errors.New("attach lease missing") + errWSLeaseExpired = errors.New("attach lease expired") + errWSLeaseForbidden = errors.New("attach lease rejected") + errWSPTYHubClosed = errors.New("PTY hub is closed") + errWSPTYStartOwnersSaturated = errors.New("too many PTY sessions are already starting") + errWSPTYStartWaitersSaturated = errors.New("too many PTY session starts are already being awaited") + wsLeaseMu sync.Mutex ) const ( - defaultPTYCols = 80 - defaultPTYRows = 24 - maxPTYDimension = 65535 - defaultWebSocketScrollbackCap = 1 << 20 - defaultWebSocketReplayChunkBytes = 48 * 1024 - defaultWebSocketWriteQueueCap = 256 - defaultPTYInputQueueCap = 256 - defaultPTYInputChunkBytes = 16 * 1024 - defaultWebSocketWriteTimeout = 10 * time.Second - defaultWebSocketSessionIdleTTL = 24 * time.Hour - defaultPTYExitDrainTimeout = time.Second - maxConcurrentPTYSessionStartOwnersPerHub = 16 - standardExecutablePath = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" + defaultPTYCols = 80 + defaultPTYRows = 24 + maxPTYDimension = 65535 + defaultWebSocketScrollbackCap = 1 << 20 + defaultWebSocketReplayChunkBytes = 48 * 1024 + defaultWebSocketWriteQueueCap = 256 + defaultPTYInputQueueCap = 256 + defaultPTYInputChunkBytes = 16 * 1024 + defaultWebSocketWriteTimeout = 10 * time.Second + defaultWebSocketSessionIdleTTL = 24 * time.Hour + defaultPTYExitDrainTimeout = time.Second + maxConcurrentPTYSessionStartOwnersPerHub = 16 + maxConcurrentPTYSessionStartWaitersPerHub = 64 + standardExecutablePath = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" ) type wsPTYOutgoingFrame struct { @@ -235,14 +237,18 @@ type wsPTYHub struct { // PTY startup is not context-cancellable once inside the operating system, // so bound the number of start owners that can survive client teardown. sessionStartSlots chan struct{} - closed bool - closedCh chan struct{} - nextAttachmentID uint64 - nextAnonymousID uint64 - shell string - stderr io.Writer - scrollbackLimit int - sessionIdleTTL time.Duration + // Multiple RPC connections share one persistent hub. Bound joiners here, + // rather than only per connection, so one stalled same-session start cannot + // retain unbounded goroutines across reconnect churn. + sessionStartWaiterSlots chan struct{} + closed bool + closedCh chan struct{} + nextAttachmentID uint64 + nextAnonymousID uint64 + shell string + stderr io.Writer + scrollbackLimit int + sessionIdleTTL time.Duration // openPTY allocates a PTY master/slave pair. It defaults to creack/pty.Open // (which opens /dev/ptmx) and exists as a field so tests can simulate a // hardened devpts where allocation is denied. @@ -263,15 +269,16 @@ func newWebSocketPTYHub(cfg wsPTYServerConfig, stderr io.Writer) *wsPTYHub { idleTTL = defaultWebSocketSessionIdleTTL } return &wsPTYHub{ - sessions: map[wsPTYSessionKey]*wsPTYSession{}, - startingSessions: map[wsPTYSessionKey]*wsPTYSessionStart{}, - sessionStartSlots: make(chan struct{}, maxConcurrentPTYSessionStartOwnersPerHub), - closedCh: make(chan struct{}), - shell: strings.TrimSpace(cfg.Shell), - stderr: stderr, - scrollbackLimit: limit, - sessionIdleTTL: idleTTL, - openPTY: pty.Open, + sessions: map[wsPTYSessionKey]*wsPTYSession{}, + startingSessions: map[wsPTYSessionKey]*wsPTYSessionStart{}, + sessionStartSlots: make(chan struct{}, maxConcurrentPTYSessionStartOwnersPerHub), + sessionStartWaiterSlots: make(chan struct{}, maxConcurrentPTYSessionStartWaitersPerHub), + closedCh: make(chan struct{}), + shell: strings.TrimSpace(cfg.Shell), + stderr: stderr, + scrollbackLimit: limit, + sessionIdleTTL: idleTTL, + openPTY: pty.Open, } } @@ -978,6 +985,12 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( break } if start := h.startingSessions[sessionKey]; start != nil { + select { + case h.sessionStartWaiterSlots <- struct{}{}: + default: + h.mu.Unlock() + return nil, nil, nil, errWSPTYStartWaitersSaturated + } start.waiters++ if reservationReady != nil { reservationReady() @@ -986,12 +999,14 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( h.mu.Unlock() select { case <-start.done: + <-h.sessionStartWaiterSlots if start.err != nil { return nil, nil, nil, start.err } claimedSession = start.session ownsInitialClaim = claimedSession != nil case <-closedCh: + <-h.sessionStartWaiterSlots h.mu.Lock() if start.session != nil { h.releaseInitialClaimLocked(start.session) @@ -1001,6 +1016,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed case <-ctx.Done(): + <-h.sessionStartWaiterSlots h.mu.Lock() if start.session != nil { h.releaseInitialClaimLocked(start.session) @@ -1052,6 +1068,10 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( case existingSession != nil && !existingSession.closed: discardStartedSession = true default: + // A completed persistent generation deliberately survives a + // transport gap when a counted joiner is canceled concurrently. + // Its initial claim is released by that joiner and the ordinary + // idle reaper bounds retention until the wrapper reconnects. startedSession.initialClaims = start.waiters if ownerContextErr == nil { startedSession.initialClaims++ @@ -1180,6 +1200,9 @@ func (h *wsPTYHub) releaseInitialClaimLocked(session *wsPTYSession) { } session.initialClaims-- h.activateInitialSessionIfReadyLocked(session) + // An awaiting persistent generation with no attachments is intentionally + // retained for reconnect and bounded by its idle timer. Only a generation + // that already exited before any claimant attached is removed immediately. if session.initialClaims != 0 || session.initialPhase != wsPTYSessionFinishedBeforeInitialAttachment || h.sessions[session.key] != session { From fc4eea26d83e62bd48dc93e17ba033f6a76c25e7 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:04:10 -0700 Subject: [PATCH 17/37] test: update persistent PTY retry contract --- cmuxTests/SSHPersistentPTYRetryLifecycleTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmuxTests/SSHPersistentPTYRetryLifecycleTests.swift b/cmuxTests/SSHPersistentPTYRetryLifecycleTests.swift index e7b84dbe8c0a..8048d2cb57df 100644 --- a/cmuxTests/SSHPersistentPTYRetryLifecycleTests.swift +++ b/cmuxTests/SSHPersistentPTYRetryLifecycleTests.swift @@ -94,6 +94,6 @@ extension CLINotifyProcessIntegrationRegressionTests { XCTAssertTrue(auth.lowerBound < retryLoop.lowerBound, script, file: file, line: line) XCTAssertEqual(script.components(separatedBy: "cmux_auth_status=$?").count - 1, 1, script, file: file, line: line) XCTAssertFalse(script.contains("case \"$cmux_auth_status\" in 254|255) exit 1"), script, file: file, line: line) - XCTAssertTrue(script.contains("case \"$cmux_ssh_status\" in 254|255"), script, file: file, line: line) + XCTAssertTrue(script.contains("case \"$cmux_ssh_status\" in 251|254|255"), script, file: file, line: line) } } From 9cf8c9b722ccf3b8024ac75f5c681c770715ef19 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:18:23 -0700 Subject: [PATCH 18/37] test(remote): hide retained fast-exit generations --- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index e779cf850be2..38c9dc1f715d 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -531,6 +531,18 @@ func TestAttachRPCFastExitCoalescedWaitersShareGeneration(t *testing.T) { close(releaseWaiter) t.Fatalf("fast-exit generation phase = %d, want finished-before-initial-attachment", initialPhase) } + if snapshots := hub.sessionSnapshots(); len(snapshots) != 0 { + close(releaseWaiter) + t.Fatalf("fast-exit generation remained visible as running: %+v", snapshots) + } + if status := hub.writeInputByID("coalesced-fast-exit", "first", "", nil); status != wsPTYInputWriteNotFound { + close(releaseWaiter) + t.Fatalf("fast-exit generation input status = %v, want not found", status) + } + if hub.resizeByID("coalesced-fast-exit", "first", "", 100, 30) { + close(releaseWaiter) + t.Fatal("fast-exit generation remained resizable") + } close(releaseWaiter) second := <-secondResult From a1109a0c5270c3d354f239d9eed0d9d426a65624 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:21:56 -0700 Subject: [PATCH 19/37] fix(remote): separate retained and live PTY state --- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 30 ++++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 6e1613786d98..436a20691104 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -171,8 +171,8 @@ const ( type wsPTYSessionInitialPhase uint8 -// The initial phase keeps a process that exits during attach startup visible -// until every caller coalesced onto that generation can observe ready + exit. +// The initial phase keeps a process that exits during attach startup claimable, +// but not live, until every coalesced caller can observe ready + exit. const ( wsPTYSessionInitialActive wsPTYSessionInitialPhase = iota wsPTYSessionAwaitingInitialAttachment @@ -966,7 +966,10 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( } if claimedSession != nil { session = claimedSession - if h.sessions[sessionKey] != session || session.closed { + claimableFinishedSession := ownsInitialClaim && + session.initialPhase == wsPTYSessionFinishedBeforeInitialAttachment + if h.sessions[sessionKey] != session || + (session.closed && !claimableFinishedSession) { h.releaseInitialClaimLocked(session) h.mu.Unlock() return nil, nil, nil, fmt.Errorf("persistent PTY session %q closed before attachment completed", sessionID) @@ -974,11 +977,12 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( break } session = h.sessions[sessionKey] + if session != nil && + session.initialPhase == wsPTYSessionFinishedBeforeInitialAttachment { + h.mu.Unlock() + return nil, nil, nil, fmt.Errorf("persistent PTY session %q is no longer running", sessionID) + } if session != nil && !session.closed { - if session.initialPhase == wsPTYSessionFinishedBeforeInitialAttachment { - h.mu.Unlock() - return nil, nil, nil, fmt.Errorf("persistent PTY session %q is no longer running", sessionID) - } if reservationReady != nil { reservationReady() } @@ -1841,7 +1845,13 @@ func (session *wsPTYSession) ptyFileSnapshot() *os.File { func (h *wsPTYHub) activeSessionCount() int { h.mu.Lock() defer h.mu.Unlock() - return len(h.sessions) + count := 0 + for _, session := range h.sessions { + if session != nil && !session.closed { + count++ + } + } + return count } func (h *wsPTYHub) maxScrollbackBytes() int { @@ -1886,11 +1896,11 @@ func (h *wsPTYHub) finishSession(session *wsPTYSession) { h.mu.Lock() if session.initialPhase == wsPTYSessionAwaitingInitialAttachment { session.initialPhase = wsPTYSessionFinishedBeforeInitialAttachment + session.closed = true + h.cancelIdleReapLocked(session) close(session.done) if session.initialClaims == 0 && h.sessions[session.key] == session { delete(h.sessions, session.key) - h.cancelIdleReapLocked(session) - session.closed = true } h.mu.Unlock() return From 9b2924540ded9cb5eb8e4add602272ea450641a1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:36:10 -0700 Subject: [PATCH 20/37] test: preserve daemon transport after PTY attach timeout --- ...DaemonRPCClientTimeoutIsolationTests.swift | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift new file mode 100644 index 000000000000..454fbf78f455 --- /dev/null +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -0,0 +1,123 @@ +import Darwin +import Foundation +import Testing +import CmuxCore +@testable import CmuxRemoteDaemon + +@Suite("RemoteDaemonRPCClient timeout isolation") +struct RemoteDaemonRPCClientTimeoutIsolationTests { + @Test("a timed-out PTY attach preserves the transport and existing PTY subscriptions") + func timedOutPTYAttachPreservesHealthyTransportState() throws { + let executable = try makeTransport() + defer { + try? FileManager.default.removeItem( + at: URL(fileURLWithPath: executable).deletingLastPathComponent() + ) + } + + let existingPTYEvent = DispatchSemaphore(value: 0) + let unexpectedTermination = DispatchSemaphore(value: 0) + let client = RemoteDaemonRPCClient( + configuration: configuration(), + remotePath: "/fake/cmuxd-remote", + strings: RemoteDaemonStrings( + missingPersistentPTYCapability: "missing persistent PTY", + missingRequiredFunctionality: "missing functionality" + ) + ) { _ in + unexpectedTermination.signal() + } + defer { client.stop() } + client.transportExecutableOverride = executable + + try client.start() + _ = try client.attachPTY( + sessionID: "existing-session", + attachmentID: "existing-attachment", + cols: 80, + rows: 24, + command: nil, + requireExisting: true, + queue: .global() + ) { event in + if case .data(let data) = event, data == Data("still-alive".utf8) { + existingPTYEvent.signal() + } + } + + do { + _ = try client.call( + method: "pty.attach", + params: [ + "session_id": "stalled-session", + "attachment_id": "stalled-attachment", + ], + timeout: 0.05 + ) + Issue.record("stalled pty.attach unexpectedly succeeded") + } catch { + let nsError = error as NSError + #expect(nsError.domain == "cmux.remote.daemon.rpc") + #expect(nsError.code == 11) + } + + let result = try client.call(method: "hello", params: [:], timeout: 1) + #expect(result["transport"] as? String == "alive") + #expect(existingPTYEvent.wait(timeout: .now() + 1) == .success) + #expect(unexpectedTermination.wait(timeout: .now()) == .timedOut) + } + + private func configuration() -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: "fake-host", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil, + preserveAfterTerminalExit: false, + persistentDaemonSlot: nil + ) + } + + private func makeTransport() throws -> String { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-remote-daemon-timeout-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let scriptURL = directory.appendingPathComponent("fake-ssh-timeout") + let script = """ + #!/bin/sh + read_id() { + printf '%s\\n' "$1" | sed -n 's/.*"id":\\([0-9][0-9]*\\).*/\\1/p' + } + if IFS= read -r line; then + id=$(read_id "$line") + printf '{"id":%s,"ok":true,"result":{"capabilities":["proxy.stream.push"]}}\\n' "$id" + else + exit 1 + fi + if IFS= read -r line; then + id=$(read_id "$line") + printf '{"id":%s,"ok":true,"result":{"attachment_id":"existing-attachment","attachment_token":"existing-token"}}\\n' "$id" + else + exit 1 + fi + if ! IFS= read -r _stalled_attach; then + exit 1 + fi + if IFS= read -r line; then + id=$(read_id "$line") + printf '{"event":"pty.data","session_id":"existing-session","attachment_id":"existing-attachment","attachment_token":"existing-token","data_base64":"c3RpbGwtYWxpdmU="}\\n' + printf '{"id":%s,"ok":true,"result":{"transport":"alive"}}\\n' "$id" + fi + while IFS= read -r _line; do :; done + """ + try Data(script.utf8).write(to: scriptURL, options: .atomic) + chmod(scriptURL.path, 0o755) + return scriptURL.path + } +} From 20725e8f88f33a790b6cd1a2f24739364fdc6772 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:40:15 -0700 Subject: [PATCH 21/37] fix: isolate PTY attach call timeouts --- .../Client/RemoteDaemonRPCClient+RPC.swift | 8 +++++++- .../RemoteDaemonRPCClientTimeoutIsolationTests.swift | 5 +++-- .../CLINotifyProcessIntegrationRegressionTests.swift | 2 +- cmuxTests/TabManagerSessionSnapshotTests.swift | 4 ++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift index 8fdd9f74de31..3023917a7b9e 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift @@ -333,7 +333,13 @@ extension RemoteDaemonRPCClient { let response: [String: Any] switch pendingCalls.wait(for: pendingCall, timeout: timeout) { case .timedOut: - stop(suppressTerminationCallback: false) + // pty.attach is dispatched independently by the daemon because + // PTY allocation can block inside the operating system. Its + // deadline removes only this pending call; it is not evidence + // that the shared transport or existing PTY subscriptions died. + if method != "pty.attach" { + stop(suppressTerminationCallback: false) + } throw NSError(domain: "cmux.remote.daemon.rpc", code: 11, userInfo: [ NSLocalizedDescriptionKey: "daemon RPC timeout waiting for \(method) response", ]) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index 454fbf78f455..ec1d6d81af62 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -102,7 +102,8 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { fi if IFS= read -r line; then id=$(read_id "$line") - printf '{"id":%s,"ok":true,"result":{"attachment_id":"existing-attachment","attachment_token":"existing-token"}}\\n' "$id" + existing_token=$(printf '%s\\n' "$line" | sed -n 's/.*"client_attachment_token":"\\([^"]*\\)".*/\\1/p') + printf '{"id":%s,"ok":true,"result":{"attachment_id":"existing-attachment","attachment_token":"%s"}}\\n' "$id" "$existing_token" else exit 1 fi @@ -111,7 +112,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { fi if IFS= read -r line; then id=$(read_id "$line") - printf '{"event":"pty.data","session_id":"existing-session","attachment_id":"existing-attachment","attachment_token":"existing-token","data_base64":"c3RpbGwtYWxpdmU="}\\n' + printf '{"event":"pty.data","session_id":"existing-session","attachment_id":"existing-attachment","attachment_token":"%s","data_base64":"c3RpbGwtYWxpdmU="}\\n' "$existing_token" printf '{"id":%s,"ok":true,"result":{"transport":"alive"}}\\n' "$id" fi while IFS= read -r _line; do :; done diff --git a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift index 93e193c0fbc2..8f896b3b0948 100644 --- a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift +++ b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift @@ -4695,7 +4695,7 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { XCTAssertTrue(initialCommand.contains(sessionId), initialCommand) XCTAssertTrue(initialCommand.contains("CMUX_WORKSPACE_ID"), initialCommand) XCTAssertTrue(initialCommand.contains("CMUX_SURFACE_ID"), initialCommand) - XCTAssertTrue(initialCommand.contains("254|255") && initialCommand.contains("CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS") && initialCommand.contains("∞"), initialCommand) + XCTAssertTrue(initialCommand.contains("251|254|255") && initialCommand.contains("CMUX_SSH_RECONNECT_MAX_DELAY_SECONDS") && initialCommand.contains("∞"), initialCommand) XCTAssertEqual(initialCommand.components(separatedBy: "/usr/bin/uuidgen").count - 1, 1, initialCommand) XCTAssertTrue(initialCommand.contains("ssh-session-end --lifecycle-only"), initialCommand) return self.v2Response( diff --git a/cmuxTests/TabManagerSessionSnapshotTests.swift b/cmuxTests/TabManagerSessionSnapshotTests.swift index 4ee841cb1d49..efc04014977a 100644 --- a/cmuxTests/TabManagerSessionSnapshotTests.swift +++ b/cmuxTests/TabManagerSessionSnapshotTests.swift @@ -2490,7 +2490,7 @@ final class TabManagerSessionSnapshotTests: XCTestCase { XCTAssertFalse(terminalStartupCommand.contains(expectedSessionID), terminalStartupCommand) XCTAssertFalse(terminalStartupCommand.contains("--require-existing"), terminalStartupCommand) XCTAssertTrue(terminalStartupCommand.contains("--command-b64 "), terminalStartupCommand) - XCTAssertTrue(terminalStartupCommand.contains("251|254|255"), terminalStartupCommand) + XCTAssertTrue(terminalStartupCommand.contains("251)") && terminalStartupCommand.contains("254)") && terminalStartupCommand.contains("255)"), terminalStartupCommand) let restoredDefaultRemoteCommand = try XCTUnwrap( Self.decodedSSHPTYCommandB64(in: terminalStartupCommand) ) @@ -2559,7 +2559,7 @@ final class TabManagerSessionSnapshotTests: XCTestCase { XCTAssertTrue(restoredInitialCommand.contains("workspace.remote.foreground_auth_ready"), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains(restoredForegroundAuthToken), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains("--require-existing"), restoredInitialCommand) - XCTAssertTrue(restoredInitialCommand.contains("251|254|255"), restoredInitialCommand) + XCTAssertTrue(restoredInitialCommand.contains("251)") && restoredInitialCommand.contains("254)") && restoredInitialCommand.contains("255)"), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains(expectedSessionID), restoredInitialCommand) XCTAssertTrue(restoredInitialCommand.contains("CMUX_SURFACE_ID"), restoredInitialCommand) XCTAssertFalse(restoredInitialCommand.contains("--command-b64 "), restoredInitialCommand) From 4ff9dedb1d79b96e97c375a54240f2c0b5a7b471 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 02:58:36 -0700 Subject: [PATCH 22/37] test: cancel timed-out remote PTY attaches --- ...DaemonRPCClientTimeoutIsolationTests.swift | 21 +- daemon/remote/cmd/cmuxd-remote/main_test.go | 202 ++++++++++++++++++ 2 files changed, 221 insertions(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index ec1d6d81af62..6937a48a2c4f 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -6,7 +6,7 @@ import CmuxCore @Suite("RemoteDaemonRPCClient timeout isolation") struct RemoteDaemonRPCClientTimeoutIsolationTests { - @Test("a timed-out PTY attach preserves the transport and existing PTY subscriptions") + @Test("a timed-out PTY attach cancels remotely while preserving the transport and subscriptions") func timedOutPTYAttachPreservesHealthyTransportState() throws { let executable = try makeTransport() defer { @@ -51,6 +51,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { params: [ "session_id": "stalled-session", "attachment_id": "stalled-attachment", + "client_attachment_token": "stalled-token", ], timeout: 0.05 ) @@ -107,7 +108,23 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { else exit 1 fi - if ! IFS= read -r _stalled_attach; then + if ! IFS= read -r stalled_attach; then + exit 1 + fi + stalled_id=$(read_id "$stalled_attach") + if IFS= read -r line; then + cancel_request_id=$(printf '%s\\n' "$line" | sed -n 's/.*"request_id":\\([0-9][0-9]*\\).*/\\1/p') + cancel_session=$(printf '%s\\n' "$line" | sed -n 's/.*"session_id":"\\([^"]*\\)".*/\\1/p') + cancel_attachment=$(printf '%s\\n' "$line" | sed -n 's/.*"attachment_id":"\\([^"]*\\)".*/\\1/p') + cancel_token=$(printf '%s\\n' "$line" | sed -n 's/.*"client_attachment_token":"\\([^"]*\\)".*/\\1/p') + case "$line" in *'"method":"pty.attach.cancel"'*) ;; *) exit 2 ;; esac + if [ "$cancel_request_id" != "$stalled_id" ] || + [ "$cancel_session" != "stalled-session" ] || + [ "$cancel_attachment" != "stalled-attachment" ] || + [ "$cancel_token" != "stalled-token" ]; then + exit 3 + fi + else exit 1 fi if IFS= read -r line; then diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index d5afd69bd7af..57586cad460f 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1278,6 +1278,208 @@ func TestStdioRPCStalledPTYAttachDoesNotBlockHealthyAttach(t *testing.T) { } } +func TestStdioRPCPTYAttachCancelStopsInFlightStartWithoutClosingConnection(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{ + Shell: "/bin/sh", + SessionIdleTTL: time.Hour, + }, io.Discard) + t.Cleanup(hub.closeAll) + + const healthySessionID = "cancel-keeps-transport-healthy" + if _, _, _, err := hub.attachRPC( + context.Background(), + healthySessionID, + "seed", + 80, + 24, + "sleep 30", + "seed-token", + false, + false, + ); err != nil { + t.Fatalf("seed healthy PTY session: %v", err) + } + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + var releaseStartOnce sync.Once + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + serverDone := make(chan error, 1) + go func() { + serverDone <- runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { + releaseStartOnce.Do(func() { close(releaseStart) }) + _ = stdinWriter.Close() + }) + + writer := bufio.NewWriter(stdinWriter) + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 1, + HasID: true, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "cancel-stalled-start", + "attachment_id": "stalled", + "client_attachment_token": "stalled-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("PTY attach never reached its stalled allocation") + } + + writePersistentTestFrame(t, writer, rpcRequest{ + Method: "pty.attach.cancel", + Params: map[string]any{ + "request_id": 1, + "session_id": "cancel-stalled-start", + "attachment_id": "stalled", + "client_attachment_token": "stalled-token", + }, + }) + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 2, + HasID: true, + Method: "pty.attach", + Params: map[string]any{ + "session_id": healthySessionID, + "attachment_id": "healthy", + "client_attachment_token": "healthy-token", + "cols": 80, + "rows": 24, + "require_existing": true, + }, + }) + healthyResponse := waitForRPCResponseID(t, output, 2, time.Second) + if ok, _ := healthyResponse["ok"].(bool); !ok { + t.Fatalf("healthy attach behind canceled start failed: %v", healthyResponse) + } + if strings.Contains(output.String(), `unknown method "pty.attach.cancel"`) { + t.Fatalf("PTY attach cancellation was treated as an ordinary RPC: %q", output.String()) + } + + releaseStartOnce.Do(func() { close(releaseStart) }) + deadline := time.Now().Add(5 * time.Second) + for { + hub.mu.Lock() + _, starting := hub.startingSessions[persistentPTYSessionKey("cancel-stalled-start")] + _, published := hub.sessions[persistentPTYSessionKey("cancel-stalled-start")] + hub.mu.Unlock() + if !starting { + if published { + t.Fatal("canceled PTY start was published after allocation returned") + } + break + } + if time.Now().After(deadline) { + t.Fatal("canceled PTY start did not finish after allocation returned") + } + time.Sleep(5 * time.Millisecond) + } + + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 3, + HasID: true, + Method: "ping", + }) + ping := waitForRPCResponseID(t, output, 3, time.Second) + if ok, _ := ping["ok"].(bool); !ok { + t.Fatalf("RPC transport stopped after canceling one PTY attach: %v", ping) + } + select { + case err := <-serverDone: + t.Fatalf("RPC server exited after PTY attach cancellation: %v", err) + default: + } +} + +func TestStdioRPCLatePTYAttachCancelDropsPublishedAttachment(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{ + Shell: "/bin/sh", + SessionIdleTTL: time.Hour, + }, io.Discard) + t.Cleanup(hub.closeAll) + + stdinReader, stdinWriter := io.Pipe() + output := newNotifyingBuffer() + go func() { + _ = runRPCServer(stdinReader, output, hub, false) + }() + t.Cleanup(func() { _ = stdinWriter.Close() }) + + writer := bufio.NewWriter(stdinWriter) + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 41, + HasID: true, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "late-cancel-session", + "attachment_id": "surface", + "client_attachment_token": "timed-out-token", + "cols": 80, + "rows": 24, + "command": "sleep 30", + }, + }) + response := waitForRPCResponseID(t, output, 41, 5*time.Second) + if ok, _ := response["ok"].(bool); !ok { + t.Fatalf("initial PTY attach failed: %v", response) + } + waitForHubSessionSize(t, hub, "late-cancel-session", 1, 80, 24, time.Second) + + writePersistentTestFrame(t, writer, rpcRequest{ + Method: "pty.attach.cancel", + Params: map[string]any{ + "request_id": 41, + "session_id": "late-cancel-session", + "attachment_id": "surface", + "client_attachment_token": "timed-out-token", + }, + }) + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 42, + HasID: true, + Method: "ping", + }) + ping := waitForRPCResponseID(t, output, 42, time.Second) + if ok, _ := ping["ok"].(bool); !ok { + t.Fatalf("ping after late PTY attach cancellation failed: %v", ping) + } + waitForHubSessionSize(t, hub, "late-cancel-session", 0, 80, 24, time.Second) + + writePersistentTestFrame(t, writer, rpcRequest{ + ID: 43, + HasID: true, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "late-cancel-session", + "attachment_id": "surface", + "client_attachment_token": "replacement-token", + "cols": 100, + "rows": 30, + "require_existing": true, + }, + }) + replacement := waitForRPCResponseID(t, output, 43, time.Second) + if ok, _ := replacement["ok"].(bool); !ok { + t.Fatalf("replacement attach after late cancellation failed: %v", replacement) + } + waitForHubSessionSize(t, hub, "late-cancel-session", 1, 100, 30, time.Second) +} + func TestStdioRPCCloseOvertakesStalledPTYStart(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) From 52fcbf8544ee09f0ff7908664348c5ad9e4b364c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:01:52 -0700 Subject: [PATCH 23/37] fix(remote): cancel timed-out PTY attach requests --- .../Client/RemoteDaemonRPCClient+RPC.swift | 38 ++++- daemon/remote/cmd/cmuxd-remote/main.go | 160 +++++++++++++++--- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 26 ++- 3 files changed, 191 insertions(+), 33 deletions(-) diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift index 3023917a7b9e..19e3d38cb992 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift @@ -293,7 +293,12 @@ extension RemoteDaemonRPCClient { throw error } - return try waitForCall(pendingCall, method: method, timeout: timeout) + return try waitForCall( + pendingCall, + method: method, + params: params, + timeout: timeout + ) } /// Sends an RPC only when the transport has no unanswered application @@ -322,12 +327,18 @@ extension RemoteDaemonRPCClient { } guard let admittedCall else { return nil } - return try waitForCall(admittedCall, method: method, timeout: timeout) + return try waitForCall( + admittedCall, + method: method, + params: params, + timeout: timeout + ) } private func waitForCall( _ pendingCall: RemoteDaemonPendingCallRegistry.PendingCall, method: String, + params: [String: Any], timeout: TimeInterval ) throws -> [String: Any] { let response: [String: Any] @@ -337,7 +348,12 @@ extension RemoteDaemonRPCClient { // PTY allocation can block inside the operating system. Its // deadline removes only this pending call; it is not evidence // that the shared transport or existing PTY subscriptions died. - if method != "pty.attach" { + if method == "pty.attach" { + sendPTYAttachCancellation( + requestID: pendingCall.id, + attachParams: params + ) + } else { stop(suppressTerminationCallback: false) } throw NSError(domain: "cmux.remote.daemon.rpc", code: 11, userInfo: [ @@ -369,6 +385,22 @@ extension RemoteDaemonRPCClient { ]) } + private func sendPTYAttachCancellation( + requestID: Int, + attachParams: [String: Any] + ) { + var cancellationParams: [String: Any] = ["request_id": requestID] + for key in ["session_id", "attachment_id", "client_attachment_token"] { + if let value = attachParams[key] as? String { + cancellationParams[key] = value + } + } + try? notify( + method: "pty.attach.cancel", + params: cancellationParams + ) + } + func notify(method: String, params: [String: Any]) throws { let payload: Data do { diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index b2e88afebd3a..6b2c88370cd2 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -116,12 +116,24 @@ type rpcServer struct { } type rpcRequestDispatcher struct { - ctx context.Context - cancelConnection context.CancelFunc - interruptRead func() - server *rpcServer - ptyAttachSlots chan struct{} - asyncErrors chan error + ctx context.Context + cancelConnection context.CancelFunc + interruptRead func() + server *rpcServer + ptyAttachSlots chan struct{} + // Request cancellation is separate from attachment lifetime: completed + // attachments remain connection-owned after their request leaves this map. + ptyAttachMu sync.Mutex + ptyAttachRequests map[string]*rpcPTYAttachRequest + asyncErrors chan error +} + +type rpcPTYAttachRequest struct { + requestIDKey string + sessionID string + attachmentID string + attachmentToken string + cancel context.CancelFunc } func newRPCRequestDispatcher( @@ -131,12 +143,13 @@ func newRPCRequestDispatcher( server *rpcServer, ) *rpcRequestDispatcher { return &rpcRequestDispatcher{ - ctx: ctx, - cancelConnection: cancelConnection, - interruptRead: interruptRead, - server: server, - ptyAttachSlots: make(chan struct{}, maxConcurrentPTYAttachRPCsPerConnection), - asyncErrors: make(chan error, 1), + ctx: ctx, + cancelConnection: cancelConnection, + interruptRead: interruptRead, + server: server, + ptyAttachSlots: make(chan struct{}, maxConcurrentPTYAttachRPCsPerConnection), + ptyAttachRequests: map[string]*rpcPTYAttachRequest{}, + asyncErrors: make(chan error, 1), } } @@ -146,6 +159,10 @@ func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { // writers serialize the resulting concurrent response writes. Before // reading the next request, wait only until the attach has reserved or // selected its hub generation so a following pty.close cannot overtake it. + if req.Method == "pty.attach.cancel" { + d.cancelPTYAttach(req) + return nil + } if req.Method != "pty.attach" { return d.server.handleRequestAndWriteResponse(req) } @@ -165,10 +182,24 @@ func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { }) } + attachCtx, attachRequest, registered := d.registerPTYAttach(req) + if !registered { + <-d.ptyAttachSlots + return d.server.frameWriter.writeResponse(rpcResponse{ + ID: req.ID, + OK: false, + Error: &rpcError{ + Code: "invalid_request", + Message: "PTY attach request id is already in progress", + }, + }) + } + reservationReady := make(chan struct{}) go func() { defer func() { <-d.ptyAttachSlots }() - if err := d.server.handlePTYAttachAndWriteResponseWithReservation(d.ctx, req, func() { + defer d.finishPTYAttach(attachRequest) + if err := d.server.handlePTYAttachAndWriteResponseWithReservation(attachCtx, d.ctx, req, func() { close(reservationReady) }); err != nil { select { @@ -189,6 +220,84 @@ func (d *rpcRequestDispatcher) dispatch(req rpcRequest) error { } } +func (d *rpcRequestDispatcher) registerPTYAttach(req rpcRequest) (context.Context, *rpcPTYAttachRequest, bool) { + ctx, cancel := context.WithCancel(d.ctx) + request := &rpcPTYAttachRequest{cancel: cancel} + request.sessionID, _ = getStringParam(req.Params, "session_id") + request.attachmentID, _ = getStringParam(req.Params, "attachment_id") + request.attachmentToken, _ = getStringParam(req.Params, "client_attachment_token") + request.sessionID = strings.TrimSpace(request.sessionID) + request.attachmentID = strings.TrimSpace(request.attachmentID) + request.attachmentToken = strings.TrimSpace(request.attachmentToken) + + requestIDKey, hasRequestID := normalizedRPCRequestID(req.ID) + if !req.HasID || !hasRequestID { + return ctx, request, true + } + request.requestIDKey = requestIDKey + + d.ptyAttachMu.Lock() + defer d.ptyAttachMu.Unlock() + if _, exists := d.ptyAttachRequests[requestIDKey]; exists { + cancel() + return nil, nil, false + } + d.ptyAttachRequests[requestIDKey] = request + return ctx, request, true +} + +func (d *rpcRequestDispatcher) finishPTYAttach(request *rpcPTYAttachRequest) { + if request == nil { + return + } + request.cancel() + if request.requestIDKey == "" { + return + } + d.ptyAttachMu.Lock() + if current := d.ptyAttachRequests[request.requestIDKey]; current == request { + delete(d.ptyAttachRequests, request.requestIDKey) + } + d.ptyAttachMu.Unlock() +} + +func (d *rpcRequestDispatcher) cancelPTYAttach(req rpcRequest) { + requestID, hasRequestID := req.Params["request_id"] + requestIDKey, normalized := normalizedRPCRequestID(requestID) + var request *rpcPTYAttachRequest + if hasRequestID && normalized { + d.ptyAttachMu.Lock() + request = d.ptyAttachRequests[requestIDKey] + d.ptyAttachMu.Unlock() + } + + sessionID, _ := getStringParam(req.Params, "session_id") + attachmentID, _ := getStringParam(req.Params, "attachment_id") + attachmentToken, _ := getStringParam(req.Params, "client_attachment_token") + if request != nil { + request.cancel() + sessionID = request.sessionID + attachmentID = request.attachmentID + attachmentToken = request.attachmentToken + } + // The identity cleanup closes the race where the attach completed and left + // the request map just before its timeout notification arrived. + if d.server.ptyHub != nil { + d.server.ptyHub.detachByID(sessionID, attachmentID, attachmentToken) + } +} + +func normalizedRPCRequestID(id any) (string, bool) { + if id == nil { + return "", false + } + encoded, err := json.Marshal(id) + if err != nil { + return "", false + } + return string(encoded), true +} + func (d *rpcRequestDispatcher) takeAsyncError() error { select { case err := <-d.asyncErrors: @@ -1578,6 +1687,7 @@ func (s *rpcServer) handleRequest(req rpcRequest) rpcResponse { "pty.session.persistent_daemon", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", "pty.input.seq_ack", "cli.bridge", }, @@ -1646,16 +1756,22 @@ func (s *rpcServer) handleRequestAndWriteResponse(req rpcRequest) error { } func (s *rpcServer) handlePTYAttachAndWriteResponse(ctx context.Context, req rpcRequest) error { - return s.handlePTYAttachAndWriteResponseWithReservation(ctx, req, nil) + return s.handlePTYAttachAndWriteResponseWithReservation(ctx, ctx, req, nil) } func (s *rpcServer) handlePTYAttachAndWriteResponseWithReservation( - ctx context.Context, + operationCtx context.Context, + attachmentLifetimeCtx context.Context, req rpcRequest, reservationReady func(), ) error { - response := s.handlePTYAttachContextWithReservation(ctx, req, reservationReady) - if ctx.Err() != nil { + response := s.handlePTYAttachContextWithReservation( + operationCtx, + attachmentLifetimeCtx, + req, + reservationReady, + ) + if operationCtx.Err() != nil { return nil } return s.frameWriter.writeResponse(response) @@ -2212,11 +2328,12 @@ func (s *rpcServer) handlePTYAttach(req rpcRequest) rpcResponse { } func (s *rpcServer) handlePTYAttachContext(ctx context.Context, req rpcRequest) rpcResponse { - return s.handlePTYAttachContextWithReservation(ctx, req, nil) + return s.handlePTYAttachContextWithReservation(ctx, ctx, req, nil) } func (s *rpcServer) handlePTYAttachContextWithReservation( - ctx context.Context, + operationCtx context.Context, + attachmentLifetimeCtx context.Context, req rpcRequest, reservationReady func(), ) rpcResponse { @@ -2287,7 +2404,8 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( } } attachment, attachmentCtx, sessionDone, err := hub.attachRPCWithReservation( - ctx, + operationCtx, + attachmentLifetimeCtx, sessionID, attachmentID, cols, @@ -2308,7 +2426,7 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( }, } } - if err := ctx.Err(); err != nil { + if err := operationCtx.Err(); err != nil { hub.dropAttachment(attachment) return rpcResponse{ ID: req.ID, diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 436a20691104..ac685a1e5cbb 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -853,6 +853,7 @@ func (h *wsPTYHub) attachRPC( inputSeqAck bool, ) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { return h.attachRPCWithReservation( + ctx, ctx, sessionID, attachmentID, @@ -867,7 +868,8 @@ func (h *wsPTYHub) attachRPC( } func (h *wsPTYHub) attachRPCWithReservation( - ctx context.Context, + operationCtx context.Context, + attachmentLifetimeCtx context.Context, sessionID string, attachmentID string, cols int, @@ -885,7 +887,8 @@ func (h *wsPTYHub) attachRPCWithReservation( attachmentID = strings.TrimSpace(attachmentID) cols, rows = normalizePTYSize(cols, rows) return h.prepareAttachmentWithReservation( - ctx, + operationCtx, + attachmentLifetimeCtx, nil, sessionID, attachmentID, @@ -914,6 +917,7 @@ func (h *wsPTYHub) prepareAttachment( inputSeqAck bool, ) (*wsPTYAttachment, context.Context, <-chan struct{}, error) { return h.prepareAttachmentWithReservation( + ctx, ctx, conn, sessionID, @@ -930,7 +934,8 @@ func (h *wsPTYHub) prepareAttachment( } func (h *wsPTYHub) prepareAttachmentWithReservation( - ctx context.Context, + operationCtx context.Context, + attachmentLifetimeCtx context.Context, conn *websocket.Conn, sessionID string, attachmentID string, @@ -1019,7 +1024,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( } h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed - case <-ctx.Done(): + case <-operationCtx.Done(): <-h.sessionStartWaiterSlots h.mu.Lock() if start.session != nil { @@ -1028,7 +1033,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( start.waiters-- } h.mu.Unlock() - return nil, nil, nil, ctx.Err() + return nil, nil, nil, operationCtx.Err() } continue } @@ -1058,7 +1063,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( h.mu.Lock() delete(h.startingSessions, sessionKey) if startErr == nil { - ownerContextErr := ctx.Err() + ownerContextErr := operationCtx.Err() switch existingSession := h.sessions[sessionKey]; { case h.closed: startErr = errWSPTYHubClosed @@ -1103,14 +1108,14 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( return nil, nil, nil, startErr } if publishedStartedSession && !ownsInitialClaim { - return nil, nil, nil, ctx.Err() + return nil, nil, nil, operationCtx.Err() } if publishedStartedSession { continue } } - if err := ctx.Err(); err != nil { + if err := operationCtx.Err(); err != nil { if ownsInitialClaim { h.releaseInitialClaimLocked(session) } @@ -1139,7 +1144,10 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( superseded = old } - attachmentCtx, cancel := context.WithCancel(ctx) + // Operation cancellation may abandon this attach without ending the + // connection. Once published, the attachment follows the connection + // lifetime and can be canceled independently by its identity token. + attachmentCtx, cancel := context.WithCancel(attachmentLifetimeCtx) clientToken = strings.TrimSpace(clientToken) attachment := &wsPTYAttachment{ sessionKey: sessionKey, From e63a9da88dfddd0da717253272333cb91f122b64 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:15:56 -0700 Subject: [PATCH 24/37] fix(remote): bound PTY attach cancellation writes --- .../Capabilities/RemoteDaemonCapability.swift | 4 + ...aemonRPCClient+PTYAttachCancellation.swift | 39 +++++++++ .../Client/RemoteDaemonRPCClient+RPC.swift | 16 ---- .../Client/RemoteDaemonRPCClient.swift | 5 ++ ...RemoteDaemonRPCClientCapabilityTests.swift | 3 + ...DaemonRPCClientTimeoutIsolationTests.swift | 81 +++++++++++++++++++ .../RemoteDaemonStringsTests.swift | 3 + .../Session/RemoteSessionCoordinator.swift | 6 +- .../RemotePortScanGatingTests.swift | 1 + 9 files changed, 137 insertions(+), 21 deletions(-) create mode 100644 Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Capabilities/RemoteDaemonCapability.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Capabilities/RemoteDaemonCapability.swift index e6b21b8e5e4b..f29a39c7bb01 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Capabilities/RemoteDaemonCapability.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Capabilities/RemoteDaemonCapability.swift @@ -16,6 +16,9 @@ public enum RemoteDaemonCapability: String, Sendable, CaseIterable { case ptyWriteNotification = "pty.write.notification" /// Resize notifications (`pty.resize.notification`). case ptyResizeNotification = "pty.resize.notification" + /// Canceling an in-flight PTY attach without closing the transport + /// (`pty.attach.cancel`). + case ptyAttachCancel = "pty.attach.cancel" /// Sequenced, cumulatively acknowledged PTY input (`pty.input.seq_ack`). case ptyInputSeqAck = "pty.input.seq_ack" @@ -27,5 +30,6 @@ public enum RemoteDaemonCapability: String, Sendable, CaseIterable { RemoteDaemonCapability.ptyPersistentDaemon.rawValue, RemoteDaemonCapability.ptyWriteNotification.rawValue, RemoteDaemonCapability.ptyResizeNotification.rawValue, + RemoteDaemonCapability.ptyAttachCancel.rawValue, ] } diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift new file mode 100644 index 000000000000..f284ea39c5cd --- /dev/null +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift @@ -0,0 +1,39 @@ +internal import Foundation + +extension RemoteDaemonRPCClient { + func sendPTYAttachCancellation( + requestID: Int, + attachParams: [String: Any] + ) { + var cancellationParams: [String: Any] = ["request_id": requestID] + for key in ["session_id", "attachment_id", "client_attachment_token"] { + if let value = attachParams[key] as? String { + cancellationParams[key] = value + } + } + guard let payload = try? Self.encodeJSON([ + "method": "pty.attach.cancel", + "params": cancellationParams, + ]) else { + stop(suppressTerminationCallback: false) + return + } + + // The attach deadline has already expired, so cancellation must not + // make that synchronous caller wait on a congested transport writer. + // If the queued write cannot finish promptly, the transport is no + // longer safe to preserve and the established stop path takes over. + let writeFinished = DispatchSemaphore(value: 0) + writeQueue.async { [weak self] in + defer { writeFinished.signal() } + guard let self else { return } + try? self.writePayload(payload) + } + DispatchQueue.global(qos: .utility).asyncAfter( + deadline: .now() + Self.ptyAttachCancellationWriteTimeout + ) { [weak self] in + guard writeFinished.wait(timeout: .now()) == .timedOut else { return } + self?.stop(suppressTerminationCallback: false) + } + } +} diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift index 19e3d38cb992..fe4b714a10c4 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift @@ -385,22 +385,6 @@ extension RemoteDaemonRPCClient { ]) } - private func sendPTYAttachCancellation( - requestID: Int, - attachParams: [String: Any] - ) { - var cancellationParams: [String: Any] = ["request_id": requestID] - for key in ["session_id", "attachment_id", "client_attachment_token"] { - if let value = attachParams[key] as? String { - cancellationParams[key] = value - } - } - try? notify( - method: "pty.attach.cancel", - params: cancellationParams - ) - } - func notify(method: String, params: [String: Any]) throws { let payload: Data do { diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift index 0296de2fea0e..d87b7077f43a 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift @@ -41,6 +41,7 @@ public final class RemoteDaemonRPCClient: @unchecked Sendable { static let bakedVMDaemonSocketPath = "/run/cmuxd-remote.sock" static let socketForwardStartupGracePeriod: TimeInterval = 0.75 static let webSocketKeepaliveInterval: TimeInterval = 5.0 + static let ptyAttachCancellationWriteTimeout: TimeInterval = 1.0 /// Wire capability required for push-based proxy streaming /// (`proxy.stream.push`; value is test-pinned, do not change). public static let requiredProxyStreamCapability = RemoteDaemonCapability.proxyStreamPush.rawValue @@ -59,6 +60,9 @@ public final class RemoteDaemonRPCClient: @unchecked Sendable { /// Wire capability required for resize notifications /// (`pty.resize.notification`; value is test-pinned, do not change). public static let requiredPTYResizeNotificationCapability = RemoteDaemonCapability.ptyResizeNotification.rawValue + /// Wire capability required to cancel timed-out PTY attach requests + /// (`pty.attach.cancel`; value is test-pinned, do not change). + public static let requiredPTYAttachCancelCapability = RemoteDaemonCapability.ptyAttachCancel.rawValue /// Optional wire capability for sequenced, acked PTY input /// (`pty.input.seq_ack`; value is test-pinned, do not change). public static let optionalPTYInputSeqAckCapability = RemoteDaemonCapability.ptyInputSeqAck.rawValue @@ -222,6 +226,7 @@ public final class RemoteDaemonRPCClient: @unchecked Sendable { capabilities.append(requiredPTYSessionTokenCapability) capabilities.append(requiredPTYWriteNotificationCapability) capabilities.append(requiredPTYResizeNotificationCapability) + capabilities.append(requiredPTYAttachCancelCapability) } if configuration.persistentDaemonSlot != nil { capabilities.append(requiredPTYPersistentDaemonCapability) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientCapabilityTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientCapabilityTests.swift index 17ca53c65c66..5fc78dcb3e12 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientCapabilityTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientCapabilityTests.swift @@ -32,6 +32,7 @@ struct RemoteDaemonRPCClientCapabilityTests { #expect(RemoteDaemonRPCClient.requiredPTYPersistentDaemonCapability == "pty.session.persistent_daemon") #expect(RemoteDaemonRPCClient.requiredPTYWriteNotificationCapability == "pty.write.notification") #expect(RemoteDaemonRPCClient.requiredPTYResizeNotificationCapability == "pty.resize.notification") + #expect(RemoteDaemonRPCClient.requiredPTYAttachCancelCapability == "pty.attach.cancel") #expect(RemoteDaemonRPCClient.optionalPTYInputSeqAckCapability == "pty.input.seq_ack") #expect(RemoteDaemonRPCClient.ptyInputSeqGapErrorCode == "pty_input_seq_gap") } @@ -55,6 +56,7 @@ struct RemoteDaemonRPCClientCapabilityTests { "pty.session.token", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", ] ) } @@ -73,6 +75,7 @@ struct RemoteDaemonRPCClientCapabilityTests { "pty.session.token", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", "pty.session.persistent_daemon", ] ) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index 6937a48a2c4f..853697cc18ed 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -68,6 +68,86 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { #expect(unexpectedTermination.wait(timeout: .now()) == .timedOut) } + @Test("a timed-out PTY attach does not wait for a blocked cancellation write") + func timedOutPTYAttachBoundsCancellationWrite() throws { + let executable = try makeTransport() + defer { + try? FileManager.default.removeItem( + at: URL(fileURLWithPath: executable).deletingLastPathComponent() + ) + } + + let stalledAttachRead = DispatchSemaphore(value: 0) + let unexpectedTermination = DispatchSemaphore(value: 0) + let client = RemoteDaemonRPCClient( + configuration: configuration(), + remotePath: "/fake/cmuxd-remote", + strings: RemoteDaemonStrings( + missingPersistentPTYCapability: "missing persistent PTY", + missingRequiredFunctionality: "missing functionality" + ) + ) { _ in + unexpectedTermination.signal() + } + defer { client.stop() } + client.transportExecutableOverride = executable + + try client.start() + _ = try client.attachPTY( + sessionID: "existing-session", + attachmentID: "existing-attachment", + cols: 80, + rows: 24, + command: nil, + requireExisting: true, + queue: .global() + ) { event in + if case .data(let data) = event, data == Data("attach-read".utf8) { + stalledAttachRead.signal() + } + } + + let writeBlockEntered = DispatchSemaphore(value: 0) + let releaseWrite = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + guard stalledAttachRead.wait(timeout: .now() + 2) == .success else { + releaseWrite.signal() + return + } + client.writeQueue.async { + writeBlockEntered.signal() + releaseWrite.wait() + } + } + DispatchQueue.global().asyncAfter(deadline: .now() + 4) { + releaseWrite.signal() + } + + let startedAt = DispatchTime.now() + do { + _ = try client.call( + method: "pty.attach", + params: [ + "session_id": "stalled-session", + "attachment_id": "stalled-attachment", + "client_attachment_token": "stalled-token", + ], + timeout: 1 + ) + Issue.record("stalled pty.attach unexpectedly succeeded") + } catch { + let nsError = error as NSError + #expect(nsError.domain == "cmux.remote.daemon.rpc") + #expect(nsError.code == 11) + } + let elapsed = Double(DispatchTime.now().uptimeNanoseconds - startedAt.uptimeNanoseconds) / 1_000_000_000 + + #expect(writeBlockEntered.wait(timeout: .now()) == .success) + #expect(elapsed < 2) + #expect(unexpectedTermination.wait(timeout: .now() + 2) == .success) + releaseWrite.signal() + } + private func configuration() -> WorkspaceRemoteConfiguration { WorkspaceRemoteConfiguration( destination: "fake-host", @@ -112,6 +192,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { exit 1 fi stalled_id=$(read_id "$stalled_attach") + printf '{"event":"pty.data","session_id":"existing-session","attachment_id":"existing-attachment","attachment_token":"%s","data_base64":"YXR0YWNoLXJlYWQ="}\\n' "$existing_token" if IFS= read -r line; then cancel_request_id=$(printf '%s\\n' "$line" | sed -n 's/.*"request_id":\\([0-9][0-9]*\\).*/\\1/p') cancel_session=$(printf '%s\\n' "$line" | sed -n 's/.*"session_id":"\\([^"]*\\)".*/\\1/p') diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonStringsTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonStringsTests.swift index 2ea7f5bb8fda..f2baf86d0d76 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonStringsTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonStringsTests.swift @@ -11,6 +11,7 @@ struct RemoteDaemonCapabilityTests { #expect(RemoteDaemonCapability.ptyPersistentDaemon.rawValue == "pty.session.persistent_daemon") #expect(RemoteDaemonCapability.ptyWriteNotification.rawValue == "pty.write.notification") #expect(RemoteDaemonCapability.ptyResizeNotification.rawValue == "pty.resize.notification") + #expect(RemoteDaemonCapability.ptyAttachCancel.rawValue == "pty.attach.cancel") #expect(RemoteDaemonCapability.ptyInputSeqAck.rawValue == "pty.input.seq_ack") } @@ -22,6 +23,7 @@ struct RemoteDaemonCapabilityTests { "pty.session.persistent_daemon", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", ]) } } @@ -41,6 +43,7 @@ struct RemoteDaemonStringsTests { "pty.session.persistent_daemon", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", ] { #expect( strings.missingRequiredCapabilitiesMessage([capability]) diff --git a/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator.swift b/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator.swift index a778dff079d1..2d0a78b4cdf6 100644 --- a/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator.swift +++ b/Packages/macOS/CmuxRemoteSession/Sources/CmuxRemoteSession/Session/RemoteSessionCoordinator.swift @@ -508,11 +508,7 @@ public final class RemoteSessionCoordinator: @unchecked Sendable { var bakedDaemonPreflightRequiredCapabilities: [String] { requiredDaemonCapabilities.filter { - $0 != RemoteDaemonRPCClient.requiredPTYSessionCapability && - $0 != RemoteDaemonRPCClient.requiredPTYSessionTokenCapability && - $0 != RemoteDaemonRPCClient.requiredPTYPersistentDaemonCapability && - $0 != RemoteDaemonRPCClient.requiredPTYWriteNotificationCapability && - $0 != RemoteDaemonRPCClient.requiredPTYResizeNotificationCapability + !RemoteDaemonCapability.persistentPTYFamily.contains($0) } } diff --git a/Packages/macOS/CmuxRemoteSession/Tests/CmuxRemoteSessionTests/RemotePortScanGatingTests.swift b/Packages/macOS/CmuxRemoteSession/Tests/CmuxRemoteSessionTests/RemotePortScanGatingTests.swift index 16bdce028256..c3bd3c85f063 100644 --- a/Packages/macOS/CmuxRemoteSession/Tests/CmuxRemoteSessionTests/RemotePortScanGatingTests.swift +++ b/Packages/macOS/CmuxRemoteSession/Tests/CmuxRemoteSessionTests/RemotePortScanGatingTests.swift @@ -291,6 +291,7 @@ struct RemotePortScanGatingTests { "pty.session.token", "pty.write.notification", "pty.resize.notification", + "pty.attach.cancel", "pty.session.persistent_daemon", ]) #expect(coordinator.bakedDaemonPreflightRequiredCapabilities == ["proxy.stream.push"]) From 622b30296704eae68d0694e4b29cff8d4c8b33b3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:23:33 -0700 Subject: [PATCH 25/37] fix(remote): use cancellable attach timeout timers --- ...aemonRPCClient+PTYAttachCancellation.swift | 25 +++++++++++++------ .../Client/RemoteDaemonRPCClient.swift | 1 + ...DaemonRPCClientTimeoutIsolationTests.swift | 15 ++++++++--- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift index f284ea39c5cd..0a7ab8b4f0c9 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+PTYAttachCancellation.swift @@ -1,4 +1,5 @@ internal import Foundation +internal import CmuxFoundation extension RemoteDaemonRPCClient { func sendPTYAttachCancellation( @@ -23,17 +24,25 @@ extension RemoteDaemonRPCClient { // make that synchronous caller wait on a congested transport writer. // If the queued write cannot finish promptly, the transport is no // longer safe to preserve and the established stop path takes over. - let writeFinished = DispatchSemaphore(value: 0) + // The timer callback and write completion race to settle this one + // deadline; a lock-free gate avoids shared mutable lifecycle state. + let deadlineSettled = AtomicBooleanGate(false) + // A one-shot DispatchSource is required here because this legacy + // synchronous client has no async task in which to host the deadline. + let timeoutTimer = DispatchSource.makeTimerSource(queue: ptyAttachCancellationTimerQueue) + timeoutTimer.schedule(deadline: .now() + Self.ptyAttachCancellationWriteTimeout) + timeoutTimer.setEventHandler { [weak self] in + guard deadlineSettled.compareExchange(expected: false, desired: true) else { return } + self?.stop(suppressTerminationCallback: false) + } + timeoutTimer.resume() writeQueue.async { [weak self] in - defer { writeFinished.signal() } + defer { + _ = deadlineSettled.compareExchange(expected: false, desired: true) + timeoutTimer.cancel() + } guard let self else { return } try? self.writePayload(payload) } - DispatchQueue.global(qos: .utility).asyncAfter( - deadline: .now() + Self.ptyAttachCancellationWriteTimeout - ) { [weak self] in - guard writeFinished.wait(timeout: .now()) == .timedOut else { return } - self?.stop(suppressTerminationCallback: false) - } } } diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift index d87b7077f43a..ff336051ce62 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient.swift @@ -114,6 +114,7 @@ public final class RemoteDaemonRPCClient: @unchecked Sendable { var transportExecutableOverride: String? let onUnexpectedTermination: (String) -> Void let transportKeepaliveQueue = DispatchQueue(label: "com.cmux.remote-ssh.daemon-rpc.keepalive.\(UUID().uuidString)") + let ptyAttachCancellationTimerQueue = DispatchQueue(label: "com.cmux.remote-ssh.daemon-rpc.pty-attach-cancel-timeout.\(UUID().uuidString)") let writeQueue = DispatchQueue(label: "com.cmux.remote-ssh.daemon-rpc.write.\(UUID().uuidString)") let stateQueue = DispatchQueue(label: "com.cmux.remote-ssh.daemon-rpc.state.\(UUID().uuidString)") let cliRequestQueue = DispatchQueue(label: "com.cmux.remote-ssh.daemon-rpc.cli.\(UUID().uuidString)", qos: .utility, attributes: .concurrent) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index 853697cc18ed..acd115c7a394 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -109,7 +109,8 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { let writeBlockEntered = DispatchSemaphore(value: 0) let releaseWrite = DispatchSemaphore(value: 0) - DispatchQueue.global().async { + let writeBlockQueue = DispatchQueue(label: "com.cmux.tests.remote-daemon.block-cancellation-write") + writeBlockQueue.async { guard stalledAttachRead.wait(timeout: .now() + 2) == .success else { releaseWrite.signal() return @@ -119,7 +120,16 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { releaseWrite.wait() } } - DispatchQueue.global().asyncAfter(deadline: .now() + 4) { + // One-shot failure safety keeps a regressed synchronous cancellation + // from stranding the test process; ordinary cleanup is deterministic. + let cleanupTimer = DispatchSource.makeTimerSource(queue: writeBlockQueue) + cleanupTimer.schedule(deadline: .now() + 4) + cleanupTimer.setEventHandler { + releaseWrite.signal() + } + cleanupTimer.resume() + defer { + cleanupTimer.cancel() releaseWrite.signal() } @@ -145,7 +155,6 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { #expect(writeBlockEntered.wait(timeout: .now()) == .success) #expect(elapsed < 2) #expect(unexpectedTermination.wait(timeout: .now() + 2) == .success) - releaseWrite.signal() } private func configuration() -> WorkspaceRemoteConfiguration { From 3762e098f2855c143ef1d01e837b4263b3162ff6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:45:29 -0700 Subject: [PATCH 26/37] test(remote): pin canceled start publication race --- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index 38c9dc1f715d..bbe50b0b8368 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -430,6 +430,95 @@ func TestAttachRPCSharedStartSurvivesOwnerCancellation(t *testing.T) { } } +func TestAttachRPCSharedStartDropsWaitersCanceledBeforePublication(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) + t.Cleanup(hub.closeAll) + + openPTY := hub.openPTY + startEntered := make(chan struct{}) + releaseStart := make(chan struct{}) + hub.openPTY = func() (*os.File, *os.File, error) { + close(startEntered) + <-releaseStart + return openPTY() + } + + connectionCtx, cancelConnection := context.WithCancel(context.Background()) + ownerResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + connectionCtx, + "connection-canceled-session", + "owner", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + ownerResult <- err + }() + select { + case <-startEntered: + case <-time.After(5 * time.Second): + t.Fatal("start owner never attempted PTY allocation") + } + + waiterDoneObserved := make(chan struct{}, 1) + releaseWaiterDone := make(chan struct{}) + waiterReleased := false + defer func() { + if !waiterReleased { + close(releaseWaiterDone) + } + }() + waiterResult := make(chan error, 1) + go func() { + _, _, _, err := hub.attachRPC( + gatedDoneContext{ + Context: connectionCtx, + observed: waiterDoneObserved, + release: releaseWaiterDone, + }, + "connection-canceled-session", + "waiter", + 80, + 24, + "sleep 30", + "", + false, + false, + ) + waiterResult <- err + }() + select { + case <-waiterDoneObserved: + case <-time.After(time.Second): + close(releaseStart) + t.Fatal("same-connection waiter did not join the in-flight start") + } + + cancelConnection() + close(releaseStart) + if err := <-ownerResult; !errors.Is(err, context.Canceled) { + t.Fatalf("canceled start owner error = %v, want context canceled", err) + } + + hub.mu.Lock() + _, published := hub.sessions[persistentPTYSessionKey("connection-canceled-session")] + hub.mu.Unlock() + if published { + t.Fatal("start published a session for waiters canceled before publication") + } + + close(releaseWaiterDone) + waiterReleased = true + if err := <-waiterResult; !errors.Is(err, context.Canceled) { + t.Fatalf("canceled start waiter error = %v, want context canceled", err) + } +} + func TestAttachRPCFastExitCoalescedWaitersShareGeneration(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) From 05d4570c97dc79866f7e4080644c978f495068c2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:48:25 -0700 Subject: [PATCH 27/37] fix(remote): linearize PTY start waiter cancellation --- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 48 +++++++++++++++++------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index ac685a1e5cbb..3fe811c31257 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -221,12 +221,18 @@ type wsPTYSessionStart struct { done chan struct{} err error session *wsPTYSession - // waiters counts joiners only until the owner publishes or discards the - // completed start; the count is never consulted after done closes. - waiters int + // waiters retains the contexts of joiners until the owner publishes or + // discards the completed start. Publication marks only contexts that are + // still live as initial claimants, linearizing disconnect against publish. + waiters map[*wsPTYSessionStartWaiter]struct{} closeRequested bool } +type wsPTYSessionStartWaiter struct { + ctx context.Context + claimed bool +} + type wsPTYHub struct { mu sync.Mutex sessions map[wsPTYSessionKey]*wsPTYSession @@ -1000,7 +1006,8 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( h.mu.Unlock() return nil, nil, nil, errWSPTYStartWaitersSaturated } - start.waiters++ + waiter := &wsPTYSessionStartWaiter{ctx: operationCtx} + start.waiters[waiter] = struct{}{} if reservationReady != nil { reservationReady() } @@ -1012,25 +1019,28 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( if start.err != nil { return nil, nil, nil, start.err } + if !waiter.claimed { + return nil, nil, nil, operationCtx.Err() + } claimedSession = start.session ownsInitialClaim = claimedSession != nil case <-closedCh: <-h.sessionStartWaiterSlots h.mu.Lock() - if start.session != nil { + if start.session != nil && waiter.claimed { h.releaseInitialClaimLocked(start.session) } else { - start.waiters-- + delete(start.waiters, waiter) } h.mu.Unlock() return nil, nil, nil, errWSPTYHubClosed case <-operationCtx.Done(): <-h.sessionStartWaiterSlots h.mu.Lock() - if start.session != nil { + if start.session != nil && waiter.claimed { h.releaseInitialClaimLocked(start.session) } else { - start.waiters-- + delete(start.waiters, waiter) } h.mu.Unlock() return nil, nil, nil, operationCtx.Err() @@ -1048,7 +1058,10 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( h.mu.Unlock() return nil, nil, nil, errWSPTYStartOwnersSaturated } - start := &wsPTYSessionStart{done: make(chan struct{})} + start := &wsPTYSessionStart{ + done: make(chan struct{}), + waiters: map[*wsPTYSessionStartWaiter]struct{}{}, + } h.startingSessions[sessionKey] = start if reservationReady != nil { reservationReady() @@ -1064,6 +1077,13 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( delete(h.startingSessions, sessionKey) if startErr == nil { ownerContextErr := operationCtx.Err() + liveWaiters := 0 + for waiter := range start.waiters { + if waiter.ctx.Err() == nil { + waiter.claimed = true + liveWaiters++ + } + } switch existingSession := h.sessions[sessionKey]; { case h.closed: startErr = errWSPTYHubClosed @@ -1071,17 +1091,17 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( case start.closeRequested: startErr = fmt.Errorf("persistent PTY session %q was closed while starting", sessionID) discardStartedSession = true - case ownerContextErr != nil && start.waiters == 0: + case ownerContextErr != nil && liveWaiters == 0: startErr = ownerContextErr discardStartedSession = true case existingSession != nil && !existingSession.closed: discardStartedSession = true default: // A completed persistent generation deliberately survives a - // transport gap when a counted joiner is canceled concurrently. - // Its initial claim is released by that joiner and the ordinary - // idle reaper bounds retention until the wrapper reconnects. - startedSession.initialClaims = start.waiters + // transport gap when a joiner counted live at publication + // cancels immediately afterward. Its initial claim is released + // by that joiner and the idle reaper bounds retention. + startedSession.initialClaims = liveWaiters if ownerContextErr == nil { startedSession.initialClaims++ claimedSession = startedSession From e316f1acc7cbf1a745d520636824a862d5576708 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 03:49:43 -0700 Subject: [PATCH 28/37] test(remote): assert timeout cancellation ordering --- ...DaemonRPCClientTimeoutIsolationTests.swift | 53 ++++++++++++------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index acd115c7a394..6ea973190907 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -122,9 +122,11 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { } // One-shot failure safety keeps a regressed synchronous cancellation // from stranding the test process; ordinary cleanup is deterministic. + let cleanupFired = DispatchSemaphore(value: 0) let cleanupTimer = DispatchSource.makeTimerSource(queue: writeBlockQueue) - cleanupTimer.schedule(deadline: .now() + 4) + cleanupTimer.schedule(deadline: .now() + 5) cleanupTimer.setEventHandler { + cleanupFired.signal() releaseWrite.signal() } cleanupTimer.resume() @@ -133,27 +135,38 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { releaseWrite.signal() } - let startedAt = DispatchTime.now() - do { - _ = try client.call( - method: "pty.attach", - params: [ - "session_id": "stalled-session", - "attachment_id": "stalled-attachment", - "client_attachment_token": "stalled-token", - ], - timeout: 1 - ) - Issue.record("stalled pty.attach unexpectedly succeeded") - } catch { - let nsError = error as NSError - #expect(nsError.domain == "cmux.remote.daemon.rpc") - #expect(nsError.code == 11) + let callFinished = DispatchSemaphore(value: 0) + let callTimedOut = DispatchSemaphore(value: 0) + let unexpectedCallResult = DispatchSemaphore(value: 0) + let callQueue = DispatchQueue(label: "com.cmux.tests.remote-daemon.call-with-blocked-cancellation") + callQueue.async { + defer { callFinished.signal() } + do { + _ = try client.call( + method: "pty.attach", + params: [ + "session_id": "stalled-session", + "attachment_id": "stalled-attachment", + "client_attachment_token": "stalled-token", + ], + timeout: 1 + ) + unexpectedCallResult.signal() + } catch { + let nsError = error as NSError + if nsError.domain == "cmux.remote.daemon.rpc", nsError.code == 11 { + callTimedOut.signal() + } else { + unexpectedCallResult.signal() + } + } } - let elapsed = Double(DispatchTime.now().uptimeNanoseconds - startedAt.uptimeNanoseconds) / 1_000_000_000 - #expect(writeBlockEntered.wait(timeout: .now()) == .success) - #expect(elapsed < 2) + #expect(writeBlockEntered.wait(timeout: .now() + 2) == .success) + #expect(callFinished.wait(timeout: .now() + 6) == .success) + #expect(callTimedOut.wait(timeout: .now()) == .success) + #expect(unexpectedCallResult.wait(timeout: .now()) == .timedOut) + #expect(cleanupFired.wait(timeout: .now()) == .timedOut) #expect(unexpectedTermination.wait(timeout: .now() + 2) == .success) } From 92b2c3274c784b393a88f35abc921a9ff204a6be Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:01:54 -0700 Subject: [PATCH 29/37] test(remote): expose completed attachment context leak --- daemon/remote/cmd/cmuxd-remote/main_test.go | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index 57586cad460f..ceef10ac0c3e 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1800,6 +1800,30 @@ func TestPTYAttachmentPumpCancellationDropsHubAttachment(t *testing.T) { } } +func TestPTYAttachmentPumpReleasesLifetimeContextAfterSessionExit(t *testing.T) { + attachmentCtx, cancelAttachment := context.WithCancel(context.Background()) + defer cancelAttachment() + attachment := &wsPTYAttachment{ + sessionKey: persistentPTYSessionKey("completed-session"), + id: "completed-attachment", + clientToken: "completed-token", + send: make(chan wsPTYOutgoingFrame, defaultWebSocketWriteQueueCap), + cancel: cancelAttachment, + persistent: true, + } + sessionDone := make(chan struct{}) + close(sessionDone) + server := &rpcServer{ + frameWriter: &stdioFrameWriter{writer: bufio.NewWriter(io.Discard)}, + } + + server.ptyAttachmentPump(attachmentCtx, attachment, sessionDone) + + if !errors.Is(attachmentCtx.Err(), context.Canceled) { + t.Fatalf("attachment context error after session exit = %v, want context.Canceled", attachmentCtx.Err()) + } +} + func TestPersistentStdioProxyReturnsWhenDaemonClosesFirst(t *testing.T) { client, server := net.Pipe() stdinReader, stdinWriter := io.Pipe() From 0a7cefe3255239284e7ab7c01b3689e397449ae5 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:03:09 -0700 Subject: [PATCH 30/37] fix(remote): release completed attachment contexts --- daemon/remote/cmd/cmuxd-remote/main.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 6b2c88370cd2..622f38da4340 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -2679,6 +2679,9 @@ func (s *rpcServer) handlePTYList(req rpcRequest) rpcResponse { func (s *rpcServer) ptyAttachmentPump(ctx context.Context, attachment *wsPTYAttachment, sessionDone <-chan struct{}) { defer s.untrackPTYAttachment(attachment) + if attachment.cancel != nil { + defer attachment.cancel() + } for { select { case <-ctx.Done(): From c0ea226aa2e4e0bdf40b60f00dc28dbaf47bd5b0 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:18:45 -0700 Subject: [PATCH 31/37] test(remote): advertise attach cancellation in bridge fixture --- .../RemotePTYBridgeTransportTerminationTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeTransportTerminationTests.swift b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeTransportTerminationTests.swift index 9ef6c17641d2..61d197027a42 100644 --- a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeTransportTerminationTests.swift +++ b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeTransportTerminationTests.swift @@ -82,7 +82,7 @@ struct RemotePTYBridgeTransportTerminationTests { #!/bin/sh if ! IFS= read -r hello; then exit 1; fi hello_id=$(printf '%s\n' "$hello" | sed -n 's/.*"id":\\([0-9][0-9]*\\).*/\\1/p') - printf '{"id":%s,"ok":true,"result":{"capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification"],"name":"fake","version":"test","remote_path":"/fake"}}\n' "$hello_id" + printf '{"id":%s,"ok":true,"result":{"capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification","pty.attach.cancel"],"name":"fake","version":"test","remote_path":"/fake"}}\n' "$hello_id" if ! IFS= read -r attach; then exit 1; fi attach_id=$(printf '%s\n' "$attach" | sed -n 's/.*"id":\\([0-9][0-9]*\\).*/\\1/p') printf '{"id":%s,"ok":true,"result":{"attachment_id":"surface","attachment_token":"server-token"}}\n' "$attach_id" From 4f49ea2cd3a11e0489cfa4f0621c9d12d6707dfc Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:30:07 -0700 Subject: [PATCH 32/37] test(remote): expose canceled anonymous PTY retention --- daemon/remote/cmd/cmuxd-remote/ws_pty_test.go | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go index bbe50b0b8368..1a6769c3582d 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty_test.go @@ -745,6 +745,40 @@ func TestAttachRPCLateCancellationSchedulesPublishedSessionReap(t *testing.T) { waitForHubSessionCount(t, hub, 0, 5*time.Second) } +func TestAnonymousAttachLateCancellationDropsPublishedSession(t *testing.T) { + hub := newWebSocketPTYHub(wsPTYServerConfig{ + Shell: "/bin/sh", + SessionIdleTTL: time.Hour, + }, io.Discard) + t.Cleanup(hub.closeAll) + + baseCtx, cancel := context.WithCancel(context.Background()) + ctx := &cancelAfterFirstErrContext{Context: baseCtx, cancel: cancel} + _, _, _, err := hub.prepareAttachment( + ctx, + nil, + "late-canceled-anonymous", + "", + 80, + 24, + false, + "sleep 30", + "", + false, + false, + ) + if !errors.Is(err, context.Canceled) { + t.Fatalf("late-canceled anonymous attach error = %v, want context canceled", err) + } + + hub.mu.Lock() + sessionCount := len(hub.sessions) + hub.mu.Unlock() + if sessionCount != 0 { + t.Fatalf("anonymous sessions after late cancellation = %d, want 0", sessionCount) + } +} + func TestAttachRPCBoundsStalledSessionStartOwners(t *testing.T) { hub := newWebSocketPTYHub(wsPTYServerConfig{Shell: "/bin/sh"}, io.Discard) t.Cleanup(hub.closeAll) From a9f9783b83f811b96d7665fc0cf2fe5c50f7467e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:31:59 -0700 Subject: [PATCH 33/37] fix(remote): terminate canceled anonymous PTY starts --- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index 3fe811c31257..be9aa611f5ad 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -1139,10 +1139,19 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( if ownsInitialClaim { h.releaseInitialClaimLocked(session) } - if len(session.attachments) == 0 { + terminateAnonymous := false + if !persistent && h.sessions[sessionKey] == session { + delete(h.sessions, sessionKey) + h.cancelIdleReapLocked(session) + terminateAnonymous = true + } else if persistent && len(session.attachments) == 0 { h.scheduleIdleReapLocked(session) } h.mu.Unlock() + if terminateAnonymous { + session.terminateProcesses() + session.closePTYFiles() + } return nil, nil, nil, err } if attachmentID == "" { From edd2fbaeceb9928a699dc83f7c1b9c05d01c1a44 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:42:44 -0700 Subject: [PATCH 34/37] test(remote): distinguish replay from live PTY output --- .../SSHPTYAttachExitCodeTests.swift | 13 +++++++++++++ .../RemotePTYBridgeServerTests.swift | 12 ++++++++++-- daemon/remote/cmd/cmuxd-remote/main_test.go | 5 +++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift index cc008e5bd70a..74ea3c5033b7 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/SSHPTYAttachExitCodeTests.swift @@ -91,6 +91,19 @@ struct SSHPTYAttachExitCodeTests { ) } + @Test("replayed scrollback does not count as live bridge progress") + func replayedScrollbackDoesNotCountAsLiveProgress() { + var progress = SSHPTYAttachOutputProgress(replayBytes: 6) + + progress.recordOutput(byteCount: 4) + #expect(progress.replayBytesRemaining == 2) + #expect(!progress.receivedLiveOutput) + + progress.recordOutput(byteCount: 4) + #expect(progress.replayBytesRemaining == 0) + #expect(progress.receivedLiveOutput) + } + private static func writeExecutable(_ url: URL, _ source: String) throws { try source.write(to: url, atomically: true, encoding: .utf8) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path) diff --git a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeServerTests.swift b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeServerTests.swift index ce92925d636f..45f00fbe9f7e 100644 --- a/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeServerTests.swift +++ b/Packages/macOS/CmuxRemoteWorkspace/Tests/CmuxRemoteWorkspaceTests/RemotePTYBridgeServerTests.swift @@ -13,6 +13,7 @@ final class RecordingPTYBridgeRPCClient: RemotePTYBridgeRPCClient, @unchecked Se private var _eventQueue: DispatchQueue? var attachError: (any Error)? var supportsInputSeqAck = false + var replayByteCount = 0 var writes: [Data] { lock.lock() @@ -58,7 +59,11 @@ final class RecordingPTYBridgeRPCClient: RemotePTYBridgeRPCClient, @unchecked Se _onEvent = onEvent _eventQueue = queue lock.unlock() - return RemotePTYBridgeAttachment(attachmentID: attachmentID, token: "attach-token-1") + return RemotePTYBridgeAttachment( + attachmentID: attachmentID, + token: "attach-token-1", + replayByteCount: replayByteCount + ) } func writePTY( @@ -224,6 +229,7 @@ struct RemotePTYBridgeServerTests { @Test("a valid handshake attaches and the bridge pumps both directions") func handshakeAttachesAndPumps() throws { let rpc = RecordingPTYBridgeRPCClient() + rpc.replayByteCount = 6 let server = makeServer(client: rpc) defer { server.stop() } let endpoint = try server.start() @@ -235,7 +241,9 @@ struct RemotePTYBridgeServerTests { // The bridge answers with the newline-terminated ready status line // carrying the daemon attachment token (wire-pinned shape). #expect(client.waitForReceived { data, _ in - String(decoding: data, as: UTF8.self).contains("\"attachment_token\":\"attach-token-1\"") + let status = String(decoding: data, as: UTF8.self) + return status.contains("\"attachment_token\":\"attach-token-1\"") && + status.contains("\"replay_bytes\":6") }) // Client input is forwarded to pty.write. diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index ceef10ac0c3e..a56a3b3c908e 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -1897,6 +1897,11 @@ func TestPersistentDaemonPTYReattachSurvivesClientDisconnect(t *testing.T) { if ok, _ := attach2["ok"].(bool); !ok { t.Fatalf("second pty.attach failed: %v", attach2) } + attach2Result, _ := attach2["result"].(map[string]any) + replayBytes, _ := attach2Result["replay_bytes"].(float64) + if replayBytes <= 0 { + t.Fatalf("second pty.attach replay_bytes = %v, want positive scrollback size", attach2Result["replay_bytes"]) + } readPersistentTestEvent(t, conn2, reader2, func(frame map[string]any) bool { return frame["event"] == "pty.ready" && frame["attachment_id"] == "a2" }) From a5dbe7bdaa7ca943f7b8dbd72dc278b15aff7009 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 04:48:39 -0700 Subject: [PATCH 35/37] fix(remote): exclude replay from attach progress --- CLI/CMUXCLI+SSHPTYAttachBridge.swift | 19 +++++++++++---- CLI/cmux.swift | 13 ++++++---- .../CmuxFoundation/SSHPTYAttachExitCode.swift | 11 +++++---- .../SSHPTYAttachOutputProgress.swift | 24 +++++++++++++++++++ .../Client/RemoteDaemonRPCClient+RPC.swift | 4 +++- .../PTYBridge/RemotePTYBridgeAttachment.swift | 5 +++- ...DaemonRPCClientTimeoutIsolationTests.swift | 5 ++-- .../PTYBridge/RemotePTYBridgeSession.swift | 1 + Resources/Localizable.xcstrings | 4 ++-- ...ifyProcessIntegrationRegressionTests.swift | 2 +- .../SSHPTYAttachNoProgressRetryTests.swift | 6 ++--- daemon/remote/cmd/cmuxd-remote/main.go | 11 +++++---- daemon/remote/cmd/cmuxd-remote/ws_pty.go | 4 +++- 13 files changed, 78 insertions(+), 31 deletions(-) create mode 100644 Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachOutputProgress.swift diff --git a/CLI/CMUXCLI+SSHPTYAttachBridge.swift b/CLI/CMUXCLI+SSHPTYAttachBridge.swift index 96e4f1d76258..a5e55a3c0d6d 100644 --- a/CLI/CMUXCLI+SSHPTYAttachBridge.swift +++ b/CLI/CMUXCLI+SSHPTYAttachBridge.swift @@ -36,7 +36,7 @@ extension CMUXCLI { } func sshPTYAttachBridgeClosedExitCode( - receivedOutput: Bool, + receivedLiveOutput: Bool, readyUptime: TimeInterval ) -> SSHPTYAttachExitCode { let environment = ProcessInfo.processInfo.environment @@ -45,7 +45,7 @@ extension CMUXCLI { environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_RETRY"] != nil, environment["CMUX_SSH_PTY_ATTACH_NO_PROGRESS_LIMIT"] != nil, SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( - receivedOutput: receivedOutput, + receivedLiveOutput: receivedLiveOutput, bridgeUptime: bridgeUptime ) else { return .bridgeClosedSessionRunning @@ -186,7 +186,7 @@ extension CMUXCLI { if sessionRunningExitCode == .bridgeClosedWithoutProgress { message = String( localized: "cli.sshPtyAttach.bridgeClosedWithoutProgress", - defaultValue: "ssh-pty-attach: bridge closed without receiving output while the remote PTY session is still running" + defaultValue: "ssh-pty-attach: bridge closed without receiving new output while the remote PTY session is still running" ) } else { message = "ssh-pty-attach: bridge closed while remote PTY session is still running" @@ -212,7 +212,7 @@ extension CMUXCLI { return true } - func readSSHPTYBridgeReady(fd: Int32) throws -> String { + func readSSHPTYBridgeReady(fd: Int32) throws -> (attachmentToken: String, replayBytes: Int) { let maxStatusBytes = 4096 // Bound only the pre-ready status wait: a bridge that accepts the TCP // connection and then goes silent must not hang the attach (and its @@ -236,8 +236,12 @@ extension CMUXCLI { } switch type { case "ready": - return ((payload["attachment_token"] as? String)? + let attachmentToken = ((payload["attachment_token"] as? String)? .trimmingCharacters(in: .whitespacesAndNewlines)) ?? "" + return ( + attachmentToken: attachmentToken, + replayBytes: sshPTYBridgeReplayByteCount(payload["replay_bytes"]) + ) case "error": let message = ((payload["message"] as? String)? .trimmingCharacters(in: .whitespacesAndNewlines)).flatMap { $0.isEmpty ? nil : $0 } @@ -271,6 +275,11 @@ extension CMUXCLI { throw CLIError(message: "ssh-pty-attach: bridge status exceeded \(maxStatusBytes) bytes") } + private func sshPTYBridgeReplayByteCount(_ value: Any?) -> Int { + guard let count = value as? Int, count >= 0 else { return 0 } + return count + } + /// Ceiling for the bridge ready/error status wait. Defaults to 185s, /// matching the `wait_for_ready` RPC response timeout in `runSSHPTYAttach`. private func sshPTYBridgeReadyTimeoutSeconds() -> TimeInterval { diff --git a/CLI/cmux.swift b/CLI/cmux.swift index aec392cfad40..31e7edfd13c1 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -12616,6 +12616,7 @@ struct CMUXCLI { var connectedFD: Int32? var bridgeHandshakeSize = Self.currentCLITerminalSize() var bridgeReadyUptime: TimeInterval = 0 + var bridgeReplayBytes = 0 do { let host = (bridge["host"] as? String) ?? "127.0.0.1" guard let port = cliStrictInt(bridge["port"]), port > 0, port <= 65535 else { @@ -12637,7 +12638,9 @@ struct CMUXCLI { ], options: []) handshakeData.append(0x0A) try Self.writeAll(fd: fd, data: handshakeData) - attachmentToken = try readSSHPTYBridgeReady(fd: fd) + let ready = try readSSHPTYBridgeReady(fd: fd) + attachmentToken = ready.attachmentToken + bridgeReplayBytes = ready.replayBytes bridgeReachedReady = true bridgeReadyUptime = ProcessInfo.processInfo.systemUptime } catch { @@ -12698,13 +12701,13 @@ struct CMUXCLI { throw CLIError(message: "ssh-pty-attach: bridge write failed") } var reconnectInputFilterStopRequested = false - var receivedOutput = false + var outputProgress = SSHPTYAttachOutputProgress(replayBytes: bridgeReplayBytes) var outputBuffer = [UInt8](repeating: 0, count: 32768) while true { let count = Darwin.read(fd, &outputBuffer, outputBuffer.count) if count > 0 { - receivedOutput = true + outputProgress.recordOutput(byteCount: count) reconnectInputFilterControl?.stopFilteringBeforeFirstOutput(unlessAlreadyRequested: &reconnectInputFilterStopRequested) cliWriteStdout(Data(outputBuffer.prefix(count))) } else if count == 0 { @@ -12712,7 +12715,7 @@ struct CMUXCLI { _ = try reconcileBridgeEnd( intentionalOnly: false, sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode( - receivedOutput: receivedOutput, + receivedLiveOutput: outputProgress.receivedLiveOutput, readyUptime: bridgeReadyUptime ) ) @@ -12724,7 +12727,7 @@ struct CMUXCLI { _ = try reconcileBridgeEnd( intentionalOnly: false, sessionRunningExitCode: sshPTYAttachBridgeClosedExitCode( - receivedOutput: receivedOutput, + receivedLiveOutput: outputProgress.receivedLiveOutput, readyUptime: bridgeReadyUptime ) ) diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift index e266f9d868fe..63f5d43a6804 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachExitCode.swift @@ -13,7 +13,7 @@ public enum SSHPTYAttachExitCode: Int32 { /// Temporary daemon-side admission pressure that should retry without reauthentication. case retryableWithoutReauthentication = 251 - /// A rapidly closed bridge that produced no remote PTY output. + /// A rapidly closed bridge that produced no live remote PTY output. case bridgeClosedWithoutProgress = 252 /// A persistent PTY session that no longer exists and must be respawned. @@ -38,16 +38,17 @@ public enum SSHPTYAttachExitCode: Int32 { /// Determines whether a bridge closed before demonstrating useful progress. /// /// - Parameters: - /// - receivedOutput: Whether the bridge delivered any remote PTY output. + /// - receivedLiveOutput: Whether the bridge delivered output after its + /// initial scrollback replay. /// - bridgeUptime: The number of seconds the ready bridge remained open. - /// - Returns: `true` for a rapid, zero-output closure. + /// - Returns: `true` for a rapid closure with no live output. public static func bridgeClosureMadeNoProgress( - receivedOutput: Bool, + receivedLiveOutput: Bool, bridgeUptime: Double ) -> Bool { // A bridge that remains connected through an ordinary idle interval is // healthy even when the remote shell has not emitted output. - !receivedOutput && bridgeUptime >= 0 && bridgeUptime < healthyBridgeUptime + !receivedLiveOutput && bridgeUptime >= 0 && bridgeUptime < healthyBridgeUptime } /// Determines whether another no-progress retry remains in the bounded budget. diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachOutputProgress.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachOutputProgress.swift new file mode 100644 index 000000000000..1390065763cf --- /dev/null +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/SSHPTYAttachOutputProgress.swift @@ -0,0 +1,24 @@ +/// Tracks whether an SSH PTY attachment delivered output newer than its +/// initial scrollback replay. +public struct SSHPTYAttachOutputProgress: Sendable { + /// Initial replay bytes that have not yet arrived from the bridge. + public private(set) var replayBytesRemaining: Int + + /// Whether any output arrived after the initial replay boundary. + public private(set) var receivedLiveOutput = false + + /// Creates progress accounting for an attachment's declared replay size. + public init(replayBytes: Int) { + replayBytesRemaining = max(0, replayBytes) + } + + /// Records one ordered output chunk from the bridge. + public mutating func recordOutput(byteCount: Int) { + guard byteCount > 0 else { return } + let replayBytes = min(byteCount, replayBytesRemaining) + replayBytesRemaining -= replayBytes + if byteCount > replayBytes { + receivedLiveOutput = true + } + } +} diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift index fe4b714a10c4..0eddc4847913 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/Client/RemoteDaemonRPCClient+RPC.swift @@ -159,9 +159,11 @@ extension RemoteDaemonRPCClient { let returnedToken = (result["attachment_token"] as? String)? .trimmingCharacters(in: .whitespacesAndNewlines) ?? clientAttachmentToken + let replayByteCount = max(0, (result["replay_bytes"] as? Int) ?? 0) return RemotePTYBridgeAttachment( attachmentID: returnedAttachmentID, - token: returnedToken + token: returnedToken, + replayByteCount: replayByteCount ) } catch { unregisterPTY( diff --git a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/PTYBridge/RemotePTYBridgeAttachment.swift b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/PTYBridge/RemotePTYBridgeAttachment.swift index 8b600a22b2cc..863465bdef2f 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/PTYBridge/RemotePTYBridgeAttachment.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Sources/CmuxRemoteDaemon/PTYBridge/RemotePTYBridgeAttachment.swift @@ -5,10 +5,13 @@ public struct RemotePTYBridgeAttachment: Sendable { public let attachmentID: String /// Daemon-issued secret authorizing operations on this attachment. public let token: String + /// Bytes of initial scrollback replayed before live PTY output. + public let replayByteCount: Int /// Creates an attachment identity; mirrors the original memberwise initializer. - public init(attachmentID: String, token: String) { + public init(attachmentID: String, token: String, replayByteCount: Int = 0) { self.attachmentID = attachmentID self.token = token + self.replayByteCount = max(0, replayByteCount) } } diff --git a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift index 6ea973190907..86e2901abbe2 100644 --- a/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift +++ b/Packages/macOS/CmuxRemoteDaemon/Tests/CmuxRemoteDaemonTests/RemoteDaemonRPCClientTimeoutIsolationTests.swift @@ -31,7 +31,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { client.transportExecutableOverride = executable try client.start() - _ = try client.attachPTY( + let existingAttachment = try client.attachPTY( sessionID: "existing-session", attachmentID: "existing-attachment", cols: 80, @@ -44,6 +44,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { existingPTYEvent.signal() } } + #expect(existingAttachment.replayByteCount == 11) do { _ = try client.call( @@ -206,7 +207,7 @@ struct RemoteDaemonRPCClientTimeoutIsolationTests { if IFS= read -r line; then id=$(read_id "$line") existing_token=$(printf '%s\\n' "$line" | sed -n 's/.*"client_attachment_token":"\\([^"]*\\)".*/\\1/p') - printf '{"id":%s,"ok":true,"result":{"attachment_id":"existing-attachment","attachment_token":"%s"}}\\n' "$id" "$existing_token" + printf '{"id":%s,"ok":true,"result":{"attachment_id":"existing-attachment","attachment_token":"%s","replay_bytes":11}}\\n' "$id" "$existing_token" else exit 1 fi diff --git a/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession.swift b/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession.swift index a4c258af0179..9f6e14a50870 100644 --- a/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession.swift +++ b/Packages/macOS/CmuxRemoteWorkspace/Sources/CmuxRemoteWorkspace/PTYBridge/RemotePTYBridgeSession.swift @@ -229,6 +229,7 @@ extension RemotePTYBridgeServer { sendBridgeStatus([ "type": "ready", "attachment_token": remoteAttachment.token, + "replay_bytes": remoteAttachment.replayByteCount, ]) isAttached = true let pendingPTYEvents = pendingPTYEventsBeforeReady diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 44333db577fd..d8e710c14e55 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -50486,13 +50486,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "ssh-pty-attach: bridge closed without receiving output while the remote PTY session is still running" + "value": "ssh-pty-attach: bridge closed without receiving new output while the remote PTY session is still running" } }, "ja": { "stringUnit": { "state": "translated", - "value": "ssh-pty-attach: 出力を受信しないままブリッジが閉じましたが、リモート PTY セッションは引き続き実行中です" + "value": "ssh-pty-attach: 新しい出力を受信しないままブリッジが閉じましたが、リモート PTY セッションは引き続き実行中です" } } } diff --git a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift index 8f896b3b0948..2966cbe99523 100644 --- a/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift +++ b/cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift @@ -4010,7 +4010,7 @@ final class CLINotifyProcessIntegrationRegressionTests: XCTestCase { XCTAssertFalse(result.timedOut, result.stderr) XCTAssertEqual(result.status, 252, result.stderr) XCTAssertTrue( - result.stderr.contains("bridge closed without receiving output"), + result.stderr.contains("bridge closed without receiving new output"), result.stderr ) let methods = state.snapshot().compactMap { self.jsonObject($0)?["method"] as? String } diff --git a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift index 59e37c21a453..b1de87c2130c 100644 --- a/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift +++ b/cmuxTests/SSHPTYAttachNoProgressRetryTests.swift @@ -33,19 +33,19 @@ struct SSHPTYAttachNoProgressRetryTests { func bridgeProgressClassification() { #expect( SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( - receivedOutput: false, + receivedLiveOutput: false, bridgeUptime: 1 ) ) #expect( !SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( - receivedOutput: true, + receivedLiveOutput: true, bridgeUptime: 1 ) ) #expect( !SSHPTYAttachExitCode.bridgeClosureMadeNoProgress( - receivedOutput: false, + receivedLiveOutput: false, bridgeUptime: 30 ) ) diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 622f38da4340..40fb12e80057 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -116,11 +116,11 @@ type rpcServer struct { } type rpcRequestDispatcher struct { - ctx context.Context - cancelConnection context.CancelFunc - interruptRead func() - server *rpcServer - ptyAttachSlots chan struct{} + ctx context.Context + cancelConnection context.CancelFunc + interruptRead func() + server *rpcServer + ptyAttachSlots chan struct{} // Request cancellation is separate from attachment lifetime: completed // attachments remain connection-owned after their request leaves this map. ptyAttachMu sync.Mutex @@ -2457,6 +2457,7 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( "session_id": strings.TrimSpace(sessionID), "attachment_id": attachment.id, "attachment_token": attachment.clientToken, + "replay_bytes": attachment.replayBytes, "attached": true, }, } diff --git a/daemon/remote/cmd/cmuxd-remote/ws_pty.go b/daemon/remote/cmd/cmuxd-remote/ws_pty.go index be9aa611f5ad..659bd426dbf5 100644 --- a/daemon/remote/cmd/cmuxd-remote/ws_pty.go +++ b/daemon/remote/cmd/cmuxd-remote/ws_pty.go @@ -150,6 +150,7 @@ type wsPTYAttachment struct { conn *websocket.Conn persistent bool inputSeqAck bool + replayBytes int lastAcceptedSeq uint64 ackMu sync.Mutex ackQueued bool @@ -1177,6 +1178,7 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( // connection. Once published, the attachment follows the connection // lifetime and can be canceled independently by its identity token. attachmentCtx, cancel := context.WithCancel(attachmentLifetimeCtx) + replay := append([]byte(nil), session.scrollback...) clientToken = strings.TrimSpace(clientToken) attachment := &wsPTYAttachment{ sessionKey: sessionKey, @@ -1189,8 +1191,8 @@ func (h *wsPTYHub) prepareAttachmentWithReservation( conn: conn, persistent: persistent, inputSeqAck: inputSeqAck, + replayBytes: len(replay), } - replay := append([]byte(nil), session.scrollback...) if ok := attachment.enqueueReady(sessionID); !ok { cancel() if ownsInitialClaim { From d6a3855da048381bd1ba06684d0758a1498f1429 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 05:11:53 -0700 Subject: [PATCH 36/37] test(remote): require cancellable attachment identities --- .../WorkspaceRemoteConnectionTests.swift | 4 +-- daemon/remote/cmd/cmuxd-remote/main_test.go | 36 ++++++++++++------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/cmuxTests/WorkspaceRemoteConnectionTests.swift b/cmuxTests/WorkspaceRemoteConnectionTests.swift index 373b0ffed7ab..7bca5e8e2f58 100644 --- a/cmuxTests/WorkspaceRemoteConnectionTests.swift +++ b/cmuxTests/WorkspaceRemoteConnectionTests.swift @@ -2261,7 +2261,7 @@ final class WorkspaceRemoteConnectionTests: XCTestCase { if remoteDaemonServeCommand(command) { return ( status: 0, - stdout: #"{"id":1,"ok":true,"result":{"name":"cmuxd-remote","version":"dev","capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification","pty.session.persistent_daemon"]}}"# + "\n", + stdout: #"{"id":1,"ok":true,"result":{"name":"cmuxd-remote","version":"dev","capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification","pty.attach.cancel","pty.session.persistent_daemon"]}}"# + "\n", stderr: "" ) } @@ -2374,7 +2374,7 @@ final class WorkspaceRemoteConnectionTests: XCTestCase { if remoteDaemonServeCommand(command) { return ( status: 0, - stdout: #"{"id":1,"ok":true,"result":{"name":"cmuxd-remote","version":"dev","capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification","pty.session.persistent_daemon"]}}"# + "\n", + stdout: #"{"id":1,"ok":true,"result":{"name":"cmuxd-remote","version":"dev","capabilities":["proxy.stream.push","pty.session","pty.session.token","pty.write.notification","pty.resize.notification","pty.attach.cancel","pty.session.persistent_daemon"]}}"# + "\n", stderr: "" ) } diff --git a/daemon/remote/cmd/cmuxd-remote/main_test.go b/daemon/remote/cmd/cmuxd-remote/main_test.go index a56a3b3c908e..6fcccbdb99a9 100644 --- a/daemon/remote/cmd/cmuxd-remote/main_test.go +++ b/daemon/remote/cmd/cmuxd-remote/main_test.go @@ -2799,7 +2799,7 @@ func TestPTYRPCTokenRejectsStaleAttachmentControl(t *testing.T) { } } -func TestPTYRPCRequiresAttachmentToken(t *testing.T) { +func TestPTYRPCRequiresAttachmentIdentity(t *testing.T) { eventOutput := newNotifyingBuffer() server := &rpcServer{ nextStreamID: 1, @@ -2817,17 +2817,29 @@ func TestPTYRPCRequiresAttachmentToken(t *testing.T) { } defer server.closeAll() - expectMissingToken := func(method string, resp rpcResponse) { + expectInvalidParams := func(method string, resp rpcResponse, expectedMessage string) { t.Helper() if resp.OK || resp.Error == nil || resp.Error.Code != "invalid_params" { t.Fatalf("%s response = %+v, want invalid_params", method, resp) } - if !strings.Contains(resp.Error.Message, method+" requires client_attachment_token") { - t.Fatalf("%s message = %q, want client_attachment_token requirement", method, resp.Error.Message) + if !strings.Contains(resp.Error.Message, expectedMessage) { + t.Fatalf("%s message = %q, want %q", method, resp.Error.Message, expectedMessage) } } - expectMissingToken("pty.attach", server.handleRequest(rpcRequest{ + expectInvalidParams("pty.attach", server.handleRequest(rpcRequest{ + ID: 1, + Method: "pty.attach", + Params: map[string]any{ + "session_id": "id-required", + "client_attachment_token": "id-required-token", + "cols": 80, + "rows": 24, + "command": "sleep 60", + }, + }), "pty.attach requires attachment_id") + + expectInvalidParams("pty.attach", server.handleRequest(rpcRequest{ ID: 1, Method: "pty.attach", Params: map[string]any{ @@ -2837,7 +2849,7 @@ func TestPTYRPCRequiresAttachmentToken(t *testing.T) { "rows": 24, "command": "sleep 60", }, - })) + }), "pty.attach requires client_attachment_token") attach := server.handleRequest(rpcRequest{ ID: 2, @@ -2861,7 +2873,7 @@ func TestPTYRPCRequiresAttachmentToken(t *testing.T) { event["attachment_token"] == "fresh-token" }) - expectMissingToken("pty.write", server.handleRequest(rpcRequest{ + expectInvalidParams("pty.write", server.handleRequest(rpcRequest{ ID: 3, Method: "pty.write", Params: map[string]any{ @@ -2869,8 +2881,8 @@ func TestPTYRPCRequiresAttachmentToken(t *testing.T) { "attachment_id": "same", "data_base64": base64.StdEncoding.EncodeToString([]byte("missing token")), }, - })) - expectMissingToken("pty.resize", server.handleRequest(rpcRequest{ + }), "pty.write requires client_attachment_token") + expectInvalidParams("pty.resize", server.handleRequest(rpcRequest{ ID: 4, Method: "pty.resize", Params: map[string]any{ @@ -2880,15 +2892,15 @@ func TestPTYRPCRequiresAttachmentToken(t *testing.T) { "cols": 100, "rows": 30, }, - })) - expectMissingToken("pty.detach", server.handleRequest(rpcRequest{ + }), "pty.resize requires client_attachment_token") + expectInvalidParams("pty.detach", server.handleRequest(rpcRequest{ ID: 5, Method: "pty.detach", Params: map[string]any{ "session_id": "token-required", "attachment_id": "same", }, - })) + }), "pty.detach requires client_attachment_token") detach := server.handleRequest(rpcRequest{ ID: 6, From 0a68c39c07fe8c120f934d7786f2704890f21d9c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 29 Jul 2026 05:12:41 -0700 Subject: [PATCH 37/37] fix(remote): require cancellable attachment ids --- daemon/remote/cmd/cmuxd-remote/main.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/daemon/remote/cmd/cmuxd-remote/main.go b/daemon/remote/cmd/cmuxd-remote/main.go index 40fb12e80057..9c1f7e2ac63c 100644 --- a/daemon/remote/cmd/cmuxd-remote/main.go +++ b/daemon/remote/cmd/cmuxd-remote/main.go @@ -2360,7 +2360,18 @@ func (s *rpcServer) handlePTYAttachContextWithReservation( }, } } - attachmentID, _ := getStringParam(req.Params, "attachment_id") + attachmentID, ok := getStringParam(req.Params, "attachment_id") + attachmentID = strings.TrimSpace(attachmentID) + if !ok || attachmentID == "" { + return rpcResponse{ + ID: req.ID, + OK: false, + Error: &rpcError{ + Code: "invalid_params", + Message: "pty.attach requires attachment_id", + }, + } + } attachmentToken, _ := getStringParam(req.Params, "client_attachment_token") attachmentToken = strings.TrimSpace(attachmentToken) if attachmentToken == "" {