Skip to content

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

Go

MUL-5610: add Codex first-item wait telemetry (#6312)

Multica Eve55dc302d0ee3
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index ec8a2d1524..6989fdb5c2 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -108,6 +108,9 @@ func codexProcessWaitDelay() time.Duration {
}
type codexStderrClassification struct {
+ // modelRefreshFailure is the broad catalog failure bucket. It includes the
+ // narrower modelRefreshTimeout bucket, so the two counts are not additive.
+ modelRefreshFailure int
modelRefreshTimeout int
mcpInitTransport int
bareTimeout int
@@ -119,6 +122,7 @@ type codexStderrClassification struct {
func classifyCodexStartupStderr(stderr string, timedOut bool) codexStderrClassification {
lower := strings.ToLower(sanitizeCodexDiagnostic(stderr))
classification := codexStderrClassification{
+ modelRefreshFailure: strings.Count(lower, codexModelCatalogRefreshFailureSignal),
modelRefreshTimeout: strings.Count(lower, codexModelCatalogRefreshTimeoutSignal),
}
for _, line := range strings.Split(lower, "\n") {
@@ -127,7 +131,10 @@ func classifyCodexStartupStderr(stderr string, timedOut bool) codexStderrClassif
classification.mcpInitTransport++
}
}
- if timedOut && classification.modelRefreshTimeout == 0 && classification.mcpInitTransport == 0 {
+ // Any catalog refresh failure now owns the timeout classification, not only
+ // the narrower child-process timeout signal. This intentionally makes the
+ // existing bare-timeout bucket stricter across daemon versions.
+ if timedOut && classification.modelRefreshFailure == 0 && classification.mcpInitTransport == 0 {
classification.bareTimeout = 1
}
return classification
@@ -174,6 +181,47 @@ type codexTimeoutDiagnostic struct {
CodexVersion string
}
+// codexFirstItemWaitObservation records the interval from turn/started to the
+// first semantic progress or terminal outcome. start is called by the stdout
+// reader before it publishes status:running, while finish is called by the
+// lifecycle goroutine; the mutex keeps the cross-goroutine timestamp precise
+// without changing the watchdog's existing channel-driven semantics.
+type codexFirstItemWaitObservation struct {
+ mu sync.Mutex
+ startedAt time.Time
+ finishedAt time.Time
+ outcome string
+ stderr codexStderrClassification
+}
+
+func (o *codexFirstItemWaitObservation) start(now time.Time) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.startedAt.IsZero() {
+ o.startedAt = now
+ }
+}
+
+func (o *codexFirstItemWaitObservation) finish(now time.Time, outcome string, stderr codexStderrClassification) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.startedAt.IsZero() || o.outcome != "" {
+ return
+ }
+ o.finishedAt = now
+ o.outcome = outcome
+ o.stderr = stderr
+}
+
+func (o *codexFirstItemWaitObservation) snapshot() (time.Duration, string, codexStderrClassification, bool) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.startedAt.IsZero() || o.finishedAt.IsZero() || o.outcome == "" {
+ return 0, "", codexStderrClassification{}, false
+ }
+ return o.finishedAt.Sub(o.startedAt), o.outcome, o.stderr, true
+}
+
// codexBackend implements Backend by spawning `codex app-server --listen stdio://`
// and communicating via JSON-RPC 2.0 over stdin/stdout.
type codexBackend struct {
@@ -975,6 +1023,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
var finalAnswer, lastAgentMessage string
var semanticObserved atomic.Bool
turnNotificationGate := &codexTurnNotificationGate{}
+ firstItemWait := &codexFirstItemWaitObservation{}
// turnDone is set before starting the reader goroutine so there is no
// race between the lifecycle goroutine writing and the reader reading.
@@ -1004,9 +1053,13 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
lastAgentMessage = msg.Content
outputMu.Unlock()
}
+ activity := describeCodexSemanticActivity(msg)
+ if activity == "status:running" {
+ firstItemWait.start(time.Now())
+ }
trySend(msgCh, msg)
- trySendString(semanticActivityCh, describeCodexSemanticActivity(msg))
- if describeCodexSemanticActivity(msg) != "" {
+ trySendString(semanticActivityCh, activity)
+ if activity != "" {
semanticObserved.Store(true)
}
},
@@ -1284,6 +1337,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
"reaped", cleanupConfirmed,
"retry_safe", false,
"retry_attempted", false,
+ "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
"stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
"stderr_mcp_init_transport_count", classification.mcpInitTransport,
"stderr_bare_timeout_count", classification.bareTimeout,
@@ -1320,10 +1374,18 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
waitingForTurn := true
var timeoutDiagnostic codexTimeoutDiagnostic
var processExitErr error
+ finishFirstItemWait := func(outcome string) {
+ firstItemWait.finish(
+ time.Now(),
+ outcome,
+ classifyCodexStartupStderr(stderrBuf.Tail(), strings.HasSuffix(outcome, "_timeout")),
+ )
+ }
finishTurn := func(aborted bool) {
waitingForTurn = false
switch {
case aborted:
+ finishFirstItemWait("turn_aborted")
finalStatus = "aborted"
if errMsg := c.getTurnError(); errMsg != "" {
finalError = errMsg
@@ -1332,8 +1394,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
default:
if errMsg := c.getTurnError(); errMsg != "" {
+ finishFirstItemWait("turn_failed")
finalStatus = "failed"
finalError = errMsg
+ } else {
+ finishFirstItemWait("turn_completed")
}
}
}
@@ -1374,9 +1439,11 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
finishRunContextDone := func() {
waitingForTurn = false
if runCtx.Err() == context.DeadlineExceeded {
+ finishFirstItemWait("execution_timeout")
finalStatus = "timeout"
finalError = fmt.Sprintf("codex timed out after %s", timeout)
} else {
+ finishFirstItemWait("cancelled")
finalStatus = "aborted"
finalError = "execution cancelled"
}
@@ -1391,14 +1458,21 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
resetTimer(semanticTimer, semanticInactivityTimeout)
if activity == "status:running" && !firstTurnStarted {
firstTurnStarted = true
+ firstItemWait.start(time.Now())
firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)
firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C
} else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {
firstTurnProgressObserved = true
+ if activity == "error:terminal" {
+ finishFirstItemWait("turn_failed")
+ } else {
+ finishFirstItemWait("progress")
+ }
stopFirstTurnNoProgressTimer()
}
case <-firstTurnNoProgressTimerC:
waitingForTurn = false
+ finishFirstItemWait("no_progress_timeout")
finalStatus = "timeout"
timeoutDiagnostic = codexTimeoutDiagnostic{
Kind: codexTimeoutFirstTurnNoProgress,
@@ -1417,6 +1491,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
)
case <-semanticTimer.C:
waitingForTurn = false
+ finishFirstItemWait("semantic_inactivity_timeout")
finalStatus = "timeout"
timeoutDiagnostic = codexTimeoutDiagnostic{
Kind: codexTimeoutSemanticInactivity,
@@ -1445,6 +1520,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
finishRunContextDone()
} else {
waitingForTurn = false
+ finishFirstItemWait("process_exit")
finalStatus = "failed"
processExitErr = c.getProcessErr()
if processExitErr == nil {
@@ -1494,6 +1570,53 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
)
}
+ if waitLatency, outcome, classification, ok := firstItemWait.snapshot(); ok {
+ if waitLatency < 0 {
+ waitLatency = 0
+ }
+ // On timeout, cmd.Wait is the synchronization point that guarantees
+ // the stderr copy goroutine has drained. Reclassify from the complete
+ // bounded tail so a last-moment catalog/MCP signal is not reported as
+ // a bare timeout. Successful waits keep the snapshot taken at first
+ // progress so later turn stderr cannot pollute first-item telemetry.
+ if strings.HasSuffix(outcome, "_timeout") {
+ classification = classifyCodexStartupStderr(stderrTail, true)
+ }
+ fields := []any{
+ "phase", "first_item_wait",
+ "task_id", b.cfg.TaskID,
+ "runtime_id", b.cfg.RuntimeID,
+ "pid", cmd.Process.Pid,
+ "attempt", attempt,
+ "active_launches", activeLaunches,
+ "method", "turn/start",
+ "thread_id", threadID,
+ "turn_id", c.turnID,
+ "outcome", outcome,
+ "latency", waitLatency.Round(time.Millisecond).String(),
+ "latency_ms", waitLatency.Milliseconds(),
+ "timeout", firstTurnNoProgressTimeout.String(),
+ "semantic_inactivity_timeout", semanticInactivityTimeout.String(),
+ "codex_version", codexVersion,
+ "daemon_version", b.cfg.DaemonVersion,
+ "cleanup_confirmed", cleanupConfirmed,
+ "reaped", cleanupConfirmed,
+ // retry_safe describes the terminal attempt, not the measured wait
+ // interval. Successful samples therefore report false by design.
+ "retry_safe", startupRefreshRetrySafe,
+ "stderr_model_refresh_failure_count", classification.modelRefreshFailure,
+ "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,
+ "stderr_mcp_init_transport_count", classification.mcpInitTransport,
+ "stderr_bare_timeout_count", classification.bareTimeout,
+ }
+ switch outcome {
+ case "progress", "turn_completed":
+ b.cfg.Logger.Info("codex lifecycle", fields...)
+ default:
+ b.cfg.Logger.Warn("codex lifecycle", fields...)
+ }
+ }
+
outputMu.Lock()
finalOutput := codexDeliverableOutput(finalAnswer, lastAgentMessage)
outputMu.Unlock()
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 507738ff8b..db65f24047 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -2411,7 +2411,8 @@ func TestCodexExecuteThreadStartTimeoutLifecycleIsFailClosed(t *testing.T) {
if failure["retry_safe"] != false || failure["retry_attempted"] != false {
t.Fatalf("thread/start timeout must remain fail-closed: %v", failure)
}
- if failure["stderr_model_refresh_timeout_count"] != float64(1) ||
+ if failure["stderr_model_refresh_failure_count"] != float64(1) ||
+ failure["stderr_model_refresh_timeout_count"] != float64(1) ||
failure["stderr_mcp_init_transport_count"] != float64(1) ||
failure["stderr_bare_timeout_count"] != float64(0) {
t.Fatalf("unexpected stderr classification: %v", failure)
@@ -2745,7 +2746,12 @@ func TestClassifyCodexStartupStderr(t *testing.T) {
{
name: "model refresh timeout",
stderr: "failed to refresh available models: timeout waiting for child process to exit",
- want: codexStderrClassification{modelRefreshTimeout: 1},
+ want: codexStderrClassification{modelRefreshFailure: 1, modelRefreshTimeout: 1},
+ },
+ {
+ name: "model refresh non-timeout failure",
+ stderr: "failed to refresh available models: stream disconnected before completion",
+ want: codexStderrClassification{modelRefreshFailure: 1},
},
{
name: "mcp init transport",
@@ -2953,6 +2959,136 @@ func TestCodexExecuteFirstTurnNoProgressSurfacesDiagnostics(t *testing.T) {
}
}
+func TestCodexExecuteFirstItemWaitLifecycle(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))
+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })
+ // The helper budget owns the complete subtest, including a possible
+ // two-attempt retry chain, while ExecOptions.Timeout applies per attempt.
+ // Keep the helper deadline away from race-instrumented subprocess jitter.
+ const firstItemWaitTestBudget = 20 * time.Second
+
+ t.Run("successful progress emits a latency sample", func(t *testing.T) {
+ 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-first-item-ok"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-first-item-ok","turn":{"id":"turn-first-item-ok"}}}'`+"\n"+
+ `sleep 0.03`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-first-item-ok","item":{"type":"agentMessage","id":"msg-1","text":"Done"}}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-first-item-ok","turn":{"id":"turn-first-item-ok","status":"completed"}}}'`+"\n")
+
+ var logs bytes.Buffer
+ result, _ := executeFakeCodexCollectingMessagesWithConfig(t, fakePath, Config{
+ Logger: slog.New(slog.NewJSONHandler(&logs, nil)),
+ TaskID: "task-first-item-ok",
+ RuntimeID: "runtime-first-item-ok",
+ DaemonVersion: "daemon-test",
+ CodexVersion: "codex-test",
+ }, ExecOptions{
+ Timeout: 5 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ }, firstItemWaitTestBudget)
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got %+v", result)
+ }
+
+ entry := findCodexLifecyclePhase(t, parseJSONLogEntries(t, logs.String()), "first_item_wait")
+ for key, want := range map[string]any{
+ "task_id": "task-first-item-ok",
+ "runtime_id": "runtime-first-item-ok",
+ "attempt": float64(1),
+ "active_launches": float64(1),
+ "method": "turn/start",
+ "thread_id": "thr-first-item-ok",
+ "turn_id": "turn-first-item-ok",
+ "outcome": "progress",
+ "timeout": "4s",
+ "semantic_inactivity_timeout": "5s",
+ "codex_version": "codex-test",
+ "daemon_version": "daemon-test",
+ "cleanup_confirmed": true,
+ "reaped": true,
+ "retry_safe": false,
+ } {
+ if got := entry[key]; got != want {
+ t.Fatalf("entry[%s]=%v, want %v; entry=%v", key, got, want, entry)
+ }
+ }
+ if latency, ok := entry["latency_ms"].(float64); !ok || latency <= 0 {
+ t.Fatalf("missing/invalid latency_ms: %v", entry)
+ }
+ if entry["stderr_model_refresh_failure_count"] != float64(0) ||
+ entry["stderr_model_refresh_timeout_count"] != float64(0) ||
+ entry["stderr_mcp_init_transport_count"] != float64(0) ||
+ entry["stderr_bare_timeout_count"] != float64(0) {
+ t.Fatalf("successful wait has unexpected stderr classification: %v", entry)
+ }
+ })
+
+ t.Run("catalog failure is classified on every timed-out attempt", func(t *testing.T) {
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `DIR="$(dirname "$0")"`+"\n"+
+ `ATTEMPT=$(cat "$DIR/attempts" 2>/dev/null || echo 0)`+"\n"+
+ `ATTEMPT=$((ATTEMPT+1))`+"\n"+
+ `echo "$ATTEMPT" > "$DIR/attempts"`+"\n"+
+ `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-first-item-timeout"}}}'`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":3,"result":{}}'`+"\n"+
+ `echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-first-item-timeout","turn":{"id":"turn-first-item-timeout"}}}'`+"\n"+
+ `echo 'ERROR codex_models_manager::manager: failed to refresh available models: stream disconnected before completion' >&2`+"\n"+
+ `sleep 2`+"\n")
+
+ var logs bytes.Buffer
+ result, _ := executeFakeCodexCollectingMessagesWithConfig(t, fakePath, Config{
+ Logger: slog.New(slog.NewJSONHandler(&logs, nil)),
+ TaskID: "task-first-item-timeout",
+ RuntimeID: "runtime-first-item-timeout",
+ DaemonVersion: "daemon-test",
+ CodexVersion: "codex-test",
+ }, ExecOptions{
+ Timeout: 5 * time.Second,
+ SemanticInactivityTimeout: 100 * time.Millisecond,
+ }, firstItemWaitTestBudget)
+ if result.Status != "timeout" {
+ t.Fatalf("expected timeout after the bounded retry, got %+v", result)
+ }
+ assertCodexAttemptCount(t, fakePath, "2")
+
+ var waits []map[string]any
+ for _, entry := range parseJSONLogEntries(t, logs.String()) {
+ if entry["msg"] == "codex lifecycle" && entry["phase"] == "first_item_wait" {
+ waits = append(waits, entry)
+ }
+ }
+ if len(waits) != 2 {
+ t.Fatalf("expected one first-item sample per attempt, got %d: %v", len(waits), waits)
+ }
+ for i, entry := range waits {
+ if entry["attempt"] != float64(i+1) || entry["outcome"] != "no_progress_timeout" ||
+ entry["retry_safe"] != true || entry["cleanup_confirmed"] != true {
+ t.Fatalf("unexpected timeout lifecycle entry: %v", entry)
+ }
+ if entry["stderr_model_refresh_failure_count"] != float64(1) ||
+ entry["stderr_model_refresh_timeout_count"] != float64(0) ||
+ entry["stderr_mcp_init_transport_count"] != float64(0) ||
+ entry["stderr_bare_timeout_count"] != float64(0) {
+ t.Fatalf("catalog failure was misclassified: %v", entry)
+ }
+ }
+ })
+}
+
func TestCodexExecuteFailsWhenProcessExitsDuringActiveTurn(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
@@ -3642,7 +3778,13 @@ func executeFakeCodex(t *testing.T, fakePath string, opts ExecOptions) Result {
// the wait, so retry-exercising tests can ask for more than the default.
func executeFakeCodexCollectingMessages(t *testing.T, fakePath string, opts ExecOptions, budget time.Duration) (Result, []Message) {
t.Helper()
- backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ return executeFakeCodexCollectingMessagesWithConfig(t, fakePath, Config{Logger: slog.Default()}, opts, budget)
+}
+
+func executeFakeCodexCollectingMessagesWithConfig(t *testing.T, fakePath string, cfg Config, opts ExecOptions, budget time.Duration) (Result, []Message) {
+ t.Helper()
+ cfg.ExecutablePath = fakePath
+ backend, err := New("codex", cfg)
if err != nil {
t.Fatalf("new codex backend: %v", err)
}