Skip to content

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

Go

fix(codex): unhang cleanup after stdout scanner overflow (#4520) (#4563)

Multica Eveaa4478af524e
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index d6b2ed6029..099bc787f7 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -16,6 +16,8 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
+ "syscall"
"time"
)
@@ -48,6 +50,22 @@ const (
codexGracefulShutdownTimeout = 10 * time.Second
)
+// codexGracefulShutdownTimeoutNanos optionally overrides
+// codexGracefulShutdownTimeout for tests, in nanoseconds. Zero or negative
+// values keep the production default. Tests for the cleanup-on-scanner-
+// overflow path (#4520) use it to shrink the grace window from 10 s to a
+// few hundred ms so the regression runs in a normal `go test` budget
+// instead of burning two full grace windows per cleanup phase. Mirrors
+// the opencodeTerminateGraceNanos hook.
+var codexGracefulShutdownTimeoutNanos atomic.Int64
+
+func codexGracefulShutdown() time.Duration {
+ if n := codexGracefulShutdownTimeoutNanos.Load(); n > 0 {
+ return time.Duration(n)
+ }
+ return codexGracefulShutdownTimeout
+}
+
// CodexSemanticInactivityMarker prefixes timeout errors emitted when Codex
// stops making semantic progress while the process is still alive.
const CodexSemanticInactivityMarker = "codex semantic inactivity timeout"
@@ -547,6 +565,26 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
codexArgs := buildCodexArgs(opts, b.cfg.Logger)
cmd := exec.CommandContext(runCtx, execPath, codexArgs...)
hideAgentWindow(cmd)
+ // Run codex in its own process group so a cancel-on-stuck cleanup
+ // reaches the whole tree — the codex Node wrapper plus the native
+ // Rust app-server it spawns — not just the direct child. Without
+ // this, killing the leader leaves grandchildren as orphans that
+ // keep consuming memory until the OS reaps them; see #4520, where a
+ // scanner overflow during thread/resume otherwise leaked Codex
+ // processes indefinitely. configureProcessGroup is a no-op on
+ // Windows.
+ configureProcessGroup(cmd)
+ // Override the default exec.CommandContext cancel behaviour. The
+ // default sends SIGKILL only to cmd.Process (the leader); we instead
+ // signal the whole process group so descendants die too. Returning
+ // nil keeps exec from logging a spurious error; cmd.WaitDelay below
+ // still backstops cmd.Wait() if the kill leaves an open pipe.
+ cmd.Cancel = func() error {
+ if cmd.Process != nil {
+ signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ }
+ return nil
+ }
// Bound the wait after the context is cancelled so a stuck child (or an
// open pipe held by a grandchild) can't hang cmd.Wait() forever. Matches
// the other long-lived backends (claude, copilot, cursor, …).
@@ -644,11 +682,89 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
// code that reads stderrBuf.Tail() must call drainAndWait() first.
// sync.Once makes it safe to call from both error paths and the deferred
// cleanup.
+ //
+ // drainAndWait is also the cleanup safety net for the scanner-overflow
+ // path (#4520). When codex emits a single stdout line larger than the
+ // scanner's MaxScanTokenSize, the reader goroutine returns with
+ // scanner.Err() set, fails all in-flight RPCs via markProcessExited, and
+ // closes readerDone — but the codex child process is still alive and is
+ // now blocked trying to write the rest of the oversized line into a
+ // stdout pipe nobody is reading. A naive stdin.Close()+cmd.Wait() then
+ // hangs forever: codex never reaches its stdin-read syscall, so it never
+ // sees EOF, never exits, and cmd.Wait() never returns. The lifecycle
+ // goroutine therefore never sends a failed Result, the outer daemon
+ // blocks on its result channel, and the higher-level fresh-session
+ // fallback never fires.
+ //
+ // To stay correct under both clean shutdown and the stuck-child case,
+ // drainAndWait runs in two bounded phases:
+ //
+ // 1. Close stdin and wait for the reader goroutine to finish, capped by
+ // codexGracefulShutdownTimeout. The reader exits when codex closes
+ // stdout on its own (clean shutdown — gives OTEL batch exporters a
+ // chance to flush) OR when the scanner errors out (overflow case —
+ // readerDone is already closed and the select returns immediately).
+ // Per os/exec docs, calling cmd.Wait() while reads are still
+ // in-flight on a StdoutPipe-returned pipe is incorrect because Wait
+ // closes the pipe and turns pending reads into spurious errors, so
+ // we must wait for the reader first.
+ //
+ // 2. Wait for cmd.Wait() to return, capped by another
+ // codexGracefulShutdownTimeout. Normally this returns immediately
+ // because the process has already exited. In the stuck-child case
+ // the process is still alive — we cancel the runCtx, which fires
+ // cmd.Cancel (the group-SIGKILL helper installed above), and
+ // cmd.WaitDelay then guarantees cmd.Wait() returns even if pipes
+ // stay open.
var waitOnce sync.Once
drainAndWait := func() {
waitOnce.Do(func() {
stdin.Close()
- _ = cmd.Wait()
+
+ grace := codexGracefulShutdown()
+
+ // Phase 1: let the reader finish before invoking cmd.Wait().
+ select {
+ case <-readerDone:
+ // reader drained cleanly (codex shutdown closed stdout)
+ // or aborted early (e.g. scanner overflow). Either way it
+ // is now safe to call cmd.Wait().
+ case <-time.After(grace):
+ // codex did not close stdout within the grace window. Force
+ // the shutdown via context cancellation — cmd.Cancel
+ // group-kills the tree, the reader unblocks when stdout
+ // EOFs, and we proceed to phase 2.
+ b.cfg.Logger.Warn("codex did not close stdout after stdin EOF; forcing shutdown",
+ "pid", cmd.Process.Pid,
+ "grace", grace.String(),
+ )
+ cancel()
+ <-readerDone
+ }
+
+ // Phase 2: bound cmd.Wait() in case the process is still alive
+ // (scanner-overflow case: reader exited early on its own while
+ // codex stayed blocked writing into a full stdout pipe).
+ waitCh := make(chan struct{})
+ go func() {
+ _ = cmd.Wait()
+ close(waitCh)
+ }()
+ select {
+ case <-waitCh:
+ // reaped cleanly.
+ case <-time.After(grace):
+ b.cfg.Logger.Warn("codex process still alive after reader exited; forcing shutdown",
+ "pid", cmd.Process.Pid,
+ "grace", grace.String(),
+ )
+ cancel()
+ // WaitDelay (10s) is the final backstop: even if the
+ // group-kill races with an open pipe held by a
+ // descendant, cmd.Wait() returns within WaitDelay of the
+ // cancel.
+ <-waitCh
+ }
})
}
@@ -853,24 +969,11 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
duration := time.Since(startTime)
b.cfg.Logger.Info("codex finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
- // Close stdin to signal the app-server to exit. Prefer letting codex
- // shut down on its own: a clean exit runs codex's shutdown path, which
- // force-flushes its OTEL batch exporters — killing it immediately (via
- // cancel → SIGKILL) drops the task's buffered telemetry. Give it a
- // bounded grace period; only force-cancel if it doesn't exit, so the
- // reader goroutine can never block forever on scanner.Scan().
- stdin.Close()
- select {
- case <-readerDone:
- // codex closed stdout on its own — clean shutdown, telemetry flushed.
- case <-time.After(codexGracefulShutdownTimeout):
- b.cfg.Logger.Warn("codex did not exit after stdin close; forcing shutdown",
- "pid", cmd.Process.Pid,
- "grace", codexGracefulShutdownTimeout.String(),
- )
- cancel()
- <-readerDone
- }
+ // Run cleanup. drainAndWait handles the graceful-then-cancel pattern
+ // in two bounded phases (see its declaration): wait for the reader,
+ // then wait for cmd.Wait(), force-cancelling either if the grace
+ // window expires. A clean shutdown lets codex flush OTEL telemetry;
+ // a stuck process is killed via the process-group SIGKILL.
drainAndWait()
if processExitErr != nil {
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 4aac5de607..21eb5327cd 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1574,6 +1574,86 @@ func TestCodexExecuteFailsWhenProcessExitsDuringActiveTurn(t *testing.T) {
t.Fatalf("process exit should fail fast instead of timeout, got %q", result.Error)
}
}
+func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
+ // Not t.Parallel(): this test mutates codexGracefulShutdownTimeoutNanos
+ // globally, so running concurrently with other codex Execute tests
+ // would shrink their grace window too and risk flakes.
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // Regression for GH#4520. On `thread/resume`, the fake codex emits a
+ // single stdout line larger than the daemon's bufio.Scanner cap (10 MB),
+ // which trips "bufio.Scanner: token too long" in the reader goroutine.
+ // Pre-fix, drainAndWait then hung forever on cmd.Wait(): the reader had
+ // stopped consuming the pipe, codex was blocked writing into a full
+ // stdout buffer, stdin.Close never unblocked codex, and the deferred
+ // cancel() ran AFTER drainAndWait in the LIFO defer order. The failed
+ // Result therefore never reached the outer daemon and its
+ // fresh-session fallback never fired.
+ //
+ // Post-fix, drainAndWait does graceful-then-cancel in two bounded phases
+ // (see codex.go), and cmd.Cancel group-SIGKILLs the codex tree so the
+ // process exits even when stdin EOF isn't sufficient. We verify the
+ // failed Result reaches the caller within a small bound and carries an
+ // empty SessionID so the outer daemon's PriorSessionID-with-empty-
+ // SessionID fallback can retry a fresh session.
+ codexGracefulShutdownTimeoutNanos.Store(int64(500 * time.Millisecond))
+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ // Emit a > 10 MB single line with no embedded newline. printf
+ // avoids the trailing newline echo would add; head + tr generates
+ // the bulk payload in pure POSIX shell. The scanner errors out at
+ // 10 MB even though we write 11 MB.
+ `printf '{"jsonrpc":"2.0","id":2,"result":{"big":"'`+"\n"+
+ `head -c 11000000 /dev/zero | tr '\0' 'x'`+"\n"+
+ `printf '"}}\n'`+"\n"+
+ // Hold the process open without reading more stdin. Pre-fix this
+ // hangs cmd.Wait() because codex never sees stdin EOF (it isn't
+ // in a read syscall) and the stdout pipe stays full. Cleanup must
+ // fall back to the group-SIGKILL path to make progress.
+ `sleep 30`+"\n")
+
+ start := time.Now()
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Cwd: t.TempDir(),
+ ResumeSessionID: "thr_prior",
+ Timeout: 30 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ })
+ elapsed := time.Since(start)
+
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (error=%q, elapsed=%s)",
+ result.Status, result.Error, elapsed)
+ }
+ if !strings.Contains(result.Error, "token too long") {
+ t.Fatalf("expected error to surface scanner overflow cause, got %q",
+ result.Error)
+ }
+ // Empty SessionID is the contract the outer daemon fallback relies on
+ // (daemon.go: result.Status == "failed" && PriorSessionID != "" &&
+ // result.SessionID == "" → retry fresh). Verify thread/resume failure
+ // preserves that contract.
+ if result.SessionID != "" {
+ t.Fatalf("expected empty SessionID so outer fallback retries fresh, got %q",
+ result.SessionID)
+ }
+ // With the shrunken 500 ms grace, two bounded phases plus the SIGKILL
+ // round-trip should complete in ~1-2 s. Pre-fix this test would block
+ // until the executeFakeCodex 10 s outer timeout and fail with "timeout
+ // waiting for result". We assert a much tighter bound so a future
+ // regression cannot quietly slip back up to 10 s.
+ if elapsed > 5*time.Second {
+ t.Fatalf("cleanup took %s, expected < 5s with shrunken grace (bug regressed?)",
+ elapsed)
+ }
+}
+
func TestCodexExecuteSurfacesUnsupportedServerRequestOnInterruptedTurn(t *testing.T) {
t.Parallel()