From daec9f7c5d2b59e54bf90e5f554765b472adeafd Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Sat, 14 Nov 2026 16:33:08 -0400 Subject: [PATCH 1/3] fix: do not replay brev exec after the remote command may have started brev exec treated every SSH error as a lost connection and, when the instance was still RUNNING, ran the same command again. A non-zero remote exit and a session that dropped mid-command both took that path, so a long job or an @script could start a second time. Retry only when ssh reports that the session never started. Any other failure is returned without a second run. --- pkg/cmd/exec/exec.go | 125 ++++++++++++++++++++-- pkg/cmd/exec/exec_test.go | 214 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 330 insertions(+), 9 deletions(-) create mode 100644 pkg/cmd/exec/exec_test.go diff --git a/pkg/cmd/exec/exec.go b/pkg/cmd/exec/exec.go index 1482556d..0a727e49 100644 --- a/pkg/cmd/exec/exec.go +++ b/pkg/cmd/exec/exec.go @@ -2,6 +2,7 @@ package exec import ( "bufio" + "errors" "fmt" "os" "os/exec" @@ -186,13 +187,22 @@ func runExecCommand(t *terminal.Terminal, sstore ExecStore, workspaceNameOrID st // SSH multiplexing (ControlMaster) in the config means subsequent // calls reuse an existing connection and are near-instant. // Use a 5-second connect timeout so we fail fast if the instance is down. - err := runSSHWithTimeout(sshName, command, 5) + err := runExecSSH(sshName, command, 5) if err == nil { // Success — fire analytics in background and return go trackExecAnalytics(sstore, workspaceNameOrID) return nil } + // The first attempt already is the execution. A non-zero remote status, or + // an SSH session that died after the command may have started, must not be + // run again: the instance can still be RUNNING with the original process + // (or its output) in place. Only a failure from before the session exists + // may fall through to the refresh-and-retry path below. + if !sshFailureAllowsReplay(err) { + return breverrors.WrapAndTrace(err) + } + // SSH failed — now check what's going on with the instance fmt.Fprintf(os.Stderr, "Connection failed, checking instance status...\n") @@ -228,7 +238,7 @@ func runExecCommand(t *terminal.Terminal, sstore ExecStore, workspaceNameOrID st // instance and what to check. return err //nolint:wrapcheck // do not present stack trace for this error } - err = runSSH(sshName, command) + err = runExecSSH(sshName, command, 10) if err != nil { return breverrors.WrapAndTrace(err) } @@ -256,27 +266,124 @@ func trackExecAnalytics(sstore ExecStore, workspaceNameOrID string) { _ = analytics.TrackEvent(data) } +// runExecSSH is the SSH invocation used by brev exec. Tests replace it. +var runExecSSH = runSSHWithTimeout + +// sshAttemptError is a failed SSH invocation of the remote command. +// exitCode 255 is ssh's own failure; any other code is the remote command's. +// diag is ssh's private log (ssh -E), not the remote command's stderr. +type sshAttemptError struct { + err error + exitCode int + diag string +} + +func (e *sshAttemptError) Error() string { + if e == nil || e.err == nil { + return "ssh failed" + } + return e.err.Error() +} + +func (e *sshAttemptError) Unwrap() error { return e.err } + +func newSSHAttemptError(err error, diag string) error { + code := -1 + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + code = exitErr.ExitCode() + } + return &sshAttemptError{err: err, exitCode: code, diag: diag} +} + +// sshFailureAllowsReplay reports whether the remote command is known not to +// have started, so the caller may wait for SSH and run it once. A non-zero +// remote status, a session that dropped, or an unrecognized ssh failure is +// not replayed: the command may already be running. +func sshFailureAllowsReplay(err error) bool { + var attempt *sshAttemptError + if !errors.As(err, &attempt) { + return false + } + // OpenSSH uses 255 for its own failures and passes every other status + // through from the remote command. + if attempt.exitCode != 255 { + return false + } + return sshDiagIsPreSession(attempt.diag) +} + +// sshDiagIsPreSession matches ssh messages from before a session exists. +// "ssh: connect to host" is OpenSSH's own connect-path prefix (not localized; +// the strerror after it is). "Connection reset" and "Connection closed" alone +// are intentionally absent: those phrases also show up after the remote +// command has started. +func sshDiagIsPreSession(diag string) bool { + markers := []string{ + "ssh: connect to host", + "Connection refused", + "Connection timed out", + "Operation timed out", + "No route to host", + "Could not resolve hostname", + "Name or service not known", + "nodename nor servname provided", + "Temporary failure in name resolution", + "kex_exchange_identification", + "Network is unreachable", + "Host is down", + } + for _, marker := range markers { + if strings.Contains(diag, marker) { + return true + } + } + return false +} + +func shellSingleQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + func runSSHWithTimeout(sshAlias string, command string, connectTimeoutSecs int) error { // Non-interactive: run command and pipe stdout/stderr // Escape the command for passing to SSH escapedCmd := strings.ReplaceAll(command, "'", "'\\''") // -T disables pseudo-terminal allocation (no "Pseudo-terminal will not be allocated" warning) // Only start ssh-agent if one isn't already running (avoids orphaned agent processes) + // -E keeps ssh's own errors out of the remote command's stderr so a dropped + // session is not mistaken for "never connected". agentCmd := `if [ -z "$SSH_AUTH_SOCK" ]; then eval $(ssh-agent -s) > /dev/null; fi` - cmd := fmt.Sprintf("%s && ssh -T -o ConnectTimeout=%d -o LogLevel=ERROR %s '%s'", agentCmd, connectTimeoutSecs, sshAlias, escapedCmd) + diagFile, diagErr := os.CreateTemp("", "brev-exec-ssh-") + if diagErr != nil { + return breverrors.WrapAndTrace(diagErr) + } + diagPath := diagFile.Name() + _ = diagFile.Close() + defer os.Remove(diagPath) + + cmd := fmt.Sprintf("%s && ssh -T -E %s -o ConnectTimeout=%d -o LogLevel=ERROR %s '%s'", + agentCmd, shellSingleQuote(diagPath), connectTimeoutSecs, sshAlias, escapedCmd) - sshCmd := exec.Command("bash", "-c", cmd) //nolint:gosec //cmd is user input + sshCmd := exec.Command("bash", "-c", cmd) //nolint:gosec // cmd is user input sshCmd.Stderr = os.Stderr sshCmd.Stdout = os.Stdout // Don't attach stdin - exec is non-interactive err := sshCmd.Run() + diagBytes, readErr := os.ReadFile(diagPath) + diag := "" + if readErr == nil { + diag = string(diagBytes) + } if err != nil { - return breverrors.WrapAndTrace(err) + if diag != "" { + _, _ = os.Stderr.WriteString(diag) + if !strings.HasSuffix(diag, "\n") { + _, _ = fmt.Fprintln(os.Stderr) + } + } + return newSSHAttemptError(err, diag) } return nil } - -func runSSH(sshAlias string, command string) error { - return runSSHWithTimeout(sshAlias, command, 10) -} diff --git a/pkg/cmd/exec/exec_test.go b/pkg/cmd/exec/exec_test.go new file mode 100644 index 00000000..c6758a8a --- /dev/null +++ b/pkg/cmd/exec/exec_test.go @@ -0,0 +1,214 @@ +package exec + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSSHFailureAllowsReplayOnlyBeforeSession(t *testing.T) { + t.Parallel() + cases := []struct { + name string + err error + want bool + }{ + {name: "remote exit", err: &sshAttemptError{exitCode: 1}, want: false}, + {name: "remote exit 127", err: &sshAttemptError{exitCode: 127}, want: false}, + {name: "exit 255 with empty diagnostic", err: &sshAttemptError{exitCode: 255}, want: false}, + { + name: "session dropped", + err: &sshAttemptError{exitCode: 255, diag: "client_loop: send disconnect: Broken pipe\n"}, + want: false, + }, + { + name: "connection closed after the session", + err: &sshAttemptError{exitCode: 255, diag: "Connection closed by 10.0.0.8 port 22"}, + want: false, + }, + { + name: "connection reset after the session", + err: &sshAttemptError{exitCode: 255, diag: "Connection reset by peer"}, + want: false, + }, + { + name: "connection refused", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Connection refused"}, + want: true, + }, + { + name: "localized connect failure", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Verbindung abgelehnt"}, + want: true, + }, + { + name: "connect timeout", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Connection timed out"}, + want: true, + }, + { + name: "macos connect timeout", + err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Operation timed out"}, + want: true, + }, + { + name: "unresolved alias", + err: &sshAttemptError{exitCode: 255, diag: "ssh: Could not resolve hostname gpu: Name or service not known"}, + want: true, + }, + { + name: "handshake before the command", + err: &sshAttemptError{exitCode: 255, diag: "kex_exchange_identification: Connection closed by remote host"}, + want: true, + }, + {name: "untyped error", err: fmt.Errorf("ssh: exit status 1"), want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + if got := sshFailureAllowsReplay(tc.err); got != tc.want { + t.Fatalf("sshFailureAllowsReplay() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestExecDoesNotReplayRemoteExit(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 1"), + exitCode: 1, + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("remote exit was treated as a dead connection:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the remote failure to be returned") + } +} + +func TestExecDoesNotReplaySessionDrop(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "client_loop: send disconnect: Broken pipe\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("dropped session was replayed via SSH recovery:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + +func TestExecStillRecoversWhenSSHNeverConnected(t *testing.T) { + _, output, _, _ := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "ssh: connect to host gpu port 22: Connection refused\n", + }) + if !strings.Contains(output, "Connection failed, checking instance status...") { + t.Fatalf("a refused connection should still enter recovery, output:\n%s", output) + } +} + +func TestRunSSHWithTimeoutKeepsPreSessionDiagnostic(t *testing.T) { + sshPath := writeFakeSSH(t, `#!/bin/sh +prev= +for a in "$@"; do + if [ "$prev" = "-E" ]; then + printf '%s\n' 'ssh: connect to host inst port 22: Connection refused' > "$a" + exit 255 + fi + prev=$a +done +printf '%s\n' 'fake ssh: missing -E' >&2 +exit 255 +`) + t.Setenv("SSH_AUTH_SOCK", "/tmp/brev-exec-test-sock") + t.Setenv("PATH", filepath.Dir(sshPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + + err := runSSHWithTimeout("inst", "true", 1) + if !sshFailureAllowsReplay(err) { + t.Fatalf("connection refused was not classified as pre-session: %v", err) + } +} + +func TestRunSSHWithTimeoutDoesNotReplayRemoteStatus(t *testing.T) { + sshPath := writeFakeSSH(t, `#!/bin/sh +prev= +for a in "$@"; do + if [ "$prev" = "-E" ]; then + : > "$a" + exit 1 + fi + prev=$a +done +exit 1 +`) + t.Setenv("SSH_AUTH_SOCK", "/tmp/brev-exec-test-sock") + t.Setenv("PATH", filepath.Dir(sshPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + + err := runSSHWithTimeout("inst", "mhcflurry eval", 1) + if sshFailureAllowsReplay(err) { + t.Fatalf("remote exit 1 was classified as replayable: %v", err) + } + var attempt *sshAttemptError + if !errorsAsAttempt(err, &attempt) || attempt.exitCode != 1 { + t.Fatalf("exit code = %v, err = %v", attempt, err) + } +} + +func execWithSSHResult(t *testing.T, sshErr error) (calls int, output string, ret error, panicked any) { + t.Helper() + orig := runExecSSH + t.Cleanup(func() { runExecSSH = orig }) + runExecSSH = func(alias, command string, connectTimeoutSecs int) error { + calls++ + return sshErr + } + + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldStderr := os.Stderr + os.Stderr = writer + defer func() { os.Stderr = oldStderr }() + + func() { + defer func() { panicked = recover() }() + ret = runExecCommand(nil, nil, "gpu-01", false, "mhcflurry eval") + }() + _ = writer.Close() + buf, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + return calls, string(buf), ret, panicked +} + +func writeFakeSSH(t *testing.T, script string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "ssh") + if err := os.WriteFile(path, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + return path +} + +func errorsAsAttempt(err error, target **sshAttemptError) bool { + if attempt, ok := err.(*sshAttemptError); ok { + *target = attempt + return true + } + return false +} From 85fc01c5b257d458a9a66b8f00873878f7315d02 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Sat, 14 Nov 2026 16:48:31 -0400 Subject: [PATCH 2/3] fix: classify ssh replay from the last pre-session line only Matching bare errno strings anywhere in the ssh -E log treated a session that had already started as a failed connect. "Read from remote host: Connection timed out" and an earlier "Connection refused" followed by "Broken pipe" both ran the remote command again. Retry only when the last non-empty diagnostic line starts with an OpenSSH pre-session prefix. --- pkg/cmd/exec/exec.go | 45 ++++++++++++++++++-------------- pkg/cmd/exec/exec_test.go | 55 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 20 deletions(-) diff --git a/pkg/cmd/exec/exec.go b/pkg/cmd/exec/exec.go index 0a727e49..a7fc64d6 100644 --- a/pkg/cmd/exec/exec.go +++ b/pkg/cmd/exec/exec.go @@ -313,34 +313,39 @@ func sshFailureAllowsReplay(err error) bool { return sshDiagIsPreSession(attempt.diag) } -// sshDiagIsPreSession matches ssh messages from before a session exists. -// "ssh: connect to host" is OpenSSH's own connect-path prefix (not localized; -// the strerror after it is). "Connection reset" and "Connection closed" alone -// are intentionally absent: those phrases also show up after the remote -// command has started. +// sshDiagIsPreSession reports whether ssh failed before a session existed. +// Only the last non-empty line of the -E log counts. An earlier +// "ssh: connect to host" line is normal when another address then opens a +// session that later drops, and that command must not be run again. +// The line has to start with an OpenSSH pre-session prefix. A bare errno +// string is not enough: "Read from remote host X: Connection timed out" is +// written after the session is up. The strerror after the prefix is not +// matched, so a translated message still counts. func sshDiagIsPreSession(diag string) bool { - markers := []string{ - "ssh: connect to host", - "Connection refused", - "Connection timed out", - "Operation timed out", - "No route to host", - "Could not resolve hostname", - "Name or service not known", - "nodename nor servname provided", - "Temporary failure in name resolution", - "kex_exchange_identification", - "Network is unreachable", - "Host is down", + line := lastNonEmptyDiagLine(diag) + prefixes := []string{ + "ssh: connect to host ", + "ssh: Could not resolve hostname", + "kex_exchange_identification:", } - for _, marker := range markers { - if strings.Contains(diag, marker) { + for _, prefix := range prefixes { + if strings.HasPrefix(line, prefix) { return true } } return false } +func lastNonEmptyDiagLine(diag string) string { + var line string + for _, raw := range strings.Split(diag, "\n") { + if trimmed := strings.TrimSpace(raw); trimmed != "" { + line = trimmed + } + } + return line +} + func shellSingleQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } diff --git a/pkg/cmd/exec/exec_test.go b/pkg/cmd/exec/exec_test.go index c6758a8a..292af659 100644 --- a/pkg/cmd/exec/exec_test.go +++ b/pkg/cmd/exec/exec_test.go @@ -34,6 +34,27 @@ func TestSSHFailureAllowsReplayOnlyBeforeSession(t *testing.T) { err: &sshAttemptError{exitCode: 255, diag: "Connection reset by peer"}, want: false, }, + { + name: "read timeout after the session", + err: &sshAttemptError{exitCode: 255, diag: "Read from remote host brev: Connection timed out\n"}, + want: false, + }, + { + name: "earlier refusal then a dropped session", + err: &sshAttemptError{ + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nclient_loop: send disconnect: Broken pipe\n", + }, + want: false, + }, + { + name: "every address failed before a session", + err: &sshAttemptError{ + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nssh: connect to host 10.0.0.2 port 22: Connection timed out\n", + }, + want: true, + }, { name: "connection refused", err: &sshAttemptError{exitCode: 255, diag: "ssh: connect to host gpu port 22: Connection refused"}, @@ -109,6 +130,40 @@ func TestExecDoesNotReplaySessionDrop(t *testing.T) { } } +func TestExecDoesNotReplayReadTimeoutAfterSession(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "Read from remote host brev: Connection timed out\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("read timeout after the session was replayed via SSH recovery:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + +func TestExecDoesNotReplayAfterEarlierConnectRefusal(t *testing.T) { + calls, output, err, panicked := execWithSSHResult(t, &sshAttemptError{ + err: fmt.Errorf("exit status 255"), + exitCode: 255, + diag: "ssh: connect to host 10.0.0.1 port 22: Connection refused\nclient_loop: send disconnect: Broken pipe\n", + }) + if calls != 1 { + t.Fatalf("remote command ran %d times, want 1", calls) + } + if strings.Contains(output, "Connection failed") { + t.Fatalf("session drop after an earlier refusal was replayed:\n%s", output) + } + if err == nil && panicked == nil { + t.Fatal("expected the ssh failure to be returned") + } +} + func TestExecStillRecoversWhenSSHNeverConnected(t *testing.T) { _, output, _, _ := execWithSSHResult(t, &sshAttemptError{ err: fmt.Errorf("exit status 255"), From c28da89f3e85aaabcb4e8b7a7a238942adac1335 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Sat, 14 Nov 2026 17:09:02 -0400 Subject: [PATCH 3/3] fix: count a two-line OpenSSH banner failure as pre-session sshpkt_fatal appends "Connection closed by port " after kex_exchange_identification logs the banner close. The last line alone is also a dropped session, so replay only when the previous non-empty line is that kex prefix. --- pkg/cmd/exec/exec.go | 35 +++++++++++++++++++++++++---------- pkg/cmd/exec/exec_test.go | 23 +++++++++++++++++++++-- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/pkg/cmd/exec/exec.go b/pkg/cmd/exec/exec.go index a7fc64d6..d8a88bdb 100644 --- a/pkg/cmd/exec/exec.go +++ b/pkg/cmd/exec/exec.go @@ -314,36 +314,51 @@ func sshFailureAllowsReplay(err error) bool { } // sshDiagIsPreSession reports whether ssh failed before a session existed. -// Only the last non-empty line of the -E log counts. An earlier -// "ssh: connect to host" line is normal when another address then opens a -// session that later drops, and that command must not be run again. +// Only the last non-empty line of the -E log counts, plus the OpenSSH +// banner-exchange pair below. An earlier "ssh: connect to host" line is +// normal when another address then opens a session that later drops, and +// that command must not be run again. // The line has to start with an OpenSSH pre-session prefix. A bare errno // string is not enough: "Read from remote host X: Connection timed out" is // written after the session is up. The strerror after the prefix is not // matched, so a translated message still counts. +// +// A banner failure is two lines. kex_exchange_identification logs the +// close, then sshpkt_fatal appends "Connection closed by +// port " or "Connection reset by port " and exits. +// That second line is also printed once a session exists, so it is +// pre-session only when the previous non-empty line is the kex line. func sshDiagIsPreSession(diag string) bool { - line := lastNonEmptyDiagLine(diag) + lines := nonEmptyDiagLines(diag) + if len(lines) == 0 { + return false + } + last := lines[len(lines)-1] prefixes := []string{ "ssh: connect to host ", "ssh: Could not resolve hostname", "kex_exchange_identification:", } for _, prefix := range prefixes { - if strings.HasPrefix(line, prefix) { + if strings.HasPrefix(last, prefix) { return true } } - return false + if len(lines) < 2 || !strings.HasPrefix(lines[len(lines)-2], "kex_exchange_identification:") { + return false + } + return strings.HasPrefix(last, "Connection closed by ") || + strings.HasPrefix(last, "Connection reset by ") } -func lastNonEmptyDiagLine(diag string) string { - var line string +func nonEmptyDiagLines(diag string) []string { + lines := make([]string, 0) for _, raw := range strings.Split(diag, "\n") { if trimmed := strings.TrimSpace(raw); trimmed != "" { - line = trimmed + lines = append(lines, trimmed) } } - return line + return lines } func shellSingleQuote(s string) string { diff --git a/pkg/cmd/exec/exec_test.go b/pkg/cmd/exec/exec_test.go index 292af659..49f8f007 100644 --- a/pkg/cmd/exec/exec_test.go +++ b/pkg/cmd/exec/exec_test.go @@ -81,10 +81,29 @@ func TestSSHFailureAllowsReplayOnlyBeforeSession(t *testing.T) { want: true, }, { - name: "handshake before the command", - err: &sshAttemptError{exitCode: 255, diag: "kex_exchange_identification: Connection closed by remote host"}, + name: "handshake closed before the banner", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: Connection closed by remote host\n\nConnection closed by UNKNOWN port 65535\n", + }, want: true, }, + { + name: "handshake reset before the banner", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: read: Connection reset by peer\nConnection reset by UNKNOWN port 65535\n", + }, + want: true, + }, + { + name: "kex line is not the one before the close", + err: &sshAttemptError{ + exitCode: 255, + diag: "kex_exchange_identification: Connection closed by remote host\nclient_loop: send disconnect: Broken pipe\nConnection closed by 10.0.0.8 port 22\n", + }, + want: false, + }, {name: "untyped error", err: fmt.Errorf("ssh: exit status 1"), want: false}, } for _, tc := range cases {