Skip to content

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

Go

Fix: fail fast when Codex app-server exits MUL-2840 (#4228)

Bohan Jiang114a1ffb8fdc
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index a0acb32916..3a7803127a 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"os"
@@ -57,6 +58,8 @@ const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"
const codexModelCatalogRefreshTimeoutSignal = "failed to refresh available models: timeout waiting for child process to exit"
+var errCodexProcessExited = errors.New("codex process exited")
+
type codexTimeoutKind int
const (
@@ -589,6 +592,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
cfg: b.cfg,
stdin: stdin,
pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
notificationProtocol: "unknown",
onMessage: func(msg Message) {
logCodexAgentMessage(b.cfg.Logger, msg)
@@ -625,7 +629,11 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
c.handleLine(line)
}
- c.closeAllPending(fmt.Errorf("codex process exited"))
+ if err := scanner.Err(); err != nil {
+ c.markProcessExited(fmt.Errorf("%w: %v", errCodexProcessExited, err))
+ return
+ }
+ c.markProcessExited(errCodexProcessExited)
}()
// drainAndWait closes stdin so codex shuts down, then joins cmd.Wait().
@@ -739,20 +747,34 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
waitingForTurn := true
var timeoutDiagnostic codexTimeoutDiagnostic
+ var processExitErr error
+ finishTurn := func(aborted bool) {
+ waitingForTurn = false
+ switch {
+ case aborted:
+ finalStatus = "aborted"
+ finalError = "turn was aborted"
+ default:
+ if errMsg := c.getTurnError(); errMsg != "" {
+ finalStatus = "failed"
+ finalError = errMsg
+ }
+ }
+ }
+ finishRunContextDone := func() {
+ waitingForTurn = false
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("codex timed out after %s", timeout)
+ } else {
+ finalStatus = "aborted"
+ finalError = "execution cancelled"
+ }
+ }
for waitingForTurn {
select {
case aborted := <-turnDone:
- waitingForTurn = false
- switch {
- case aborted:
- finalStatus = "aborted"
- finalError = "turn was aborted"
- default:
- if errMsg := c.getTurnError(); errMsg != "" {
- finalStatus = "failed"
- finalError = errMsg
- }
- }
+ finishTurn(aborted)
case activity := <-semanticActivityCh:
lastSemanticActivity = time.Now()
lastSemanticActivityDescription = activity
@@ -803,13 +825,23 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
"idle_for", time.Since(lastSemanticActivity).Round(time.Millisecond).String(),
)
case <-runCtx.Done():
- waitingForTurn = false
- if runCtx.Err() == context.DeadlineExceeded {
- finalStatus = "timeout"
- finalError = fmt.Sprintf("codex timed out after %s", timeout)
- } else {
- finalStatus = "aborted"
- finalError = "execution cancelled"
+ finishRunContextDone()
+ case <-c.processDone:
+ select {
+ case aborted := <-turnDone:
+ finishTurn(aborted)
+ default:
+ if runCtx.Err() != nil {
+ finishRunContextDone()
+ } else {
+ waitingForTurn = false
+ finalStatus = "failed"
+ processExitErr = c.getProcessErr()
+ if processExitErr == nil {
+ processExitErr = errCodexProcessExited
+ }
+ finalError = processExitErr.Error()
+ }
}
}
}
@@ -837,6 +869,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
drainAndWait()
+ if processExitErr != nil {
+ finalError = withAgentStderr(processExitErr.Error(), "codex", stderrBuf.Tail())
+ }
if timeoutDiagnostic.Kind != codexTimeoutNone {
timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), execPath, cmd.Env, b.cfg.Logger)
finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrBuf.Tail())
@@ -887,11 +922,12 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
// startOrResumeThread picks between Codex's thread/resume and thread/start
// based on opts.ResumeSessionID. When a prior thread ID is provided it first
-// tries thread/resume; any error (unknown thread, schema mismatch, transport
-// failure) is logged and the method falls back to thread/start so the task
-// still executes. The returned threadID is what subsequent turn/start calls
-// must reference, and resumed indicates whether the prior thread was picked
-// up (only useful for logging).
+// tries thread/resume; recoverable protocol errors (unknown thread, schema
+// mismatch) fall back to thread/start so the task still executes, while
+// transport/process failures fail fast because the app-server can no longer
+// answer a fresh start request. The returned threadID is what subsequent
+// turn/start calls must reference, and resumed indicates whether the prior
+// thread was picked up (only useful for logging).
func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions, logger *slog.Logger) (string, bool, error) {
if priorThreadID := opts.ResumeSessionID; priorThreadID != "" {
// thread/resume reuses the thread's persisted model and reasoning
@@ -915,6 +951,10 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,
}
logger.Warn("codex thread/resume returned no thread ID; falling back to thread/start", "prior_thread_id", priorThreadID)
} else {
+ if isCodexTransportError(err) {
+ logger.Warn("codex thread/resume failed due to transport error; not falling back to thread/start", "prior_thread_id", priorThreadID, "error", err)
+ return "", false, fmt.Errorf("codex thread/resume failed: %w", err)
+ }
logger.Warn("codex thread/resume failed; falling back to thread/start", "prior_thread_id", priorThreadID, "error", err)
}
}
@@ -1156,6 +1196,8 @@ type codexClient struct {
mu sync.Mutex
nextID int
pending map[int]*pendingRPC
+ processDone chan struct{}
+ processErr error
threadID string
turnID string
onMessage func(Message)
@@ -1201,7 +1243,19 @@ type rpcResult struct {
}
func (c *codexClient) request(ctx context.Context, method string, params any) (json.RawMessage, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
c.mu.Lock()
+ if c.processErr != nil {
+ err := c.processErr
+ c.mu.Unlock()
+ return nil, err
+ }
+ if c.processDone == nil {
+ c.processDone = make(chan struct{})
+ }
+ processDone := c.processDone
c.nextID++
id := c.nextID
pr := &pendingRPC{ch: make(chan rpcResult, 1), method: method}
@@ -1239,6 +1293,18 @@ func (c *codexClient) request(ctx context.Context, method string, params any) (j
select {
case res := <-pr.ch:
return res.result, res.err
+ case <-processDone:
+ c.mu.Lock()
+ delete(c.pending, id)
+ err := c.processErr
+ c.mu.Unlock()
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return nil, ctxErr
+ }
+ if err == nil {
+ err = errCodexProcessExited
+ }
+ return nil, err
case <-ctx.Done():
c.mu.Lock()
delete(c.pending, id)
@@ -1291,6 +1357,40 @@ func (c *codexClient) closeAllPending(err error) {
}
}
+func (c *codexClient) markProcessExited(err error) {
+ if err == nil {
+ err = errCodexProcessExited
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.processErr == nil {
+ c.processErr = err
+ if c.processDone != nil {
+ close(c.processDone)
+ }
+ }
+ for id, pr := range c.pending {
+ pr.ch <- rpcResult{err: err}
+ delete(c.pending, id)
+ }
+}
+
+func (c *codexClient) getProcessErr() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.processErr
+}
+
+func isCodexTransportError(err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, errCodexProcessExited) {
+ return true
+ }
+ return strings.HasPrefix(err.Error(), "write ")
+}
+
func (c *codexClient) handleLine(line string) {
var raw map[string]json.RawMessage
if err := json.Unmarshal([]byte(line), &raw); err != nil {
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 9edc02a1aa..8b08a88c73 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"os"
@@ -22,9 +23,10 @@ func newTestCodexClient(t *testing.T) (*codexClient, *fakeStdin, []Message) {
var messages []Message
c := &codexClient{
- cfg: Config{Logger: slog.Default()},
- stdin: fs,
- pending: make(map[int]*pendingRPC),
+ cfg: Config{Logger: slog.Default()},
+ stdin: fs,
+ pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
onMessage: func(msg Message) {
mu.Lock()
messages = append(messages, msg)
@@ -763,6 +765,55 @@ func TestCodexCloseAllPending(t *testing.T) {
}
}
+func TestCodexRequestFailsImmediatelyAfterProcessExit(t *testing.T) {
+ t.Parallel()
+
+ c, fs, _ := newTestCodexClient(t)
+ c.markProcessExited(errCodexProcessExited)
+
+ _, err := c.request(context.Background(), "thread/start", map[string]any{})
+ if !errors.Is(err, errCodexProcessExited) {
+ t.Fatalf("request error = %v, want errCodexProcessExited", err)
+ }
+ if lines := fs.Lines(); len(lines) != 0 {
+ t.Fatalf("request should not write after process exit, wrote %d lines", len(lines))
+ }
+}
+
+func TestCodexRequestPrefersContextCancellationOverProcessExit(t *testing.T) {
+ t.Parallel()
+
+ c, fs, _ := newTestCodexClient(t)
+ processExitMarked := make(chan error, 1)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ go func() {
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ if len(fs.Lines()) >= 1 {
+ cancel()
+ c.markProcessExited(errCodexProcessExited)
+ processExitMarked <- nil
+ return
+ }
+ if time.Now().After(deadline) {
+ processExitMarked <- fmt.Errorf("timed out waiting for request write")
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ }()
+
+ _, err := c.request(ctx, "thread/start", map[string]any{})
+ if markErr := <-processExitMarked; markErr != nil {
+ t.Fatal(markErr)
+ }
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("request error = %v, want context.Canceled", err)
+ }
+}
+
func TestCodexHandleInvalidJSON(t *testing.T) {
t.Parallel()
@@ -1080,6 +1131,61 @@ func TestCodexStartOrResumeThreadFallsBackOnResumeError(t *testing.T) {
}
}
+func TestCodexStartOrResumeThreadDoesNotFallBackAfterProcessExit(t *testing.T) {
+ t.Parallel()
+
+ c, fs, _ := newTestCodexClient(t)
+ processExitMarked := make(chan error, 1)
+ go func() {
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ if len(fs.Lines()) >= 1 {
+ c.markProcessExited(errCodexProcessExited)
+ processExitMarked <- nil
+ return
+ }
+ if time.Now().After(deadline) {
+ processExitMarked <- fmt.Errorf("timed out waiting for thread/resume request")
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ threadID, resumed, err := c.startOrResumeThread(
+ ctx,
+ ExecOptions{Cwd: "/work", ResumeSessionID: "thr_stale"},
+ slog.Default(),
+ )
+ if markErr := <-processExitMarked; markErr != nil {
+ t.Fatal(markErr)
+ }
+ if !errors.Is(err, errCodexProcessExited) {
+ t.Fatalf("startOrResumeThread error = %v, want errCodexProcessExited", err)
+ }
+ if threadID != "" {
+ t.Fatalf("threadID = %q, want empty", threadID)
+ }
+ if resumed {
+ t.Fatal("resumed should be false on process exit")
+ }
+ lines := fs.Lines()
+ if len(lines) != 1 {
+ t.Fatalf("expected only thread/resume request, got %d lines: %v", len(lines), lines)
+ }
+ var req struct {
+ Method string `json:"method"`
+ }
+ if err := json.Unmarshal([]byte(lines[0]), &req); err != nil {
+ t.Fatalf("unmarshal request: %v", err)
+ }
+ if req.Method != "thread/resume" {
+ t.Fatalf("request method = %q, want thread/resume", req.Method)
+ }
+}
+
func TestCodexStartOrResumeThreadFallsBackWhenResumeReturnsNoID(t *testing.T) {
t.Parallel()
@@ -1334,6 +1440,74 @@ func TestCodexExecuteFirstTurnNoProgressSurfacesDiagnostics(t *testing.T) {
}
}
+func TestCodexExecuteFailsWhenProcessExitsDuringActiveTurn(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-crash"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-crash","turn":{"id":"turn-crash"}}}'`+"\n"+
+ `echo 'fatal: app-server crashed after turn/start' >&2`+"\n"+
+ `exit 2`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Timeout: 5 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ })
+ if result.Status != "failed" {
+ t.Fatalf("expected failed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "codex process exited") {
+ t.Fatalf("expected process-exit error, got %q", result.Error)
+ }
+ if !strings.Contains(result.Error, "fatal: app-server crashed after turn/start") {
+ t.Fatalf("expected stderr tail in error, got %q", result.Error)
+ }
+ if strings.Contains(result.Error, "timeout") {
+ t.Fatalf("process exit should fail fast instead of timeout, got %q", result.Error)
+ }
+}
+
+func TestCodexExecuteTimeoutWinsOverProcessExitDuringActiveTurn(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-timeout"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-timeout","turn":{"id":"turn-timeout"}}}'`+"\n"+
+ `read line`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Timeout: 5 * time.Second,
+ SemanticInactivityTimeout: 30 * time.Second,
+ })
+ if result.Status != "timeout" {
+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "codex timed out after") {
+ t.Fatalf("expected timeout error, got %q", result.Error)
+ }
+ if strings.Contains(result.Error, "codex process exited") {
+ t.Fatalf("timeout should win over process EOF, got %q", result.Error)
+ }
+}
+
func TestCodexExecuteFirstTurnRetryErrorDoesNotSatisfyProgress(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {