Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): retry codex semantic inactivity fresh (#2593)
iYuan2f1f90c11a2e
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex ee1a6c830c..51ce226323 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -40,6 +40,7 @@ export type AgentRuntime = RuntimeDevice;export type TaskFailureReason =| "agent_error"| "timeout"+ | "codex_semantic_inactivity"| "runtime_offline"| "runtime_recovery"| "manual";diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex 3df05a2a79..6572bac2be 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -10,6 +10,7 @@ import type { TaskFailureReason } from "@multica/core/types";export const failureReasonLabel: Record<TaskFailureReason, string> = {agent_error: "Agent execution error",timeout: "Task timed out",+ codex_semantic_inactivity: "Codex semantic inactivity timeout",runtime_offline: "Daemon offline",runtime_recovery: "Daemon restarted",manual: "Cancelled by user",diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.goindex 4da4161e5d..bd5a546337 100644--- a/server/cmd/server/rerun_session_test.go+++ b/server/cmd/server/rerun_session_test.go@@ -9,8 +9,8 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service"- db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// setupRerunTestFixture creates an issue assigned to the integration test@@ -168,6 +168,134 @@ func TestGetLastTaskSessionExcludesAPIInvalidRequest(t *testing.T) {}}+// TestGetLastTaskSessionExcludesCodexSemanticInactivity covers Codex+// semantic inactivity timeouts: the failed task did establish a session, but+// resuming it can replay the same stuck Codex state. The resume lookup must+// skip that session.+func TestGetLastTaskSessionExcludesCodexSemanticInactivity(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ ctx := context.Background()++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, failure_reason)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '2 minutes', now() - interval '2 minutes', 'HEALTHY-SESSION', '/tmp/healthy', 'timeout')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert healthy failed task: %v", err)+ }++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, failure_reason, error)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute', 'CODEX-STUCK-SESSION', '/tmp/codex-stuck', 'codex_semantic_inactivity',+ 'codex semantic inactivity timeout after 10m0s without agent progress (last activity: tool-result:exec_command)')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert codex semantic inactivity task: %v", err)+ }++ queries := db.New(testPool)+ prior, err := queries.GetLastTaskSession(ctx, db.GetLastTaskSessionParams{+ AgentID: pgtype.UUID{Bytes: parseUUIDBytes(agentID), Valid: true},+ IssueID: pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},+ })+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "HEALTHY-SESSION" {+ t.Fatalf("expected HEALTHY-SESSION, got %q", prior.SessionID.String)+ }+}++func TestCreateRetryTaskFreshensCodexSemanticInactivity(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ ctx := context.Background()++ var parentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ started_at, completed_at, session_id, work_dir, failure_reason,+ attempt, max_attempts+ )+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute',+ 'CODEX-STUCK-SESSION', '/tmp/codex-stuck', 'codex_semantic_inactivity', 1, 2)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&parentID); err != nil {+ t.Fatalf("insert codex semantic inactivity parent task: %v", err)+ }++ queries := db.New(testPool)+ child, err := queries.CreateRetryTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true})+ if err != nil {+ t.Fatalf("CreateRetryTask failed: %v", err)+ }+ if child.SessionID.Valid {+ t.Fatalf("expected retry child to drop poisoned session_id, got %q", child.SessionID.String)+ }+ if child.WorkDir.Valid {+ t.Fatalf("expected retry child to drop poisoned work_dir, got %q", child.WorkDir.String)+ }+ if !child.ForceFreshSession {+ t.Fatal("expected retry child to force a fresh session")+ }+ if child.Attempt != 2 {+ t.Fatalf("expected attempt 2, got %d", child.Attempt)+ }+}++func TestCreateRetryTaskKeepsOrdinaryTimeoutSession(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ ctx := context.Background()++ var parentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ started_at, completed_at, session_id, work_dir, failure_reason,+ attempt, max_attempts+ )+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute',+ 'ORDINARY-TIMEOUT-SESSION', '/tmp/ordinary-timeout', 'timeout', 1, 2)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&parentID); err != nil {+ t.Fatalf("insert ordinary timeout parent task: %v", err)+ }++ queries := db.New(testPool)+ child, err := queries.CreateRetryTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true})+ if err != nil {+ t.Fatalf("CreateRetryTask failed: %v", err)+ }+ if !child.SessionID.Valid || child.SessionID.String != "ORDINARY-TIMEOUT-SESSION" {+ t.Fatalf("expected retry child to inherit session_id, got %+v", child.SessionID)+ }+ if !child.WorkDir.Valid || child.WorkDir.String != "/tmp/ordinary-timeout" {+ t.Fatalf("expected retry child to inherit work_dir, got %+v", child.WorkDir)+ }+ if child.ForceFreshSession {+ t.Fatal("expected ordinary timeout retry child to keep resume enabled")+ }+ if child.Attempt != 2 {+ t.Fatalf("expected attempt 2, got %d", child.Attempt)+ }+}+// TestGetLastTaskSessionExcludesLegacyAPI400 is the MUL-1921 legacy// regression: pre-fix rows are tagged failure_reason='agent_error' even// though their error text contains the canonical Anthropic 400diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex e58a56220a..76a15c5bf8 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2666,13 +2666,20 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif comment == "" {comment = fmt.Sprintf("%s timed out after %s", provider, d.cfg.AgentTimeout)}+ failureReason := "timeout"+ if reason, ok := classifyResumeUnsafeTimeout(provider, comment); ok {+ taskLog.Warn("agent timed out with resume-unsafe session, classifying as blocked",+ "failure_reason", reason,+ )+ failureReason = reason+ }return TaskResult{Status: "blocked",Comment: comment,SessionID: result.SessionID,WorkDir: env.WorkDir,EnvRoot: env.RootDir,- FailureReason: "timeout",+ FailureReason: failureReason,Usage: usageEntries,}, nilcase "idle_watchdog":diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex 974f122c4a..459229a343 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -1,6 +1,10 @@package daemon-import "strings"+import (+ "strings"++ "github.com/multica-ai/multica/server/pkg/agent"+)// FailureReason values for tasks whose session is "poisoned" — i.e.// resuming the same conversation on a follow-up task would deterministically@@ -16,10 +20,15 @@ import "strings"// invalid_request_error (oversized payload, malformed image, etc.).// The bad message is already baked into the conversation history, so// every resume hits the same 400. Detected via classifyPoisonedError.+// - Timeout-side: Codex reported semantic inactivity after the session got+// stuck without agent progress. Resuming that Codex session can replay the+// same stuck state, while a fresh manual rerun may succeed. Detected via+// classifyResumeUnsafeTimeout.const (- FailureReasonIterationLimit = "iteration_limit"- FailureReasonAgentFallbackMsg = "agent_fallback_message"- FailureReasonAPIInvalidRequest = "api_invalid_request"+ FailureReasonIterationLimit = "iteration_limit"+ FailureReasonAgentFallbackMsg = "agent_fallback_message"+ FailureReasonAPIInvalidRequest = "api_invalid_request"+ FailureReasonCodexSemanticInactivity = "codex_semantic_inactivity")// poisonedOutputMaxLen caps how long an output can be and still be@@ -98,3 +107,17 @@ func classifyPoisonedError(errMsg string) (string, bool) {}return "", false}++// classifyResumeUnsafeTimeout reports whether a timeout means the recorded+// session should not be resumed. Keep this intentionally provider-specific:+// ordinary daemon/backend timeouts are infrastructure-shaped and should keep+// the resume pointer so retries can continue the in-flight conversation.+func classifyResumeUnsafeTimeout(provider, errMsg string) (string, bool) {+ if strings.ToLower(strings.TrimSpace(provider)) != "codex" || errMsg == "" {+ return "", false+ }+ if strings.Contains(strings.ToLower(errMsg), strings.ToLower(agent.CodexSemanticInactivityMarker)) {+ return FailureReasonCodexSemanticInactivity, true+ }+ return "", false+}diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex 805f1147e8..a4800c470f 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -3,6 +3,8 @@ package daemonimport ("strings""testing"++ "github.com/multica-ai/multica/server/pkg/agent")func TestClassifyPoisonedOutput(t *testing.T) {@@ -59,10 +61,10 @@ Detection markers under consideration:The implementation looks correct: the daemon classifies these asfallback output, persists a dedicated failure_reason, and the SQL-filter excludes them from the resume lookup. Auto-retry of mid-flight-orphans still keeps the resume contract because CreateRetryTask does-not set force_fresh_session. Approving with a follow-up note about-the matcher being too permissive on long outputs.`,+filter excludes them from the resume lookup. Resume-safe auto-retry+still keeps the resume contract, while poisoned sessions are filtered.+Approving with a follow-up note about the matcher being too permissive+on long outputs.`,wantOK: false,},{@@ -169,3 +171,51 @@ func TestClassifyPoisonedError(t *testing.T) {})}}++func TestClassifyResumeUnsafeTimeout(t *testing.T) {+ cases := []struct {+ name string+ provider string+ errMsg string+ wantOK bool+ wantReason string+ }{+ {+ name: "codex semantic inactivity",+ provider: "codex",+ errMsg: agent.CodexSemanticInactivityMarker + " after 10m0s without agent progress (last activity: tool-result:exec_command)",+ wantOK: true,+ wantReason: FailureReasonCodexSemanticInactivity,+ },+ {+ name: "codex ordinary timeout remains resumable",+ provider: "codex",+ errMsg: "codex timed out after 30m0s",+ wantOK: false,+ },+ {+ name: "other provider same text is not classified",+ provider: "claude",+ errMsg: agent.CodexSemanticInactivityMarker + " after 10m0s without agent progress",+ wantOK: false,+ },+ {+ name: "empty error",+ provider: "codex",+ errMsg: "",+ wantOK: false,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ reason, ok := classifyResumeUnsafeTimeout(tc.provider, tc.errMsg)+ if ok != tc.wantOK {+ t.Fatalf("classifyResumeUnsafeTimeout(%q, %q) ok=%v, want %v", tc.provider, tc.errMsg, ok, tc.wantOK)+ }+ if ok && reason != tc.wantReason {+ t.Fatalf("classifyResumeUnsafeTimeout(%q, %q) reason=%q, want %q", tc.provider, tc.errMsg, reason, tc.wantReason)+ }+ })+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex eb100a0c25..4e8f52e312 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1326,26 +1326,28 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {resp.Repos = repos}}- // Resume chat sessions only when the stored pointer was produced- // by the same runtime as the claiming task. When the chat_session- // pointer is missing (legacy NULL runtime_id), stale (last task- // failed before reporting completion), or runtime-mismatched, fall- // back to the most recent task row that recorded a session_id —- // otherwise a single failed turn would silently drop the entire- // conversation memory on the next message. The fallback also- // requires runtime to match.- if cs.SessionID.Valid && cs.RuntimeID.Valid && cs.RuntimeID == task.RuntimeID {- resp.PriorSessionID = cs.SessionID.String- }- if cs.WorkDir.Valid {- resp.PriorWorkDir = cs.WorkDir.String- }- if prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID); err == nil && prior.SessionID.Valid {- if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {- resp.PriorSessionID = prior.SessionID.String+ if !task.ForceFreshSession {+ // Resume chat sessions only when the stored pointer was produced+ // by the same runtime as the claiming task. When the chat_session+ // pointer is missing (legacy NULL runtime_id), stale (last task+ // failed before reporting completion), or runtime-mismatched, fall+ // back to the most recent task row that recorded a session_id —+ // otherwise a single failed turn would silently drop the entire+ // conversation memory on the next message. The fallback also+ // requires runtime to match.+ if cs.SessionID.Valid && cs.RuntimeID.Valid && cs.RuntimeID == task.RuntimeID {+ resp.PriorSessionID = cs.SessionID.String}- if prior.WorkDir.Valid && resp.PriorWorkDir == "" {- resp.PriorWorkDir = prior.WorkDir.String+ if cs.WorkDir.Valid {+ resp.PriorWorkDir = cs.WorkDir.String+ }+ if prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID); err == nil && prior.SessionID.Valid {+ if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {+ resp.PriorSessionID = prior.SessionID.String+ }+ if prior.WorkDir.Valid && resp.PriorWorkDir == "" {+ resp.PriorWorkDir = prior.WorkDir.String+ }}}// Load the latest user message for the chat prompt, plus anydiff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex fffad780c4..746faf003b 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -2532,6 +2532,57 @@ func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {}}+func TestClaimTask_ChatForceFreshSessionSkipsPriorSession(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()++ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)++ var chatSessionID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO chat_session (+ workspace_id, agent_id, creator_id, title,+ session_id, work_dir, runtime_id+ )+ VALUES ($1, $2, $3, 'force fresh chat', 'chat-pointer-session', '/tmp/chat-pointer-workdir', $4)+ RETURNING id+ `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {+ t.Fatalf("setup: create chat session: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, chat_session_id,+ status, priority, started_at, completed_at,+ session_id, work_dir+ )+ VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'task-row-session', '/tmp/task-row-workdir')+ `, agentID, runtimeID, chatSessionID); err != nil {+ t.Fatalf("setup: create prior chat task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, chat_session_id,+ status, priority, force_fresh_session+ )+ VALUES ($1, $2, $3, 'queued', 0, TRUE)+ `, agentID, runtimeID, chatSessionID); err != nil {+ t.Fatalf("setup: create force-fresh chat task: %v", err)+ }++ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.PriorSessionID != "" {+ t.Fatalf("force fresh chat: expected empty PriorSessionID, got %q", task.PriorSessionID)+ }+ if task.PriorWorkDir != "" {+ t.Fatalf("force fresh chat: expected empty PriorWorkDir, got %q", task.PriorWorkDir)+ }+}+// Locks the legacy-row fallback: chat_session.runtime_id IS NULL (e.g. a row// the migration left untouched because no prior task matched the cs pointer)// but a completed task on the claiming runtime exists. ClaimTaskByRuntimediff --git a/server/internal/middleware/cloudfront_test.go b/server/internal/middleware/cloudfront_test.goindex 060713f1f8..f48bd2afa2 100644--- a/server/internal/middleware/cloudfront_test.go+++ b/server/internal/middleware/cloudfront_test.go@@ -31,6 +31,7 @@ func testSigner(t *testing.T) *auth.CloudFrontSigner {t.Setenv("CLOUDFRONT_KEY_PAIR_ID", "TESTKEY")t.Setenv("CLOUDFRONT_DOMAIN", "cdn.example.com")t.Setenv("COOKIE_DOMAIN", ".example.com")+ t.Setenv("CLOUDFRONT_PRIVATE_KEY_SECRET", "")t.Setenv("CLOUDFRONT_PRIVATE_KEY", b64Key)signer := auth.NewCloudFrontSignerFromEnv()diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex f8cc284bca..f28d152f31 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -345,7 +345,7 @@ func taskErrorType(reason string) string {switch reason {case "runtime_offline", "runtime_recovery":return "runtime"- case "timeout":+ case "timeout", "codex_semantic_inactivity":return "timeout"case "iteration_limit", "agent_fallback_message":return "agent_output"@@ -1126,7 +1126,9 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,}task = t- if t.ChatSessionID.Valid {+ // Keep resume-unsafe sessions on the task row for observability, but+ // do not promote them to the chat-level resume pointer.+ if t.ChatSessionID.Valid && !resumeUnsafeFailureReason(failureReason) {// Pin the chat_session's runtime_id alongside the session_id so the// next claim can apply the runtime-guard. Both fields move together:// when there's no session_id to record, leave runtime_id untouched@@ -1236,18 +1238,30 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,// etc.) are intentionally excluded — those are real problems that the user// should see, not infrastructure flakiness.var retryableReasons = map[string]bool{- "runtime_offline": true,- "runtime_recovery": true,- "timeout": true,+ "runtime_offline": true,+ "runtime_recovery": true,+ "timeout": true,+ "codex_semantic_inactivity": true,+}++func resumeUnsafeFailureReason(reason string) bool {+ switch reason {+ // Keep in sync with GetLastTaskSession / GetLastChatTaskSession and+ // CreateRetryTask's fresh-session CASE WHEN.+ case "iteration_limit", "agent_fallback_message", "api_invalid_request", "codex_semantic_inactivity":+ return true+ default:+ return false+ }}// MaybeRetryFailedTask spawns a fresh queued attempt for a recently-failed// task when the failure was infrastructure-shaped (daemon crash, runtime// went offline, dispatch/run timeout) and the task hasn't exhausted its// max_attempts budget. The child task inherits agent/runtime/issue/chat-// links and the parent's session_id/work_dir so the agent can resume the-// conversation when the backend supports it. Returns the new task, or nil-// when no retry was created.+// links and, for resume-safe failures, the parent's session_id/work_dir so+// the agent can resume the conversation when the backend supports it. Returns+// the new task, or nil when no retry was created.//// Autopilot tasks are NOT auto-retried here; the autopilot scheduler owns// its own re-run cadence and we don't want to double-fire it.diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.goindex dd9dd56b9a..2c6bc22bd1 100644--- a/server/internal/service/task_complete_race_test.go+++ b/server/internal/service/task_complete_race_test.go@@ -166,3 +166,33 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {})}}++func TestTaskFailureClassifiers(t *testing.T) {+ cases := []struct {+ reason string+ wantType string+ wantResumeOK bool+ wantRetry bool+ }{+ {reason: "timeout", wantType: "timeout", wantResumeOK: true, wantRetry: true},+ {reason: "codex_semantic_inactivity", wantType: "timeout", wantResumeOK: false, wantRetry: true},+ {reason: "runtime_recovery", wantType: "runtime", wantResumeOK: true, wantRetry: true},+ {reason: "iteration_limit", wantType: "agent_output", wantResumeOK: false, wantRetry: false},+ {reason: "api_invalid_request", wantType: "agent_error", wantResumeOK: false, wantRetry: false},+ {reason: "agent_error", wantType: "agent_error", wantResumeOK: true, wantRetry: false},+ }++ for _, tc := range cases {+ t.Run(tc.reason, func(t *testing.T) {+ if got := taskErrorType(tc.reason); got != tc.wantType {+ t.Fatalf("taskErrorType(%q) = %q, want %q", tc.reason, got, tc.wantType)+ }+ if got := !resumeUnsafeFailureReason(tc.reason); got != tc.wantResumeOK {+ t.Fatalf("resume-safe(%q) = %v, want %v", tc.reason, got, tc.wantResumeOK)+ }+ if got := retryableReasons[tc.reason]; got != tc.wantRetry {+ t.Fatalf("retryableReasons[%q] = %v, want %v", tc.reason, got, tc.wantRetry)+ }+ })+ }+}diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex a20e8d277f..d8bb283aa1 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -30,6 +30,10 @@ const (defaultCodexSemanticInactivityTimeout = 10 * time.Minute)+// CodexSemanticInactivityMarker prefixes timeout errors emitted when Codex+// stops making semantic progress while the process is still alive.+const CodexSemanticInactivityMarker = "codex semantic inactivity timeout"+// codexBackend implements Backend by spawning `codex app-server --listen stdio://`// and communicating via JSON-RPC 2.0 over stdin/stdout.type codexBackend struct {@@ -262,8 +266,8 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpticase <-semanticTimer.C:waitingForTurn = falsefinalStatus = "timeout"- finalError = fmt.Sprintf("codex semantic inactivity timeout after %s without agent progress (last activity: %s)", semanticInactivityTimeout, lastSemanticActivityDescription)- b.cfg.Logger.Warn("codex semantic inactivity timeout",+ finalError = fmt.Sprintf("%s after %s without agent progress (last activity: %s)", CodexSemanticInactivityMarker, semanticInactivityTimeout, lastSemanticActivityDescription)+ b.cfg.Logger.Warn(CodexSemanticInactivityMarker,"pid", cmd.Process.Pid,"thread_id", threadID,"turn_id", c.turnID,diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 789601ffaa..63d75e537f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -857,13 +857,16 @@ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,- attempt, max_attempts, parent_task_id, is_leader_task+ attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,- p.session_id, p.work_dir,- p.attempt + 1, p.max_attempts, p.id, p.is_leader_task+ CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,+ CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,+ p.attempt + 1, p.max_attempts, p.id,+ p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',+ p.is_leader_taskFROM agent_task_queue pWHERE p.id = $1RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task@@ -871,11 +874,14 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c// Clones a parent task into a fresh queued attempt. Carries forward the// agent's resume context (session_id/work_dir) so the child can continue-// the conversation when the backend supports it. attempt is incremented;-// max_attempts, trigger_comment_id, and is_leader_task are inherited so-// the retried task keeps the same squad-role provenance as its parent and-// the self-trigger guard in shouldEnqueueSquadLeaderOnComment continues to-// recognise it as a leader task.+// the conversation when the backend supports it. Resume-unsafe failures are+// retried as fresh sessions so the child does not inherit a stuck agent+// conversation. Keep the CASE WHEN predicates in sync with+// resumeUnsafeFailureReason and the resume lookup blacklists. attempt is+// incremented; max_attempts, trigger_comment_id, and is_leader_task are+// inherited so the retried task keeps the same squad-role provenance as its+// parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment+// continues to recognise it as a leader task.func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createRetryTask, id)var i AgentTaskQueue@@ -1255,7 +1261,7 @@ WHERE agent_id = $1 AND issue_id = $2status = 'completed'OR (status = 'failed'- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request')+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')))@@ -1293,9 +1299,11 @@ type GetLastTaskSessionRow struct {// Tasks that ended in a known "poisoned" terminal state are also excluded// here so even auto-retry does not inherit the bad session. The daemon// classifies these failures (iteration_limit, agent_fallback_message,-// api_invalid_request) when it detects either an agent fallback marker in-// the output or an upstream API 400 that means the conversation history-// itself is unprocessable (oversized image, malformed base64, etc.).+// api_invalid_request, codex_semantic_inactivity) when it detects either an+// agent fallback marker in the output, an upstream API 400 that means the+// conversation history itself is unprocessable (oversized image, malformed+// base64, etc.), or a Codex semantic inactivity timeout whose recorded+// session may replay the same stuck state.//// The error-text ILIKE clause is defense-in-depth for the api_invalid_request// shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-windowdiff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex e8250e07ed..7eaea56b99 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -233,7 +233,14 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSessconst getLastChatTaskSession = `-- name: GetLastChatTaskSession :oneSELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE chat_session_id = $1- AND status IN ('completed', 'failed')+ AND (+ status = 'completed'+ OR (+ status = 'failed'+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')+ AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')+ )+ )AND session_id IS NOT NULLORDER BY completed_at DESCLIMIT 1@@ -249,7 +256,9 @@ type GetLastChatTaskSessionRow struct {// session_id. Includes both completed and failed tasks: even a failed task// may have established a real agent session before failing, and we'd rather// resume there than start over and lose conversation memory. Used as a-// fallback when chat_session.session_id is NULL.+// fallback when chat_session.session_id is NULL. Resume-unsafe failures are+// excluded because replaying those sessions deterministically reproduces the+// same terminal state.func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)var i GetLastChatTaskSessionRowdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 70eac70e42..1b566a8535 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -117,22 +117,28 @@ WHERE id = $1 AND issue_id IS NULL;-- name: CreateRetryTask :one-- Clones a parent task into a fresh queued attempt. Carries forward the-- agent's resume context (session_id/work_dir) so the child can continue--- the conversation when the backend supports it. attempt is incremented;--- max_attempts, trigger_comment_id, and is_leader_task are inherited so--- the retried task keeps the same squad-role provenance as its parent and--- the self-trigger guard in shouldEnqueueSquadLeaderOnComment continues to--- recognise it as a leader task.+-- the conversation when the backend supports it. Resume-unsafe failures are+-- retried as fresh sessions so the child does not inherit a stuck agent+-- conversation. Keep the CASE WHEN predicates in sync with+-- resumeUnsafeFailureReason and the resume lookup blacklists. attempt is+-- incremented; max_attempts, trigger_comment_id, and is_leader_task are+-- inherited so the retried task keeps the same squad-role provenance as its+-- parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment+-- continues to recognise it as a leader task.INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,- attempt, max_attempts, parent_task_id, is_leader_task+ attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,- p.session_id, p.work_dir,- p.attempt + 1, p.max_attempts, p.id, p.is_leader_task+ CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,+ CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,+ p.attempt + 1, p.max_attempts, p.id,+ p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',+ p.is_leader_taskFROM agent_task_queue pWHERE p.id = $1RETURNING *;@@ -264,9 +270,11 @@ RETURNING *;-- Tasks that ended in a known "poisoned" terminal state are also excluded-- here so even auto-retry does not inherit the bad session. The daemon-- classifies these failures (iteration_limit, agent_fallback_message,--- api_invalid_request) when it detects either an agent fallback marker in--- the output or an upstream API 400 that means the conversation history--- itself is unprocessable (oversized image, malformed base64, etc.).+-- api_invalid_request, codex_semantic_inactivity) when it detects either an+-- agent fallback marker in the output, an upstream API 400 that means the+-- conversation history itself is unprocessable (oversized image, malformed+-- base64, etc.), or a Codex semantic inactivity timeout whose recorded+-- session may replay the same stuck state.---- The error-text ILIKE clause is defense-in-depth for the api_invalid_request-- shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-window@@ -282,7 +290,7 @@ WHERE agent_id = $1 AND issue_id = $2status = 'completed'OR (status = 'failed'- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request')+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')))diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex c30c70ed4f..9a86a3d220 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -96,10 +96,19 @@ RETURNING *;-- session_id. Includes both completed and failed tasks: even a failed task-- may have established a real agent session before failing, and we'd rather-- resume there than start over and lose conversation memory. Used as a--- fallback when chat_session.session_id is NULL.+-- fallback when chat_session.session_id is NULL. Resume-unsafe failures are+-- excluded because replaying those sessions deterministically reproduces the+-- same terminal state.SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE chat_session_id = $1- AND status IN ('completed', 'failed')+ AND (+ status = 'completed'+ OR (+ status = 'failed'+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')+ AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')+ )+ )AND session_id IS NOT NULLORDER BY completed_at DESCLIMIT 1;