Skip to content

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

Go

fix(agent): recover from a codex resume that overflows the reader (MUL-5722) (#6420)

Bohan Jiangc896f677d505
diff --git a/packages/core/dashboard/failure-class.test.ts b/packages/core/dashboard/failure-class.test.ts
index e647ee4268..1b47720b9c 100644
--- a/packages/core/dashboard/failure-class.test.ts
+++ b/packages/core/dashboard/failure-class.test.ts
@@ -19,6 +19,10 @@ describe("failureClassOf", () => {
// with the substrate failures an operator fixes by checking the daemon.
expect(failureClassOf("skill_bundle_unavailable")).toBe("runtime");
expect(failureClassOf("agent_error.process_failure")).toBe("agent");
+ // MUL-5722: the daemon and the provider are both healthy — codex could
+ // not hand its own stored thread back — so this reads as an agent-side
+ // failure, not a runtime one.
+ expect(failureClassOf("codex_resume_oversized")).toBe("agent");
});
it("keeps pre-MUL-1949 coarse reasons countable", () => {
diff --git a/packages/core/dashboard/failure-class.ts b/packages/core/dashboard/failure-class.ts
index 31ea676179..0bea6ac546 100644
--- a/packages/core/dashboard/failure-class.ts
+++ b/packages/core/dashboard/failure-class.ts
@@ -68,6 +68,10 @@ const REASON_CLASS: Record<string, FailureClass> = {
// The agent process itself produced the failure.
"agent_error.process_failure": "agent",
+ // Codex could not hand its stored thread back within our transport limits.
+ // "agent" rather than "runtime": the daemon is healthy and the provider is
+ // fine — it is this backend's own resume path that could not complete.
+ codex_resume_oversized: "agent",
"agent_error.empty_or_unparseable_output": "agent",
"agent_error.context_overflow": "agent",
iteration_limit: "agent",
diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.ts
index 1e8ceb8f4b..6d3850a045 100644
--- a/packages/views/agents/components/tabs/task-failure.ts
+++ b/packages/views/agents/components/tabs/task-failure.ts
@@ -43,6 +43,9 @@ const REASON_LABEL: Record<string, string> = {
"agent_error.runtime_missing_executable": "Runner CLI not installed",
"agent_error.unknown": "Agent execution error",
+ // Provider-specific operational reasons, outside the canonical taxonomy.
+ codex_resume_oversized: "Session too large to resume",
+
// Pre-MUL-1949 coarse values, still present on historical rows.
agent_error: "Agent execution error",
codex_semantic_inactivity: "Codex semantic inactivity timeout",
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index ebbcae8a10..47974d072f 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -1138,3 +1138,139 @@ func TestGetLastTaskSessionKeepsDimensionPhraseWithoutImageMarker(t *testing.T)
t.Fatalf("expected the dimension-phrase-only session to stay resumable, got %q (valid=%v)", prior.SessionID.String, prior.SessionID.Valid)
}
}
+
+// TestGetLastTaskSessionExcludesOverflowedResumeFromOlderCompletedRow is the
+// MUL-5722 topology, and the one the first attempt at the fix got wrong.
+//
+// A codex thread/resume that overflows the reader fails BEFORE any turn runs,
+// so the backend has no session id to report and the failed row lands with
+// session_id NULL. The thread it could not read is only named by the OLDER
+// completed row. That means a row-level error-text filter on the failed row can
+// never fire — `session_id IS NOT NULL` drops the row before any filter sees
+// it — and the lookup happily returns the same oversized thread again.
+//
+// This is the shape every already-stuck issue is in right now, and the shape a
+// daemon too old to classify the failure keeps producing, so the block has to
+// key off the failure being newer than the candidate rather than off the failed
+// row carrying the session.
+func TestGetLastTaskSessionExcludesOverflowedResumeFromOlderCompletedRow(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()
+
+ // The turn that grew the thread past the reader's cap. Perfectly healthy
+ // looking: it completed, and it is the only row naming the thread.
+ 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)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '2 minutes', now() - interval '2 minutes', 'THR-OVERSIZED', '/tmp/codex')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert completed task: %v", err)
+ }
+
+ // The next turn resumed it and could not read the response back. No session
+ // id, and the pre-fix daemon classifies it as the resume-SAFE
+ // agent_error.process_failure — so only the error text identifies it.
+ 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', NULL, '/tmp/codex', 'agent_error.process_failure',
+ 'codex thread/resume failed: codex process exited: bufio.Scanner: token too long')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert overflow failed 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},
+ })
+ requireSessionExcluded(t, prior.SessionID, err)
+}
+
+// TestGetLastTaskSessionResumesAgainAfterOverflowRecovery is the other half of
+// the time-based block above: it must expire, not latch. Once a fresh thread
+// terminates after the overflow, that thread is resumable again — otherwise
+// every later turn on the issue would start cold forever, trading a permanent
+// stall for permanent amnesia.
+func TestGetLastTaskSessionResumesAgainAfterOverflowRecovery(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)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '3 minutes', now() - interval '3 minutes', 'THR-OVERSIZED', '/tmp/codex')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert completed 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 '2 minutes', now() - interval '2 minutes', NULL, '/tmp/codex', 'agent_error.process_failure',
+ 'codex thread/resume failed: codex process exited: bufio.Scanner: token too long')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert overflow failed task: %v", err)
+ }
+ // The fresh-session retry that recovered the turn.
+ 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)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', 'THR-FRESH', '/tmp/codex')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert recovered 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 != "THR-FRESH" {
+ t.Fatalf("expected the post-overflow thread THR-FRESH, got %q", prior.SessionID.String)
+ }
+}
+
+// TestGetLastTaskSessionExcludesOverflowRetiredSession covers the path a
+// current daemon takes: it names the thread it could not read via
+// retired_session_id, so the block does not have to rely on timing at all.
+func TestGetLastTaskSessionExcludesOverflowRetiredSession(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)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '2 minutes', now() - interval '2 minutes', 'THR-OVERSIZED', '/tmp/codex')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert completed 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, retired_session_id)
+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute', NULL, '/tmp/codex', 'codex_resume_oversized',
+ 'codex thread/resume failed: codex process exited: bufio.Scanner: token too long', 'THR-OVERSIZED')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert overflow failed 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},
+ })
+ requireSessionExcluded(t, prior.SessionID, err)
+}
diff --git a/server/cmd/server/retired_session_test.go b/server/cmd/server/retired_session_test.go
index 3065b4cdfe..3a80029e5b 100644
--- a/server/cmd/server/retired_session_test.go
+++ b/server/cmd/server/retired_session_test.go
@@ -261,3 +261,41 @@ func TestFailTaskKeepsChatPointerOnTransientFailure(t *testing.T) {
t.Fatal("a transient failure must keep the chat resume pointer")
}
}
+
+// TestGetLastChatTaskSessionExcludesOverflowedResumeFromOlderCompletedRow is
+// the chat half of the MUL-5722 topology. Same shape as the issue side: the
+// overflowed resume records no session, so only the older completed row names
+// the oversized thread.
+//
+// Scope worth stating: this only guards the FALLBACK query. The claim handler
+// reads chat_session.session_id first, so a pointer still naming the oversized
+// thread shadows everything asserted here — clearing that pointer at fail time
+// is what covers the rest, and for a daemon too old to report the failure it is
+// still open (see the PR notes).
+func TestGetLastChatTaskSessionExcludesOverflowedResumeFromOlderCompletedRow(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "overflow-resume")
+ ctx := context.Background()
+
+ 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() - interval '2 minutes', now() - interval '2 minutes', 'THR-CHAT-OVERSIZED', '/tmp/chat')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert completed task: %v", err)
+ }
+ 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, failure_reason, error)
+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute', NULL, '/tmp/chat', 'agent_error.process_failure',
+ 'codex thread/resume failed: codex process exited: bufio.Scanner: token too long')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert overflow failed task: %v", err)
+ }
+
+ queries := db.New(testPool)
+ prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ requireSessionExcluded(t, prior.SessionID, err)
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f4669bed1d..3808d53453 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5391,19 +5391,26 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
HandshakeTimeout: d.cfg.CodexHandshakeTimeout,
ResumeSessionID: task.PriorSessionID,
// Post-gate intent: PriorSessionID here already reflects the pre-flight
- // resume gates (a dropped resume is surfaced via the brief instead). If it
- // survived to here, the backend must disclose to the user when the live
+ // resume gates (a dropped resume is surfaced via the prompt instead). If it
+ // survived to here, the backend must disclose the loss when the live
// resume still fails — even across the fresh-session retry below, which
// clears ResumeSessionID but not this (MUL-4424).
- ResumeExpected: task.PriorSessionID != "",
- ExtraArgs: extraArgs,
- CustomArgs: customArgs,
- McpConfig: mcpConfig,
- ThinkingLevel: thinkingLevel,
- ServiceTier: serviceTier,
- OpenclawMode: openclawMode,
- ClaudeSettingsPath: env.ClaudeSettingsPath,
- QwenpawWorkspace: env.QwenpawWorkspace,
+ //
+ // What that disclosure SAYS, and whether it addresses the user at all,
+ // depends on whether this surface's conversation is still readable, which
+ // only the daemon knows — hence handing the backend finished text rather
+ // than a flag. Empty when the prompt already carries the notice, so a turn
+ // can never pay for it twice (MUL-5722).
+ ResumeExpected: task.PriorSessionID != "",
+ ResumeContinuityNotice: backendResumeContinuityNotice(task),
+ ExtraArgs: extraArgs,
+ CustomArgs: customArgs,
+ McpConfig: mcpConfig,
+ ThinkingLevel: thinkingLevel,
+ ServiceTier: serviceTier,
+ OpenclawMode: openclawMode,
+ ClaudeSettingsPath: env.ClaudeSettingsPath,
+ QwenpawWorkspace: env.QwenpawWorkspace,
}
// Some providers do not reliably load the per-task runtime config files we
// write into the task workdir:
@@ -5493,13 +5500,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// like Kiro load themselves).
// - clearing task.PriorSessionID rebuilds the prompt on the cold
// comment-reading path instead of the warm resumed one.
- // The current user prompt is preserved and prefixed with an explicit
- // context-loss disclosure so the agent re-reads the issue/thread
- // instead of assuming continuity it no longer has.
+ // - PriorSessionResumeUnavailable=true makes BuildPrompt append the
+ // continuity notice for this surface, so the agent knows not to
+ // assume continuity it no longer has. This is now the ONLY injector
+ // on the retry path: the backend's own copy is suppressed below,
+ // because before MUL-5722 both fired and the turn carried the same
+ // paragraph twice.
// task and taskCtx are local (runTask takes task by value), so these
// mutations only affect the retry.
execOpts.ResumeSessionID = ""
task.PriorSessionID = ""
+ task.PriorSessionResumeUnavailable = true
+ execOpts.ResumeContinuityNotice = ""
taskCtx.PriorSessionResumed = false
if freshBrief, briefErr := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx); briefErr != nil {
taskLog.Warn("execenv: re-inject cold runtime config for fresh retry failed (non-fatal)", "error", briefErr)
@@ -5509,7 +5521,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
execOpts.SystemPrompt = runtimeBrief
}
}
- freshPrompt := freshSessionRetryPrompt(BuildPrompt(task, provider))
+ freshPrompt := BuildPrompt(task, provider)
retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
if retryErr != nil {
@@ -5705,8 +5717,35 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// conversation permanently blocks the issue: every follow-up
// task resumes the same poisoned session and hits the same 400.
failureReason, _ := classifyPoisonedError(errMsg)
+ if failureReason == "" {
+ // A resume we could not read back leaves the same oversized thread
+ // recorded as this issue's resume pointer. Reaching here means the
+ // in-turn fresh-session retry did not save the run (it is gated on
+ // tools == 0, and can fail on its own), so classify it to keep the
+ // NEXT task off that thread rather than replaying the overflow
+ // forever (MUL-5722).
+ failureReason, _ = classifyResumeUnsafeTransport(provider, errMsg)
+ if failureReason != "" && retiredSessionID == "" && task.PriorSessionID != "" {
+ // Name the thread explicitly. The failure happens before the
+ // turn starts, so the backend has no session id to report and
+ // this row lands with session_id NULL — which means neither
+ // the reason above nor any error-text filter on this row can
+ // identify WHICH session to avoid. retired_session_id is the
+ // one channel that does not depend on the failed row carrying
+ // the session, and it is what the resume lookups and the chat
+ // pointer cleanup both key off.
+ //
+ // Belt-and-braces, not the live path: an overflowed resume
+ // fails before any tool runs, so shouldRetryWithFreshSession's
+ // tools == 0 gate is always satisfied and the retry above has
+ // already recorded the same id. This covers the case where a
+ // future condition stops the retry from firing, so the session
+ // is still retired rather than silently kept.
+ retiredSessionID = task.PriorSessionID
+ }
+ }
if failureReason != "" {
- taskLog.Warn("agent failed with poisoned API error, classifying as blocked",
+ taskLog.Warn("agent failed with a resume-unsafe error, retiring the session",
"failure_reason", failureReason,
)
} else {
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index e7cff787c8..b5c7ec5dba 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -751,37 +751,127 @@ func TestBuildPromptContainsIssueID(t *testing.T) {
}
}
-// TestFreshSessionRetryPrompt asserts the daemon's single fresh-session retry
-// preserves the current prompt verbatim and prefixes an explicit context-loss
-// disclosure (GH #5975), so the new provider session does not assume continuity
-// with the conversation that could not be resumed.
-func TestFreshSessionRetryPrompt(t *testing.T) {
+// TestSessionContinuityNoticeMatchesSurface locks the MUL-5722 split. The same
+// event costs each surface something different, so it cannot be reported with
+// one sentence. The dividing question is whether the conversation can still be
+// READ, not whether it is a chat: an issue's comments and a Slack channel's
+// history both can, a web chat's and a Feishu channel's cannot. Announcing a
+// loss on the first two describes something that did not happen — the user
+// hears "the discussion is gone" when every word survives.
+func TestSessionContinuityNoticeMatchesSurface(t *testing.T) {
t.Parallel()
- base := BuildPrompt(Task{
- IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
- TriggerCommentID: "c0ffee00-0000-0000-0000-000000000000",
- Agent: &AgentData{Name: "Local Kiro"},
- }, "kiro")
+ cases := []struct {
+ name string
+ task Task
+ tellUser bool
+ wantMentions string
+ }{
+ {
+ name: "issue rebuilds from comments",
+ task: Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"},
+ tellUser: false,
+ wantMentions: "comment history",
+ },
+ {
+ // Slack has a history reader, so the conversation is recoverable —
+ // just from the channel rather than from Multica. Telling the user it
+ // was lost contradicts the commands the same prompt hands the agent.
+ name: "slack rebuilds from the channel",
+ task: Task{ChatSessionID: "chat-1", ChatChannelType: execenv.ChannelTypeSlack},
+ tellUser: false,
+ wantMentions: "multica chat history",
+ },
+ {
+ // Web chat history lived only in the provider session.
+ name: "web chat is unrecoverable",
+ task: Task{ChatSessionID: "chat-1"},
+ tellUser: true,
+ wantMentions: "not readable from anywhere",
+ },
+ {
+ // Multica ships no history reader for Feishu, so despite being a
+ // channel it is in the same position as a web chat.
+ name: "feishu has no history reader",
+ task: Task{ChatSessionID: "chat-1", ChatChannelType: execenv.ChannelTypeFeishu},
+ tellUser: true,
+ wantMentions: "not readable from anywhere",
+ },
+ }
- got := freshSessionRetryPrompt(base)
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ notice := sessionContinuityNoticeFor(tc.task)
+ if got := strings.Contains(notice, "tell the user up front"); got != tc.tellUser {
+ t.Errorf("tells the user = %v, want %v:\n%s", got, tc.tellUser, notice)
+ }
+ if !strings.Contains(notice, tc.wantMentions) {
+ t.Errorf("notice missing %q, so the agent is not told where to rebuild from:\n%s", tc.wantMentions, notice)
+ }
+ // Where the conversation survives, the ONLY loss is the agent's
+ // unrecorded working memory, and it has to be told so or it assumes
+ // it still remembers work it no longer has. Where nothing survives
+ // that distinction is meaningless — everything is gone — so the
+ // requirement applies to the recoverable surfaces only.
+ if !tc.tellUser && !strings.Contains(notice, "your own working memory") {
+ t.Errorf("recoverable surface must name the real loss:\n%s", notice)
+ }
+ })
+ }
- // The disclosure must come first and clearly signal a brand-new session
- // with no prior provider context.
- for _, want := range []string{
- "brand-new session",
- "could not be resumed",
- "re-read the issue",
- } {
- if !strings.Contains(got, want) {
- t.Fatalf("fresh-retry prompt missing disclosure %q; got:\n%s", want, got)
- }
+ // The notice only renders when the resume actually failed.
+ if blocks := perTurnContextBlocks(Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"}); strings.Contains(blocks, "Session Continuity Notice") {
+ t.Errorf("continuity notice leaked into a run that resumed fine:\n%s", blocks)
+ }
+ lost := perTurnContextBlocks(Task{
+ IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ PriorSessionResumeUnavailable: true,
+ })
+ if !strings.Contains(lost, "Session Continuity Notice") {
+ t.Errorf("continuity notice missing when the resume was unavailable:\n%s", lost)
}
- if !strings.HasSuffix(got, base) {
- t.Fatal("fresh-retry prompt must preserve the current prompt verbatim as its suffix")
+}
+
+// TestBackendResumeContinuityNoticeSuppressedWhenPromptAlreadyHasIt is the
+// count guard Elon asked for, on the combination that actually occurs: the
+// codex overflow fresh retry. The daemon appends the notice to the prompt AND
+// hands the backend a notice to prepend, so before MUL-5722 one turn carried
+// the same paragraph twice — at full token price, from two hand-written
+// strings. Suppression is keyed on the prompt already carrying it, so the two
+// injectors cannot both fire.
+func TestBackendResumeContinuityNoticeSuppressedWhenPromptAlreadyHasIt(t *testing.T) {
+ t.Parallel()
+
+ const heading = "## Session Continuity Notice"
+
+ // Live resume rejection the daemon cannot see pre-launch: the prompt says
+ // nothing, so the backend must.
+ fresh := Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890", TriggerCommentID: "c0ffee00-0000-0000-0000-000000000000"}
+ if got := backendResumeContinuityNotice(fresh); !strings.Contains(got, heading) {
+ t.Fatal("backend must disclose when the prompt does not")
+ }
+ if strings.Contains(BuildPrompt(fresh, "codex"), heading) {
+ t.Fatal("prompt should not carry the notice when the resume has not failed yet")
}
- if strings.Index(got, "brand-new session") > strings.Index(got, base) {
- t.Fatal("context-loss disclosure must precede the preserved prompt")
+
+ // The daemon's fresh-session retry sets this, which is what makes
+ // BuildPrompt append the notice — so the backend must now stay silent.
+ retry := fresh
+ retry.PriorSessionResumeUnavailable = true
+ prompt := BuildPrompt(retry, "codex")
+ if n := strings.Count(prompt, heading); n != 1 {
+ t.Fatalf("prompt must carry exactly one notice, got %d", n)
+ }
+ backendNotice := backendResumeContinuityNotice(retry)
+ if backendNotice != "" {
+ t.Fatalf("backend must not add a second copy, got:\n%s", backendNotice)
+ }
+ // The whole turn, as codex would assemble it.
+ turn := backendNotice + prompt
+ if n := strings.Count(turn, heading); n != 1 {
+ t.Fatalf("assembled turn carries %d notices, want exactly 1:\n%s", n, turn)
}
}
@@ -2455,6 +2545,41 @@ func TestShouldRetryWithFreshSession(t *testing.T) {
provider: "kiro",
want: false,
},
+ {
+ // MUL-5722: a codex thread/resume whose response overflowed the
+ // stdout line buffer. This is the case #5715 accidentally
+ // stranded — codex reported no rejection and is not in the
+ // undetectable set, so the gate returned false and the same
+ // oversized thread got resumed on every later turn. The backend
+ // now supplies the positive evidence; this asserts the gate
+ // actually acts on it.
+ name: "codex resume overflow retries on a fresh session",
+ result: agent.Result{
+ Status: "failed",
+ Error: "codex thread/resume failed: codex process exited: bufio.Scanner: token too long",
+ ResumeRejected: true,
+ },
+ priorSessionID: "thr_oversized",
+ tools: 0,
+ provider: "codex",
+ want: true,
+ },
+ {
+ // The tools gate is not weakened by the new evidence: a run that
+ // already acted is never replayed, poisoned resume or not. Such a
+ // task still gets its session retired — by the layer-3 classifier
+ // at report time rather than by an in-turn retry.
+ name: "codex resume overflow after tool use does not retry",
+ result: agent.Result{
+ Status: "failed",
+ Error: "codex thread/resume failed: codex process exited: bufio.Scanner: token too long",
+ ResumeRejected: true,
+ },
+ priorSessionID: "thr_oversized",
+ tools: 1,
+ provider: "codex",
+ want: false,
+ },
}
for _, tt := range tests {
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 8456f2a8ee..e38b6c27f6 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -386,17 +386,43 @@ func writeInstructionPrecedence(b *strings.Builder) {
b.WriteString("Never treat this runtime workflow as permission to change issue status, investigate, implement, create issues, update issues, delegate, or otherwise act beyond your Agent Identity.\n\n")
}
-// SessionContinuityNotice warns the agent — and, through it, the user — when a
-// resume the task expected could not be honored. The daemon has already
-// cleared the resume flags, so without this the run would silently reappear as
-// a brand-new conversation; here we make the loss explicit and ask the agent to
-// disclose it in its reply (MUL-4424).
+// The SessionContinuityNotice* family tells the agent a resume the task
+// expected could not be honored. The daemon has already cleared the resume
+// flags, so without this the run would silently reappear as a brand-new
+// conversation (MUL-4424).
+//
+// There are three because the surfaces lose different things, and saying so
+// accurately matters more than saying it loudly. The question that separates
+// them is not "is this a chat?" but "can this conversation still be read?":
+//
+// - Issue: the conversation IS the issue body and its comments. Untouched,
+// and the workflow already makes the agent read them every turn.
+// - Slack: the conversation lives in the channel and `multica chat history` /
+// `multica chat thread` can fetch it — see buildChatPrompt, which hands the
+// agent exactly those commands. Recoverable, just from a different place.
+// - Web chat and Feishu: nothing can fetch it. A web chat's history lived only
+// in the provider session, and Multica ships no history reader for Feishu
+// (handler/chat_history.go is hardwired to Slack), so the run has only the
+// inbound context for this turn.
+//
+// Only the last group warrants telling the user. On the first two the discussion
+// survives, so announcing "the previous context was lost" describes a loss that
+// did not happen — the user reasonably hears "the discussion is gone" when not a
+// word of it is. There the notice informs the agent and leaves mentioning it to
+// the agent's judgement. What is actually gone on every surface is the agent's
+// own unrecorded working memory, and each variant says so.
//
// Emitted into the per-turn user message rather than the runtime brief: it is
// true of one run and false of the next on the same issue, so rendering it into
// the brief broke prompt-cache prefix stability across resumes (MUL-5377).
-const SessionContinuityNotice = "## Session Continuity Notice\n\n" +
- "This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. Rebuild context from the issue/thread before acting. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n"
+const SessionContinuityNoticeIssue = "## Session Continuity Notice\n\n" +
+ "This run was meant to continue an earlier conversation, but that provider session could not be restored, so you are on a fresh one. The issue and its full comment history are unaffected — that record is the authoritative version of this conversation, and reading it (which your workflow already requires) reconstructs it. What is gone is only your own working memory from earlier turns: what you already tried, what you ruled out, and how far you had got. Re-derive what you need instead of assuming it, and do not claim continuity the record cannot back up. Do not open your reply by announcing this — raise it only where it actually matters, such as when the user refers to reasoning you never wrote down.\n\n"
+
+const SessionContinuityNoticeChannelHistory = "## Session Continuity Notice\n\n" +
+ "This run was meant to continue an earlier conversation, but that provider session could not be restored, so you are on a fresh one. The channel conversation itself is unaffected — read it back with `multica chat history` / `multica chat thread` before acting, and treat what you find there as the authoritative version. What is gone is only your own working memory from earlier turns: what you already tried, what you ruled out, and how far you had got. Re-derive what you need instead of assuming it. Do not open your reply by announcing this — raise it only where it actually matters.\n\n"
+
+const SessionContinuityNoticeUnrecoverable = "## Session Continuity Notice\n\n" +
+ "This run was meant to continue an earlier conversation, but that session's context could NOT be restored — you are starting fresh with no memory of the previous turns. That history is not readable from anywhere now: there is no command that fetches it, and only the context already in this message survives. **When you reply, tell the user up front (one short sentence) that the previous conversation context was unavailable and this is a new session**, so they understand why the thread did not carry over.\n\n"
// writeWorkflowHeader emits the unconditional `### Workflow` heading.
func writeWorkflowHeader(b *strings.Builder) {
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 9de32cb9d0..866668c9f7 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -305,11 +305,28 @@ func TestSessionContinuityNoticeLivesOutsideBrief(t *testing.T) {
"could NOT be restored",
"tell the user up front",
} {
- if !strings.Contains(SessionContinuityNotice, want) {
- t.Errorf("SessionContinuityNotice missing %q", want)
+ if !strings.Contains(SessionContinuityNoticeUnrecoverable, want) {
+ t.Errorf("SessionContinuityNoticeUnrecoverable missing %q", want)
}
}
+ // MUL-5722: the issue variant carries the same heading and the same
+ // "do not assume continuity" job, but must NOT order an announcement. An
+ // issue's discussion lives in its comments, which the agent re-reads every
+ // turn, so telling the user it was lost describes a loss that did not
+ // happen — they hear "the discussion is gone" when every word survives.
+ if !strings.Contains(SessionContinuityNoticeIssue, "## Session Continuity Notice") {
+ t.Error("SessionContinuityNoticeIssue must keep the section heading")
+ }
+ if strings.Contains(SessionContinuityNoticeIssue, "tell the user") {
+ t.Errorf("issue variant must not script an apology:\n%s", SessionContinuityNoticeIssue)
+ }
+ // It still has to say what genuinely went missing, or the agent silently
+ // assumes it remembers work it no longer has.
+ if !strings.Contains(SessionContinuityNoticeIssue, "your own working memory") {
+ t.Errorf("issue variant must state the real loss:\n%s", SessionContinuityNoticeIssue)
+ }
+
lost := TaskContextForEnv{
IssueID: "11111111-2222-3333-4444-555555555555",
TriggerCommentID: "trigger-1",
diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.go
index a28d6e905c..21ece61362 100644
--- a/server/internal/daemon/poisoned.go
+++ b/server/internal/daemon/poisoned.go
@@ -26,6 +26,9 @@ import (
// stuck without agent progress. Resuming that Codex session can replay the
// same stuck state, while a fresh manual rerun may succeed. Detected via
// classifyResumeUnsafeTimeout.
+// - Transport-side: a Codex thread/resume response too large to read back.
+// The thread only grows, so every later resume overflows identically.
+// Detected via classifyResumeUnsafeTransport.
//
// MUL-2946: ReasonIterationLimit and ReasonAPIInvalidRequest are aliased
// to the canonical taskfailure values so the daemon and the in-flight
@@ -39,6 +42,7 @@ const (
FailureReasonAgentFallbackMsg = "agent_fallback_message"
FailureReasonAPIInvalidRequest = string(taskfailure.ReasonAPIInvalidRequest)
FailureReasonCodexSemanticInactivity = "codex_semantic_inactivity"
+ FailureReasonCodexResumeOversized = "codex_resume_oversized"
)
// poisonedOutputMaxLen caps how long an output can be and still be
@@ -165,6 +169,37 @@ func classifyPoisonedError(errMsg string) (string, bool) {
return "", false
}
+// classifyResumeUnsafeTransport reports whether a transport-level failure means
+// the recorded session must not be resumed again.
+//
+// The one case today is a Codex thread/resume whose response overflowed our
+// stdout line buffer. That session is not merely unlucky, it is finished: codex
+// serializes the whole thread into that one response and its rollout file only
+// ever grows, so every future resume of the same thread reproduces the same
+// overflow. Leaving it as the (agent, issue) resume pointer is what turned this
+// into a permanent stall (MUL-5722).
+//
+// This is the backstop for the in-turn recovery, not a replacement for it. The
+// codex backend reports the same failure as Result.ResumeRejected, which lets
+// the daemon retry the CURRENT turn on a fresh session (see
+// shouldRetryWithFreshSession) — the outcome users actually want. But that
+// retry is gated on tools == 0 and can itself fail, and either way the task
+// lands here with the oversized thread still recorded. Classifying it keeps the
+// NEXT task off that thread even when the current one could not be saved.
+//
+// Provider-specific on purpose, exactly like classifyResumeUnsafeTimeout below:
+// no other backend replays its entire history through a single line, so for
+// them an oversized line is a one-off event and the session is still good.
+func classifyResumeUnsafeTransport(provider, errMsg string) (string, bool) {
+ if strings.ToLower(strings.TrimSpace(provider)) != "codex" {
+ return "", false
+ }
+ if agent.CodexResumeOverflowError(errMsg) {
+ return FailureReasonCodexResumeOversized, true
+ }
+ 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
diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.go
index 321b170c45..dafa51c5e4 100644
--- a/server/internal/daemon/poisoned_test.go
+++ b/server/internal/daemon/poisoned_test.go
@@ -4,6 +4,7 @@ import (
"strings"
"testing"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/pkg/agent"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -258,6 +259,82 @@ func TestClassifyPoisonedError(t *testing.T) {
}
}
+func TestClassifyResumeUnsafeTransport(t *testing.T) {
+ // The exact string the codex backend produces: startOrResumeThread's
+ // "codex thread/resume failed: %w" wrapping the reader goroutine's
+ // errCodexProcessExited + bufio.ErrTooLong.
+ const overflowErr = "codex thread/resume failed: codex process exited: bufio.Scanner: token too long"
+
+ cases := []struct {
+ name string
+ provider string
+ errMsg string
+ wantOK bool
+ wantReason string
+ }{
+ {
+ name: "codex resume overflow",
+ provider: "codex",
+ errMsg: overflowErr,
+ wantOK: true,
+ wantReason: FailureReasonCodexResumeOversized,
+ },
+ {
+ // Overflow on a different RPC says nothing about the session:
+ // dropping the resume pointer would discard a healthy thread.
+ name: "overflow outside a resume stays resumable",
+ provider: "codex",
+ errMsg: "codex thread/start failed: codex process exited: bufio.Scanner: token too long",
+ wantOK: false,
+ },
+ {
+ // An ordinary resume rejection is already handled by the fresh
+ // -session fallback and must not be retired through this path.
+ name: "plain resume failure stays resumable",
+ provider: "codex",
+ errMsg: "codex thread/resume failed: thread not found",
+ wantOK: false,
+ },
+ {
+ // Only codex replays its whole history through one line.
+ name: "other provider same text is not classified",
+ provider: "claude",
+ errMsg: overflowErr,
+ wantOK: false,
+ },
+ {
+ name: "empty error",
+ provider: "codex",
+ errMsg: "",
+ wantOK: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ reason, ok := classifyResumeUnsafeTransport(tc.provider, tc.errMsg)
+ if ok != tc.wantOK {
+ t.Fatalf("classifyResumeUnsafeTransport(%q, %q) ok=%v, want %v", tc.provider, tc.errMsg, ok, tc.wantOK)
+ }
+ if ok && reason != tc.wantReason {
+ t.Fatalf("classifyResumeUnsafeTransport(%q, %q) reason=%q, want %q", tc.provider, tc.errMsg, reason, tc.wantReason)
+ }
+ })
+ }
+}
+
+// TestCodexResumeOversizedIsResumeUnsafe pins the cross-package contract that
+// makes the classifier above worth anything: classifying the failure only helps
+// if the resume lookup actually treats the reason as unsafe. The service-side
+// list and the two SQL blacklists are edited by hand in three places, so this
+// asserts the Go half rather than trusting that all three stayed in sync.
+func TestCodexResumeOversizedIsResumeUnsafe(t *testing.T) {
+ if !service.ResumeUnsafeFailure(FailureReasonCodexResumeOversized, "") {
+ t.Fatalf("ResumeUnsafeFailure(%q) = false, want true — the reason is classified but the session would still be resumed",
+ FailureReasonCodexResumeOversized)
+ }
+}
+
func TestClassifyResumeUnsafeTimeout(t *testing.T) {
cases := []struct {
name string
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 3da82ca770..752e2c0ae5 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -7,18 +7,38 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/execenv"
)
-// freshSessionRetryPrompt prefixes an explicit context-loss disclosure onto the
-// (already cold-rebuilt) prompt used for the daemon's single fresh-session
-// retry. When a resumed run is refused — the transcript is gone, belongs to
-// another account, or (GH #5975) carries history the provider now rejects —
-// the retry starts a brand-new provider session with none of the prior
-// conversation. Stating that up front stops the agent from assuming continuity
-// (e.g. "as I said earlier", relying on files/state it never created) and steers
-// it to re-read the issue and triggering thread before acting. The current user
-// prompt is preserved verbatim below the notice.
-func freshSessionRetryPrompt(prompt string) string {
- const notice = "⚠️ Note: a previous provider session for this task could not be resumed, so this is a brand-new session. None of the earlier provider conversation context is available to you now. Do not assume any prior back-and-forth, in-memory state, or uncommitted work carried over — re-read the issue and the triggering thread to reconstruct what you need before acting.\n\n"
- return notice + prompt
+// sessionContinuityNoticeFor picks the notice matching what this surface
+// actually lost. See the constants in execenv for the full reasoning; the
+// question is whether the conversation is still READABLE, not whether it is a
+// chat — an issue's comments and a Slack channel's history both are, a web
+// chat's and a Feishu channel's are not (MUL-5722).
+func sessionContinuityNoticeFor(task Task) string {
+ if task.ChatSessionID == "" {
+ return execenv.SessionContinuityNoticeIssue
+ }
+ if task.ChatChannelType == execenv.ChannelTypeSlack {
+ return execenv.SessionContinuityNoticeChannelHistory
+ }
+ // Web chat (no channel type) and every channel Multica cannot read back.
+ return execenv.SessionContinuityNoticeUnrecoverable
+}
+
+// backendResumeContinuityNotice returns the notice the BACKEND should inject if
+// it lands on a fresh thread, or "" when the prompt already carries one.
+//
+// Only one notice may reach a turn. Two paths can produce it — the daemon,
+// which appends it to the prompt whenever it already knows the resume is gone,
+// and the backend, which is the only one that can see a live resume RPC being
+// rejected mid-run. Before MUL-5722 both fired on the codex overflow retry, so
+// the same paragraph was paid for twice in one turn and maintained as two
+// hand-written strings. Deriving the backend's copy from the daemon's, and
+// suppressing it exactly when the prompt already said it, makes a duplicate
+// structurally impossible rather than merely unlikely.
+func backendResumeContinuityNotice(task Task) string {
+ if task.PriorSessionResumeUnavailable {
+ return ""
+ }
+ return sessionContinuityNoticeFor(task)
}
// Turn-mode markers consumed by the runtime brief's mode router
@@ -51,7 +71,7 @@ const (
func perTurnContextBlocks(task Task) string {
var b strings.Builder
if task.PriorSessionResumeUnavailable {
- b.WriteString(execenv.SessionContinuityNotice)
+ b.WriteString(sessionContinuityNoticeFor(task))
}
b.WriteString(execenv.BuildTaskInitiatorBlock(task.InitiatorType, task.InitiatorName, task.InitiatorEmail))
b.WriteString(execenv.BuildConnectedAppsBlock(task.ConnectedApps))
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index beafac38ae..b8e5ffc341 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -1227,7 +1227,12 @@ func TestPerTurnContextBlocksCarryMovedBriefSections(t *testing.T) {
prompt := BuildPrompt(task, "claude")
for _, want := range []string{
"## Session Continuity Notice",
- "could NOT be restored",
+ // Issue wording: this task has an IssueID, and since MUL-5722 the two
+ // surfaces word the notice differently (the chat variant is the one
+ // that says "could NOT be restored" and asks the agent to announce it).
+ // What this test cares about is that the section reaches the per-turn
+ // message at all, not which variant it is.
+ "could not be restored",
"## Task Initiator",
"initiated by **Bohan** ([email protected]), a member of this workspace",
"credentials stay scoped to the runtime owner",
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index fa27f40904..be874a3585 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3862,7 +3862,10 @@ func resumeUnsafeFailureReason(reason string) bool {
// blacklists. (CreateRetryTask's fresh-session CASE WHEN only needs the
// subset of these that is also auto-retryable, currently
// codex_semantic_inactivity.)
- case "iteration_limit", "agent_fallback_message", "api_invalid_request", "codex_semantic_inactivity", "agent_error.context_overflow":
+ // codex_resume_oversized is the strongest member of this set: a codex
+ // rollout only ever grows, so a thread whose resume response already
+ // overflowed the reader will overflow on every future attempt too.
+ case "iteration_limit", "agent_fallback_message", "api_invalid_request", "codex_semantic_inactivity", "agent_error.context_overflow", "codex_resume_oversized":
return true
default:
return false
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index dab86bf8d8..58a515774d 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -53,13 +53,26 @@ type ExecOptions struct {
// conversation, independent of ResumeSessionID (which a fallback retry may
// clear). When it is true but the backend ends up on a fresh thread — the
// live resume RPC was rejected, or a transport failure forced a fresh retry —
- // the backend surfaces a continuity notice to the user instead of silently
+ // the backend surfaces a continuity notice instead of silently
// restarting. Currently honoured by the codex backend (MUL-4424).
- ResumeExpected bool
- ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only
- CustomArgs []string // per-agent CLI arguments appended after ExtraArgs
- QwenpawWorkspace string // per-task QwenPaw workspace directory (passed as --workspace to qwenpaw acp); empty when not applicable
- McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config
+ ResumeExpected bool
+ // ResumeContinuityNotice is the text to prepend to the first turn when
+ // ResumeExpected holds but the backend lands on a fresh thread anyway. The
+ // caller owns the wording because only it knows what the surface lost — an
+ // issue's comments and a Slack channel's history survive and can be re-read,
+ // a web chat's and a Feishu channel's cannot — and that difference decides
+ // whether the agent should tell the user anything at all (MUL-5722).
+ //
+ // Empty means say nothing, and the caller MUST leave it empty when its own
+ // prompt already carries the notice. That is what keeps a turn from paying
+ // for the same paragraph twice: the daemon injects it whenever it already
+ // knows the resume is gone, and the backend covers only the case the daemon
+ // cannot see — a live resume RPC rejected mid-run.
+ ResumeContinuityNotice string
+ ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only
+ CustomArgs []string // per-agent CLI arguments appended after ExtraArgs
+ QwenpawWorkspace string // per-task QwenPaw workspace directory (passed as --workspace to qwenpaw acp); empty when not applicable
+ McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config
// ThinkingLevel is the runtime-native reasoning/effort value (e.g.
// Claude's "low|medium|high|xhigh|max", Codex's "none|minimal|low|
// medium|high|xhigh", OpenCode's model variant names). Empty means
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 2ed7b9fe84..d965a765d0 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -152,6 +152,38 @@ const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"
// did not answer within the bounded handshake window.
const CodexHandshakeTimeoutMarker = "codex app-server handshake timeout"
+// codexResumeMarker and codexLineOverflowMarker are the two halves of the
+// error text a resume-overflow produces: the method that failed (written by
+// startOrResumeThread) and bufio's own ErrTooLong wording, which reaches the
+// string through the reader goroutine.
+const (
+ codexResumeMarker = "thread/resume failed"
+ codexLineOverflowMarker = "token too long"
+)
+
+// CodexResumeOverflowError reports whether an agent error string is the
+// resume-overflow failure — the thread/resume response did not fit in our
+// stdout line buffer, so the thread cannot be handed to us at all.
+//
+// This lives next to the code that writes both halves of the text so the two
+// cannot drift apart, and it is exported because the daemon has only the error
+// STRING at report time: by then the typed bufio.ErrTooLong that
+// isCodexResumeOverflow matches in-process is long gone. Both markers are
+// required — "thread/resume failed" alone covers ordinary rejections that a
+// plain retry handles, and "token too long" alone would also match an overflow
+// on some other RPC, where dropping the session pointer cures nothing.
+//
+// The session behind such a failure is unusable for resume until it shrinks,
+// which it never does — codex rollouts are append-only. Callers use this to
+// stop handing the same oversized thread to the next task (MUL-5722).
+func CodexResumeOverflowError(errText string) bool {
+ if errText == "" {
+ return false
+ }
+ lower := strings.ToLower(errText)
+ return strings.Contains(lower, codexResumeMarker) && strings.Contains(lower, codexLineOverflowMarker)
+}
+
// codexModelCatalogRefreshFailureSignal matches the Codex models-manager error
// emitted when the model catalog could not be refreshed. Codex reports several
// distinct causes under this prefix ("timeout waiting for child process to
@@ -862,7 +894,8 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
// thread may hold the submitted input or an unfinished turn.
// Resuming it again could duplicate that input; start a fresh
// thread instead and keep ResumeExpected so codexTurnInput
- // prepends the continuity notice about the lost context.
+ // prepends the caller's continuity notice about the lost
+ // context.
if attemptOpts.ResumeSessionID != "" {
b.cfg.Logger.Warn("codex retry dropping resume pointer after model catalog refresh failure",
"prior_thread_id", attemptOpts.ResumeSessionID,
@@ -1094,7 +1127,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
c.handleLine(line)
}
if err := scanner.Err(); err != nil {
- c.markProcessExited(fmt.Errorf("%w: %v", errCodexProcessExited, err))
+ // %w on BOTH: callers match errCodexProcessExited to decide the
+ // process is gone, and bufio.ErrTooLong to tell "we could not read
+ // the response" apart from "codex died". startOrResumeThread needs
+ // that distinction to report an oversized resume as a rejected
+ // resume rather than a crash (MUL-5722).
+ c.markProcessExited(fmt.Errorf("%w: %w", errCodexProcessExited, err))
return
}
c.markProcessExited(errCodexProcessExited)
@@ -1342,7 +1380,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
"stderr_bare_timeout_count", classification.bareTimeout,
)
}
- resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ resCh <- Result{
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ ResumeRejected: isCodexResumeOverflow(opts, err),
+ }
return
}
c.threadID = threadID
@@ -1355,13 +1398,17 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// 3. Send turn and wait for completion. When a resume was expected but we
// ended up on a fresh thread (the live thread/resume RPC was rejected — a
// corrupt/incompatible rollout, server-side thread GC, schema drift — or a
- // transport failure forced a fresh retry), prepend a continuity notice so
- // the agent tells the user the prior conversation could not be restored.
- // The daemon's pre-flight gates only catch cases detectable before launch;
+ // transport failure forced a fresh retry), prepend the caller's continuity
+ // notice so the agent does not assume continuity it no longer has. The
+ // daemon's pre-flight gates only catch cases detectable before launch;
// this covers the ones only the live resume reveals (MUL-4424).
+ //
+ // Whether that notice asks the agent to tell the USER is the caller's
+ // call, not ours: it depends on whether this surface's conversation is
+ // still readable, which this package cannot see (MUL-5722).
turnParams := map[string]any{
"threadId": threadID,
- "input": codexTurnInput(prompt, opts.ResumeExpected, resumed),
+ "input": codexTurnInput(prompt, opts.ResumeExpected, resumed, opts.ResumeContinuityNotice),
}
// Per-turn reasoning override. Mirrors the per-thread injection in
// startOrResumeThread; keeping both in sync is enforced by the
@@ -1663,23 +1710,26 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
return &Session{Messages: msgCh, Result: resCh}, nil
}
-// codexResumeUnavailableNotice is prepended to the first turn's input when a
-// resume was expected but Codex ended up on a fresh thread. It mirrors the
-// daemon brief's Session Continuity Notice so the disclosure is identical
-// whether the loss is detected pre-launch (daemon gate) or only by the live
-// thread/resume RPC (MUL-4424).
-const codexResumeUnavailableNotice = "[System notice] You were expected to continue an earlier conversation, but restoring that session failed and this is a fresh thread with no memory of the previous turns. Rebuild context from the issue/thread, and when you reply, tell the user up front (one short sentence) that the previous conversation context could not be restored and this is a new session.\n\n"
+// The continuity notice this backend prepends is supplied by the caller via
+// ExecOptions.ResumeContinuityNotice rather than written here. It used to be a
+// constant in this file that mirrored the daemon's, which meant two hand-kept
+// copies of the same paragraph and no way for this package to know which
+// surface it was running on — the wording is only correct if you know whether
+// the conversation is still readable (MUL-5722).
// codexTurnInput builds the input content for the first turn/start. When a
// resume was expected (resumeExpected) but the backend landed on a fresh thread
-// (!resumed), it prepends codexResumeUnavailableNotice so the user learns the
-// prior context was lost instead of the run silently continuing as new. The
-// notice is folded into the same text block as the prompt to stay within the
-// single-text-block turn input Codex already accepts.
-func codexTurnInput(prompt string, resumeExpected, resumed bool) []map[string]any {
+// (!resumed), it prepends the caller's continuity notice so the run does not
+// silently continue as new. The notice is folded into the same text block as
+// the prompt to stay within the single-text-block turn input Codex accepts.
+//
+// An empty notice means the caller has already disclosed the loss in the prompt
+// itself, so this must add nothing — that is the whole guard against a turn
+// carrying the same paragraph twice.
+func codexTurnInput(prompt string, resumeExpected, resumed bool, notice string) []map[string]any {
text := prompt
if resumeExpected && !resumed {
- text = codexResumeUnavailableNotice + prompt
+ text = notice + prompt
}
return []map[string]any{{"type": "text", "text": text}}
}
@@ -2330,6 +2380,29 @@ func (c *codexClient) getProcessErr() error {
return c.processErr
}
+// isCodexResumeOverflow reports whether a failed startOrResumeThread failed
+// because the thread/resume RESPONSE did not fit in our stdout line buffer.
+//
+// Codex serializes the entire thread into that single response, so a long
+// enough thread overflows agentStreamMaxLineBytes and the reader goroutine
+// dies with bufio.ErrTooLong. Every other transport error means codex is
+// gone; this one means codex is fine and we cannot read it. The distinction
+// is what makes it a resume REJECTION: the thread cannot be handed to us at
+// all, so only starting over can cure it — exactly what Result.ResumeRejected
+// documents, and the evidence shouldRetryWithFreshSession looks for first.
+//
+// Recovery has to go through the daemon rather than a local thread/start
+// fallback. By the time we get here the reader goroutine has exited and codex
+// is blocked writing the rest of the oversized line into a pipe nobody drains,
+// so this process can no longer answer any RPC. The daemon's fresh-session
+// retry re-execs codex, which is the only way back (MUL-5722).
+//
+// Requires ResumeSessionID: an overflow on a thread/start response is a
+// different failure and nothing about the session pointer would fix it.
+func isCodexResumeOverflow(opts ExecOptions, err error) bool {
+ return opts.ResumeSessionID != "" && errors.Is(err, bufio.ErrTooLong)
+}
+
func isCodexTransportError(err error) bool {
if err == nil {
return false
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 61e6d9bdc6..9044385b68 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1935,6 +1935,9 @@ func TestCodexTurnInput(t *testing.T) {
t.Parallel()
const prompt = "do the task"
+ // Stands in for whatever the daemon computed for this surface; the backend
+ // only carries it, so the exact wording is the caller's business.
+ const chatNotice = "[System notice] the previous conversation context could not be restored.\n\n"
text := func(input []map[string]any) string {
if len(input) != 1 {
t.Fatalf("expected a single input block, got %d", len(input))
@@ -1945,7 +1948,7 @@ func TestCodexTurnInput(t *testing.T) {
// Resume expected but the backend fell back to a fresh thread → disclose,
// and the original prompt must still be delivered.
- fallback := text(codexTurnInput(prompt, true, false))
+ fallback := text(codexTurnInput(prompt, true, false, chatNotice))
if !strings.Contains(fallback, "previous conversation context could not be restored") {
t.Errorf("expected continuity notice on resume fallback, got:\n%s", fallback)
}
@@ -1955,14 +1958,36 @@ func TestCodexTurnInput(t *testing.T) {
// Successful resume, or an ordinary fresh start with no resume expected →
// no notice, prompt delivered verbatim.
- if got := text(codexTurnInput(prompt, true, true)); got != prompt {
+ if got := text(codexTurnInput(prompt, true, true, chatNotice)); got != prompt {
t.Errorf("successful resume must not add a notice, got:\n%s", got)
}
- if got := text(codexTurnInput(prompt, false, false)); got != prompt {
+ if got := text(codexTurnInput(prompt, false, false, chatNotice)); got != prompt {
t.Errorf("fresh start must not add a notice, got:\n%s", got)
}
}
+// TestCodexTurnInputNoticeMatchesWhatTheSurfaceLost is the MUL-5722 half of the
+// continuity notice. An issue's discussion survives in its comments, which the
+// agent re-reads every turn, so ordering it to announce "the previous context
+// was lost" tells the user the discussion is gone when none of it is. The
+// notice still has to fire — the agent must not silently assume continuity —
+// but on that surface it informs the agent instead of scripting an apology.
+func TestCodexTurnInputSuppressesNoticeWhenCallerAlreadyDisclosed(t *testing.T) {
+ t.Parallel()
+
+ // An empty notice is how the caller says "the prompt already carries it".
+ // Honouring that is the backend's half of the no-duplicate guarantee: on
+ // the daemon's fresh-session retry the prompt already ends with the
+ // continuity notice, and before MUL-5722 this path prepended a second copy
+ // of the same paragraph into the same turn.
+ const prompt = "do the task"
+ input := codexTurnInput(prompt, true, false, "")
+ got, _ := input[0]["text"].(string)
+ if got != prompt {
+ t.Fatalf("empty notice must leave the prompt untouched, got:\n%s", got)
+ }
+}
+
func TestCodexStartOrResumeThreadDoesNotFallBackAfterProcessExit(t *testing.T) {
t.Parallel()
@@ -3194,6 +3219,15 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
t.Fatalf("expected empty SessionID so outer fallback retries fresh, got %q",
result.SessionID)
}
+ // MUL-5722 layer 2: an unreadable resume response is a rejected resume,
+ // and this flag is the positive evidence shouldRetryWithFreshSession
+ // requires. Without it #5715's gate stops the retry dead (codex is in
+ // neither the ResumeRejected-capable nor the undetectable set), and the
+ // next turn resumes the same oversized thread forever.
+ if !result.ResumeRejected {
+ t.Fatalf("expected ResumeRejected=true so the daemon retries on a fresh session; error=%q",
+ result.Error)
+ }
// 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
@@ -3205,6 +3239,50 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
}
}
+func TestCodexExecuteDoesNotClaimResumeRejectedWhenOverflowIsNotAResume(t *testing.T) {
+ // Not t.Parallel(): mutates codexGracefulShutdownTimeoutNanos globally,
+ // same as its sibling above.
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // The overflow guard is scoped to resumes on purpose. A run with no prior
+ // session that overflows on the thread/start response is a different
+ // failure: there is no session pointer to drop, so reporting a resume
+ // rejection would send the daemon looking for a cure that does not apply
+ // — and ResumeRejected is documented as positive evidence, not a generic
+ // "something went wrong" flag.
+ 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"+
+ // Same oversized single line, but answering thread/start rather than
+ // thread/resume because the caller passed no ResumeSessionID.
+ `printf '{"jsonrpc":"2.0","id":2,"result":{"big":"'`+"\n"+
+ fmt.Sprintf(`head -c %d /dev/zero | tr '\0' 'x'`, agentStreamMaxLineBytes+1024*1024)+"\n"+
+ `printf '"}}\n'`+"\n"+
+ `sleep 30`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 30 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ })
+
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "token too long") {
+ t.Fatalf("expected error to surface scanner overflow cause, got %q", result.Error)
+ }
+ if result.ResumeRejected {
+ t.Fatalf("expected ResumeRejected=false without a prior session, error=%q", result.Error)
+ }
+}
+
func TestCodexExecuteSurfacesUnsupportedServerRequestOnInterruptedTurn(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
@@ -3533,8 +3611,12 @@ func TestCodexExecuteRetryAfterCatalogFailureStartsFreshThreadForResume(t *testi
`fi`+"\n")
result, _ := executeFakeCodexCollectingMessages(t, fakePath, ExecOptions{
- ResumeSessionID: "thr-prior",
- ResumeExpected: true,
+ ResumeSessionID: "thr-prior",
+ ResumeExpected: true,
+ // Supplied by the daemon since MUL-5722: this package no longer holds
+ // the wording, because only the caller knows whether the surface's
+ // conversation can still be read.
+ ResumeContinuityNotice: "[System notice] the previous conversation context could not be restored.\n\n",
Timeout: 20 * time.Second,
SemanticInactivityTimeout: 100 * time.Millisecond,
}, 20*time.Second)
@@ -3563,8 +3645,8 @@ func TestCodexExecuteRetryAfterCatalogFailureStartsFreshThreadForResume(t *testi
if !strings.Contains(string(second), "thread/start") {
t.Fatalf("expected the retry to start a fresh thread, got %s", second)
}
- // ResumeExpected survives the cleared pointer, so the agent is told the
- // prior context could not be restored.
+ // ResumeExpected survives the cleared pointer, so the caller's notice is
+ // still prepended and the agent is told the prior context is gone.
if !strings.Contains(string(second), "previous conversation context could not be restored") {
t.Fatalf("expected the retry input to carry the continuity notice, got %s", second)
}
@@ -5352,3 +5434,84 @@ func TestCodexPatchApplyStillTruncatesNonSecretPayload(t *testing.T) {
t.Fatalf("codexPatchInput must not mutate its argument: %d != %d", len(original), len(body))
}
}
+
+func TestCodexResumeOverflowError(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ errText string
+ want bool
+ }{
+ {
+ // The exact text executeOnce puts in Result.Error for this failure.
+ name: "resume overflow",
+ errText: "codex thread/resume failed: codex process exited: bufio.Scanner: token too long",
+ want: true,
+ },
+ {
+ // Both markers required: an overflow on another RPC leaves the
+ // stored thread perfectly resumable, so retiring it cures nothing.
+ name: "overflow on thread/start",
+ errText: "codex thread/start failed: codex process exited: bufio.Scanner: token too long",
+ want: false,
+ },
+ {
+ // An ordinary resume rejection already has a recovery path.
+ name: "resume failure without overflow",
+ errText: "codex thread/resume failed: thread not found",
+ want: false,
+ },
+ {
+ name: "unrelated process failure",
+ errText: "codex process exited: exit status 2",
+ want: false,
+ },
+ {name: "empty", errText: "", want: false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := CodexResumeOverflowError(tc.errText); got != tc.want {
+ t.Fatalf("CodexResumeOverflowError(%q) = %v, want %v", tc.errText, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestCodexResumeOverflowErrorMatchesLiveFailureText guards the seam between
+// the two halves of MUL-5722's layer 3: in-process the backend detects the
+// overflow from the typed bufio.ErrTooLong, but the daemon classifies it at
+// report time from the error STRING alone. If the wording produced by
+// startOrResumeThread ever drifts from what the predicate matches, the resume
+// pointer silently stops being retired and the permanent-stall bug returns
+// with every test above still green.
+func TestCodexResumeOverflowErrorMatchesLiveFailureText(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ 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"+
+ `printf '{"jsonrpc":"2.0","id":2,"result":{"big":"'`+"\n"+
+ fmt.Sprintf(`head -c %d /dev/zero | tr '\0' 'x'`, agentStreamMaxLineBytes+1024*1024)+"\n"+
+ `printf '"}}\n'`+"\n"+
+ `sleep 30`+"\n")
+
+ result := executeFakeCodex(t, fakePath, ExecOptions{
+ Cwd: t.TempDir(),
+ ResumeSessionID: "thr_prior",
+ Timeout: 30 * time.Second,
+ SemanticInactivityTimeout: 5 * time.Second,
+ })
+
+ if !CodexResumeOverflowError(result.Error) {
+ t.Fatalf("predicate missed the error the backend actually produced: %q", result.Error)
+ }
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 178f2ebee1..01397da4b0 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3038,6 +3038,15 @@ WITH retired_sessions AS (
FROM agent_task_queue r
WHERE r.agent_id = $1 AND r.issue_id = $2
AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.issue_id = $2
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
), latest_per_session AS (
SELECT DISTINCT ON (t.session_id)
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error,
@@ -3054,13 +3063,24 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
status IN ('completed', 'cancelled')
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
AND NOT (COALESCE(error, '') ILIKE '%image dimensions exceed max allowed size%' AND COALESCE(error, '') ILIKE '%image.source.base64.data%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
)
)
+ -- MUL-5722: a resume that overflowed the reader names no session, so it can
+ -- only be excluded by time, not by matching the failed row. Drop every
+ -- session whose last terminal activity predates the newest such failure: one
+ -- of them IS the oversized thread, and the row that would tell us which is
+ -- exactly the row that could not be written. Anything that terminated after
+ -- the overflow is the fresh thread that replaced it, so this un-blocks itself
+ -- as soon as one succeeds.
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR terminal_at > (SELECT at FROM resume_overflow_at)
+ )
ORDER BY terminal_at DESC
LIMIT 1
`
@@ -3107,12 +3127,14 @@ 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, codex_semantic_inactivity, agent_error.context_overflow)
+// api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow,
+// codex_resume_oversized)
// 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.), a Codex semantic inactivity
-// timeout whose recorded session may replay the same stuck state, or a context
-// window overflow that would immediately overflow again on resume. Keep this
+// timeout whose recorded session may replay the same stuck state, a context
+// window overflow that would immediately overflow again on resume, or a Codex
+// thread/resume response too large to read back (MUL-5722). Keep this
// list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
//
// The error-text ILIKE clause is defense-in-depth for the api_invalid_request
@@ -3148,6 +3170,15 @@ type GetLastTaskSessionRow struct {
// exactly as narrow as classifyPoisonedError and the Kiro detector — an
// unrelated error that only mentions image dimensions is NOT excluded.
//
+// MUL-5722 needed a different shape, and the reason is worth stating because
+// the first attempt got it wrong: a row-level guard like the ones above CANNOT
+// work for an overflowed resume. That failure happens before the turn starts,
+// so the backend has no session id to report and the row lands with session_id
+// NULL — which the latest_per_session CTE drops before any filter runs. The
+// only row naming the oversized thread is the OLDER completed one, which looks
+// perfectly healthy. Hence resume_overflow_at below: block by TIME, which needs
+// nothing from the failed row but its existence. See the clause for details.
+//
// The final pair of regexes is the provider-agnostic version of the same
// guard, and it matters most for self-hosted installs: daemons upgrade on
// their own cadence, so a host still running a daemon without
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index b447b869d2..7878c4d6aa 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -750,6 +750,19 @@ WITH retired_sessions AS (
FROM agent_task_queue r
WHERE r.chat_session_id = $1
AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ -- completed_at alone, where the issue-side twin coalesces four columns:
+ -- this query already selects and orders by bare completed_at throughout,
+ -- so the cutoff has to be measured on the same clock as the values it is
+ -- compared against. Change both halves together if that ever moves.
+ SELECT MAX(t.completed_at) AS at
+ FROM agent_task_queue t
+ WHERE t.chat_session_id = $1
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
), latest_per_session AS (
SELECT DISTINCT ON (t.session_id)
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at
@@ -765,12 +778,21 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
status IN ('completed', 'cancelled')
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
)
)
+ -- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records no
+ -- session, so exclude by time instead of by matching the failed row. Note
+ -- this only guards the FALLBACK — the claim handler reads
+ -- chat_session.session_id first, so a pointer still naming the oversized
+ -- thread has to be cleared at fail time (see FailTask) to be covered.
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR completed_at > (SELECT at FROM resume_overflow_at)
+ )
ORDER BY completed_at DESC
LIMIT 1
`
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 4456e088ca..5b36243d25 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -757,12 +757,14 @@ 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, codex_semantic_inactivity, agent_error.context_overflow)
+-- api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow,
+-- codex_resume_oversized)
-- 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.), a Codex semantic inactivity
--- timeout whose recorded session may replay the same stuck state, or a context
--- window overflow that would immediately overflow again on resume. Keep this
+-- timeout whose recorded session may replay the same stuck state, a context
+-- window overflow that would immediately overflow again on resume, or a Codex
+-- thread/resume response too large to read back (MUL-5722). Keep this
-- list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
--
-- The error-text ILIKE clause is defense-in-depth for the api_invalid_request
@@ -798,6 +800,15 @@ RETURNING *;
-- exactly as narrow as classifyPoisonedError and the Kiro detector — an
-- unrelated error that only mentions image dimensions is NOT excluded.
--
+-- MUL-5722 needed a different shape, and the reason is worth stating because
+-- the first attempt got it wrong: a row-level guard like the ones above CANNOT
+-- work for an overflowed resume. That failure happens before the turn starts,
+-- so the backend has no session id to report and the row lands with session_id
+-- NULL — which the latest_per_session CTE drops before any filter runs. The
+-- only row naming the oversized thread is the OLDER completed one, which looks
+-- perfectly healthy. Hence resume_overflow_at below: block by TIME, which needs
+-- nothing from the failed row but its existence. See the clause for details.
+--
-- The final pair of regexes is the provider-agnostic version of the same
-- guard, and it matters most for self-hosted installs: daemons upgrade on
-- their own cadence, so a host still running a daemon without
@@ -821,6 +832,15 @@ WITH retired_sessions AS (
FROM agent_task_queue r
WHERE r.agent_id = $1 AND r.issue_id = $2
AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.issue_id = $2
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
), latest_per_session AS (
SELECT DISTINCT ON (t.session_id)
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error,
@@ -837,13 +857,24 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
status IN ('completed', 'cancelled')
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
AND NOT (COALESCE(error, '') ILIKE '%image dimensions exceed max allowed size%' AND COALESCE(error, '') ILIKE '%image.source.base64.data%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
)
)
+ -- MUL-5722: a resume that overflowed the reader names no session, so it can
+ -- only be excluded by time, not by matching the failed row. Drop every
+ -- session whose last terminal activity predates the newest such failure: one
+ -- of them IS the oversized thread, and the row that would tell us which is
+ -- exactly the row that could not be written. Anything that terminated after
+ -- the overflow is the fresh thread that replaced it, so this un-blocks itself
+ -- as soon as one succeeds.
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR terminal_at > (SELECT at FROM resume_overflow_at)
+ )
ORDER BY terminal_at DESC
LIMIT 1;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index bf06b2c491..7b94f64849 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -804,6 +804,19 @@ WITH retired_sessions AS (
FROM agent_task_queue r
WHERE r.chat_session_id = $1
AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ -- completed_at alone, where the issue-side twin coalesces four columns:
+ -- this query already selects and orders by bare completed_at throughout,
+ -- so the cutoff has to be measured on the same clock as the values it is
+ -- compared against. Change both halves together if that ever moves.
+ SELECT MAX(t.completed_at) AS at
+ FROM agent_task_queue t
+ WHERE t.chat_session_id = $1
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
), latest_per_session AS (
SELECT DISTINCT ON (t.session_id)
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at
@@ -819,12 +832,21 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
status IN ('completed', 'cancelled')
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
AND NOT (COALESCE(error, '') ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
AND COALESCE(error, '') ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
)
)
+ -- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records no
+ -- session, so exclude by time instead of by matching the failed row. Note
+ -- this only guards the FALLBACK — the claim handler reads
+ -- chat_session.session_id first, so a pointer still naming the oversized
+ -- thread has to be cleared at fail time (see FailTask) to be covered.
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR completed_at > (SELECT at FROM resume_overflow_at)
+ )
ORDER BY completed_at DESC
LIMIT 1;