Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(pi): keep turn error when process exits 1 [MUL-6585] (#7451)

buihongduc132acecb7dd6082
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index 5f2f64c855..f3d046eddb 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -429,7 +429,20 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
finalError = "execution cancelled"
} else if waitErr != nil && finalStatus == "completed" {
finalStatus = "failed"
- finalError = fmt.Sprintf("%s exited with error: %v", label, waitErr)
+ // Prefer the turn's provider message over the process exit code.
+ // Pi (and pi-print-clean-exit) exits 1 after stopReason=error, so
+ // Wait() wins this branch and used to drop lastTurnError. The
+ // classifier then saw only "exit status 1" and filed the run as
+ // non-retryable process_failure — even when the turn was a
+ // transient LiteLLM/OpenAI "Connection error." / "Request timed
+ // out." Keep the exit status as a suffix so a genuine crash is
+ // still visible (same shape as the OpenCode empty-step+exit
+ // composite).
+ if lastTurnError != "" {
+ finalError = fmt.Sprintf("%s; %s exited with error: %v", lastTurnError, label, waitErr)
+ } else {
+ finalError = fmt.Sprintf("%s exited with error: %v", label, waitErr)
+ }
} else if writeErr != nil && finalStatus == "completed" {
finalStatus = "failed"
finalError = fmt.Sprintf("%s prompt write failed: %v", label, writeErr)
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index 7f5fd75813..70358bc19c 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -2,6 +2,7 @@ package agent
import (
"context"
+ "fmt"
"log/slog"
"path/filepath"
"runtime"
@@ -229,6 +230,13 @@ func TestPiExecuteAttachesStdinPipe(t *testing.T) {
// piEventStreamScript builds a sh script that prints each JSON event on
// its own stdout line. Fixtures must not contain single quotes.
func piEventStreamScript(events []string) string {
+ return piEventStreamScriptWithExit(events, 0)
+}
+
+// piEventStreamScriptWithExit is piEventStreamScript plus an explicit
+// process exit code. Real Pi (and pi-print-clean-exit) exits 1 after a
+// turn whose last assistant stopReason is "error".
+func piEventStreamScriptWithExit(events []string, exitCode int) string {
var b strings.Builder
b.WriteString("#!/bin/sh\n")
// Real Pi reads the piped prompt to EOF before emitting events, so the fake
@@ -242,6 +250,9 @@ func piEventStreamScript(events []string) string {
b.WriteString(e)
b.WriteString("'\n")
}
+ if exitCode != 0 {
+ b.WriteString(fmt.Sprintf("exit %d\n", exitCode))
+ }
return b.String()
}
@@ -396,6 +407,59 @@ func TestPiExecuteSucceedsWhenRetryFollowsTurnError(t *testing.T) {
}
}
+func TestPiExecuteKeepsTurnErrorWhenProcessExitsNonZero(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // Real Pi (and pi-print-clean-exit) exits 1 after stopReason=error.
+ // Wait() used to win the completed-branch and drop lastTurnError, so
+ // the classifier only saw "exit status 1" (non-retryable
+ // process_failure). The provider message must survive so
+ // "Connection error." / "Request timed out." classify as
+ // provider_network.
+ events := []string{
+ `{"type":"agent_start"}`,
+ `{"type":"turn_start"}`,
+ `{"type":"turn_end","message":{"role":"assistant","content":[],"model":"test","usage":{"input":0,"output":0},"stopReason":"error","errorMessage":"Connection error."}}`,
+ `{"type":"agent_end","messages":[],"willRetry":false}`,
+ }
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ writeTestExecutable(t, fakePath, []byte(piEventStreamScriptWithExit(events, 1)))
+
+ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "Connection error.") {
+ t.Fatalf("Error: got %q, want it to carry the provider message", result.Error)
+ }
+ if !strings.Contains(result.Error, "exited with error") {
+ t.Fatalf("Error: got %q, want the process exit still visible as a suffix", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
func TestStripPiToolCallMarkup(t *testing.T) {
tests := map[string]string{
`before call:bash{command:<|"|>cd repo/path && ls -F<|"|>}<tool_call|> after`: "before after",
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index af451f5ae6..eec226c42f 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -190,22 +190,30 @@ func Classify(rawError string) Reason {
// matching rule 13 by accident) and agent_error.unknown respectively;
// neither is on the retry allowlist, so a transient cut ended the task
// outright and max_attempts never applied (#6522).
- // Mirror these substrings into the MUL-1949 offline backfill SQL.
- case containsAny(lower,
- "stream disconnected",
- opencodeStreamEndedPrefix,
- "connection closed",
- "mid-response",
- "error sending request",
- "unable to connect",
- "dial tcp",
- "connection refused",
- "connectionrefused",
- "dns",
- "i/o timeout",
- "deadline exceeded",
- "timeout exceeded while awaiting",
- ):
+ // Pi's OpenAI-compatible SDK surfaces a dropped LiteLLM/OpenAI call as
+ // the bare strings "Connection error." and "Request timed out." on
+ // turn_end.errorMessage (then exits 1). Those used to fall through to
+ // process_failure via "exit status 1" and terminate the task with no
+ // retry (BHD-135). isPiProviderNetworkError matches only the exact bare
+ // messages and the stable Pi/OMP exit composite, rather than treating
+ // the same broad substrings from local tools or MCP servers as retryable.
+ // Mirror these Pi message shapes into the MUL-1949 offline backfill SQL.
+ case isPiProviderNetworkError(lower),
+ containsAny(lower,
+ "stream disconnected",
+ opencodeStreamEndedPrefix,
+ "connection closed",
+ "mid-response",
+ "error sending request",
+ "unable to connect",
+ "dial tcp",
+ "connection refused",
+ "connectionrefused",
+ "dns",
+ "i/o timeout",
+ "deadline exceeded",
+ "timeout exceeded while awaiting",
+ ):
return ReasonAgentProviderNetwork
// 8. Model not found / unavailable. The SQL uses `%model%not%found%`,
@@ -397,6 +405,17 @@ var legacyOpenclawCLITimeoutReasons = map[string]bool{
"agent_error": true,
}
+func isPiProviderNetworkError(lower string) bool {
+ for _, message := range []string{"connection error.", "request timed out."} {
+ if lower == message ||
+ strings.HasPrefix(lower, message+"; pi exited with error: ") ||
+ strings.HasPrefix(lower, message+"; omp exited with error: ") {
+ return true
+ }
+ }
+ return false
+}
+
// opencodeStreamEndedPrefix opens every failure the OpenCode terminal-signal
// guard raises (pkg/agent/opencode.go). Exactly one code path emits it, and it
// is a PREFIX of the whole error rather than a phrase somewhere inside it, so
diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.go
index 84de211164..0e6e6cbe40 100644
--- a/server/pkg/taskfailure/classify_test.go
+++ b/server/pkg/taskfailure/classify_test.go
@@ -121,6 +121,14 @@ func TestClassifyRules(t *testing.T) {
{"opencode continuation never started", "opencode stream ended without a terminal signal (last step required a continuation that never started)", ReasonAgentProviderNetwork},
{"opencode empty final step", "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing", ReasonAgentProviderNetwork},
{"opencode empty step with process exit appended", "opencode stream ended on an empty step (no text, no tool call, no reported usage) — the provider produced nothing; opencode exited with error: exit status 1", ReasonAgentProviderNetwork},
+ // BHD-135: Pi's OpenAI-compatible SDK wording for a dropped LiteLLM
+ // call. Bare strings, then the same strings glued to "exit status 1"
+ // after pi-print-clean-exit forces a non-zero wrap-up.
+ {"pi connection error", "Connection error.", ReasonAgentProviderNetwork},
+ {"pi connection error with exit status wins over process failure", "Connection error.; pi exited with error: exit status 1", ReasonAgentProviderNetwork},
+ {"pi request timed out", "Request timed out.", ReasonAgentProviderNetwork},
+ {"pi request timed out with exit status wins over process failure", "Request timed out.; pi exited with error: exit status 1", ReasonAgentProviderNetwork},
+ {"omp connection error with exit status wins over process failure", "Connection error.; omp exited with error: exit status 1", ReasonAgentProviderNetwork},
// 8. Model not found / unavailable.
{"model not found", "Error: model claude-3-opus-99 not found", ReasonAgentModelNotFoundOrUnavailable},
@@ -158,6 +166,12 @@ func TestClassifyRules(t *testing.T) {
// 14. Catchall.
{"unrecognized", "the agent gave up for reasons unknown", ReasonAgentUnknown},
{"sentence with no marker", "Hello world.", ReasonAgentUnknown},
+ // Pi's two short provider messages must not become broad substring
+ // matches: local tool and MCP failures are deterministic and retrying
+ // them only repeats the same failure.
+ {"local tool connection error is not provider network", "local tool connection error while opening its database", ReasonAgentUnknown},
+ {"mcp request timeout is not provider network", "MCP server request timed out while loading configuration", ReasonAgentUnknown},
+ {"local connection error with exit remains process failure", "MCP server connection error; agent exited with error: exit status 1", ReasonAgentProcessFailure},
// 15. Digit-boundary regression: 3-digit HTTP status codes must NOT
// match when embedded in a longer number. Before the fix these