Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): unblock issues stuck on a poisoned-image agent session (#2314)
Bohan Jiang6d9ebb0fddc0
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.goindex 03cd9f1de7..2f2c6fec72 100644--- a/server/cmd/server/rerun_session_test.go+++ b/server/cmd/server/rerun_session_test.go@@ -130,6 +130,131 @@ func TestGetLastTaskSessionFallbackPoisonedClassifier(t *testing.T) {}}+// TestGetLastTaskSessionExcludesAPIInvalidRequest covers the MUL-1921+// case: an Anthropic 400 invalid_request_error (e.g. an oversized or+// malformed image baked into the conversation) bakes the bad message+// into the session history, so resuming would replay the same 400+// forever. The daemon classifies these as 'api_invalid_request' and the+// SQL filter must skip them on the resume lookup.+func TestGetLastTaskSessionExcludesAPIInvalidRequest(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 '5 seconds', now() - interval '5 seconds', 'POISONED-API400', '/tmp/poisoned', 'api_invalid_request')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert poisoned 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},+ })+ if err == nil && prior.SessionID.Valid {+ t.Fatalf("expected no resumable session for api_invalid_request, got %q", prior.SessionID.String)+ }+}++// 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 400+// invalid_request_error marker. The daemon-side classifier only fires+// on new failures, so without a defensive ILIKE clause the resume query+// would happily return one of those rows on the next claim and+// re-poison every retry of an already-broken issue (e.g. MUL-1918,+// which already has three poisoned 'agent_error' rows when this PR+// merges). The SQL must skip the bad row on text shape alone.+func TestGetLastTaskSessionExcludesLegacyAPI400(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()++ // Legacy poisoned row: failure_reason was the pre-fix default+ // 'agent_error' but the error text shows it was an API 400+ // invalid_request_error. Migration 079 backfills these to+ // 'api_invalid_request', but the SQL filter must still exclude+ // them via ILIKE on the off chance a row escapes the migration+ // (deploy window, manual relabel, etc.).+ 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', 'LEGACY-POISONED', '/tmp/legacy', 'agent_error',+ 'API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"}}')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert legacy poisoned task: %v", err)+ }++ // Newly classified poisoned row coexisting with the legacy one.+ // Without the ILIKE clause, ORDER BY completed_at DESC would+ // skip this row (failure_reason filter fires) and fall back to+ // the legacy row (failure_reason filter MISSES) — the exact+ // wormhole GPT-Boy flagged on PR review.+ 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', 'NEW-POISONED', '/tmp/new', 'api_invalid_request',+ 'API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"}}')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert new poisoned 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 && prior.SessionID.Valid {+ t.Fatalf("expected no resumable session, but query fell back to %q", prior.SessionID.String)+ }+}++// TestGetLastTaskSessionKeepsBenignAgentErrorWithSession asserts the+// ILIKE clause is narrow enough that ordinary 'agent_error' failures+// (timeouts, tool errors, transient glue failures) still let the next+// task resume the prior session. Without this guard rail, the MUL-1921+// fix would regress MUL-1128's resume contract for everything else.+func TestGetLastTaskSessionKeepsBenignAgentErrorWithSession(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, error)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '30 seconds', now() - interval '30 seconds', 'HEALTHY-RESUMABLE', '/tmp/healthy', 'agent_error',+ 'tool execution failed: connection refused')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert benign 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},+ })+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if !prior.SessionID.Valid || prior.SessionID.String != "HEALTHY-RESUMABLE" {+ t.Fatalf("expected to resume HEALTHY-RESUMABLE, got %q (valid=%v)", prior.SessionID.String, prior.SessionID.Valid)+ }+}+// TestRerunIssueSetsForceFreshSession asserts the manual rerun flow flags// the new task so the daemon claim handler skips the resume lookup. This// is the call-site half of the fix: even if the SQL filter ever misses adiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex cdd967f392..de55d572f5 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1957,13 +1957,27 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// model reject, …). Without this the chat_session resume pointer// would either be left stale or overwritten with NULL on the// server, causing the next chat turn to lose context.+ //+ // Classify upstream API 400 invalid_request_error failures with a+ // dedicated failure_reason so GetLastTaskSession excludes the+ // task from the (agent_id, issue_id) resume lookup. Without this+ // classifier a corrupt image or oversized payload baked into the+ // conversation permanently blocks the issue: every follow-up+ // task resumes the same poisoned session and hits the same 400.+ failureReason, _ := classifyPoisonedError(errMsg)+ if failureReason != "" {+ taskLog.Warn("agent failed with poisoned API error, classifying as blocked",+ "failure_reason", failureReason,+ )+ }return TaskResult{- Status: "blocked",- Comment: errMsg,- SessionID: result.SessionID,- WorkDir: env.WorkDir,- EnvRoot: env.RootDir,- Usage: usageEntries,+ Status: "blocked",+ Comment: errMsg,+ SessionID: result.SessionID,+ WorkDir: env.WorkDir,+ EnvRoot: env.RootDir,+ Usage: usageEntries,+ FailureReason: failureReason,}, nil}}diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex 0bf1b560e3..974f122c4a 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -2,15 +2,24 @@ package daemonimport "strings"-// FailureReason values for tasks that "completed" with output but the-// output is actually a known agent fallback marker — i.e. the agent gave-// up and emitted a meta message instead of a real result. Listed here so-// the server-side query GetLastTaskSession can filter them out and a-// rerun starts from a fresh agent session instead of resuming the same-// poisoned conversation.+// FailureReason values for tasks whose session is "poisoned" — i.e.+// resuming the same conversation on a follow-up task would deterministically+// reproduce the same failure. Listed here so the server-side query+// GetLastTaskSession can filter them out and the next task starts from+// a fresh agent session instead of inheriting the bad state.+//+// Two flavors:+// - Output-side: agent "completed" with output that is actually a known+// fallback marker (gave up mid-thought, emitted a meta message). Detected+// via classifyPoisonedOutput.+// - Error-side: the LLM API itself rejected the request with a 400+// 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.const (- FailureReasonIterationLimit = "iteration_limit"- FailureReasonAgentFallbackMsg = "agent_fallback_message"+ FailureReasonIterationLimit = "iteration_limit"+ FailureReasonAgentFallbackMsg = "agent_fallback_message"+ FailureReasonAPIInvalidRequest = "api_invalid_request")// poisonedOutputMaxLen caps how long an output can be and still be@@ -55,3 +64,37 @@ func classifyPoisonedOutput(output string) (string, bool) {}return "", false}++// classifyPoisonedError reports whether an agent error message indicates+// the LLM API itself rejected the request body — i.e. the conversation+// history contains content the API will not accept (oversized image,+// malformed base64, prompt-too-long, etc.). The conversation cannot be+// resumed: every retry replays the same body and reproduces the same 400.+// The classifier returns FailureReasonAPIInvalidRequest so GetLastTaskSession+// excludes the task from the (agent_id, issue_id) resume lookup, and the+// next task on the issue starts a fresh session instead of permanently+// inheriting the bad state.+//+// Match shape: the Claude Code SDK and similar backends surface upstream+// API failures verbatim, e.g.+//+// API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"},"request_id":"..."}+//+// Matching on both "400" and "invalid_request_error" keeps the classifier+// narrow: 429 rate-limits, 5xx overloads, and tool-shaped errors are+// transient and SHOULD resume on retry.+func classifyPoisonedError(errMsg string) (string, bool) {+ if errMsg == "" {+ return "", false+ }+ lowered := strings.ToLower(errMsg)+ // Both markers must be present: "400" alone is too generic (a tool+ // could surface a 400 from anywhere) and "invalid_request_error"+ // alone could in theory appear in non-poisoning contexts. The+ // combination is the canonical Anthropic error shape and indicates+ // the request body — i.e. the conversation history — is the problem.+ if strings.Contains(lowered, "invalid_request_error") && strings.Contains(lowered, "400") {+ return FailureReasonAPIInvalidRequest, true+ }+ return "", false+}diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex b50dceee35..805f1147e8 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -84,3 +84,88 @@ the matcher being too permissive on long outputs.`,})}}++func TestClassifyPoisonedError(t *testing.T) {+ cases := []struct {+ name string+ errMsg string+ wantOK bool+ wantReason string+ }{+ {+ // MUL-1921 reproducer: a markdown image in the issue+ // description was downloaded as a 146-byte CDN auth-error+ // XML, then surfaced to the LLM as a base64 PNG. The API+ // rejected it and every follow-up task replayed the same+ // poisoned conversation.+ name: "claude could not process image",+ errMsg: `API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"Could not process image"},"request_id":"req_011CarVEtBLj95zD7i8xardY"}`,+ wantOK: true,+ wantReason: FailureReasonAPIInvalidRequest,+ },+ {+ name: "prompt too long is also poisoning",+ errMsg: `API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long: 213000 tokens > 200000 maximum"}}`,+ wantOK: true,+ wantReason: FailureReasonAPIInvalidRequest,+ },+ {+ name: "case insensitive",+ errMsg: `api error: 400 {"type":"INVALID_REQUEST_ERROR"}`,+ wantOK: true,+ wantReason: FailureReasonAPIInvalidRequest,+ },+ {+ // Rate-limit must NOT be classified as poisoning — those+ // recover on retry and we want session resume to keep the+ // in-flight conversation memory.+ name: "429 rate limit is transient",+ errMsg: `API Error: 429 {"type":"error","error":{"type":"rate_limit_error","message":"Number of request tokens has exceeded your per-minute rate limit"}}`,+ wantOK: false,+ },+ {+ name: "5xx overloaded is transient",+ errMsg: `API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`,+ wantOK: false,+ },+ {+ // 401/403 mean the daemon's credentials are bad; resuming+ // the session won't fix it but the failure is environmental,+ // not a poisoned conversation. Out of scope for this+ // classifier.+ name: "401 auth error",+ errMsg: `API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid api key"}}`,+ wantOK: false,+ },+ {+ // A tool surfacing a 400 from somewhere unrelated must not+ // trigger the classifier — only the combination of 400 ++ // invalid_request_error indicates a corrupted body.+ name: "tool 400 without invalid_request_error",+ errMsg: `agent tool returned status 400: not found`,+ wantOK: false,+ },+ {+ name: "empty error message",+ errMsg: "",+ wantOK: false,+ },+ {+ name: "unrelated execution error",+ errMsg: "claude execution timeout after 10m",+ wantOK: false,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ reason, ok := classifyPoisonedError(tc.errMsg)+ if ok != tc.wantOK {+ t.Fatalf("classifyPoisonedError(%q) ok=%v, want %v", tc.errMsg, ok, tc.wantOK)+ }+ if ok && reason != tc.wantReason {+ t.Fatalf("classifyPoisonedError(%q) reason=%q, want %q", tc.errMsg, reason, tc.wantReason)+ }+ })+ }+}diff --git a/server/migrations/079_backfill_api_invalid_request.down.sql b/server/migrations/079_backfill_api_invalid_request.down.sqlnew file mode 100644index 0000000000..88cf4c2670--- /dev/null+++ b/server/migrations/079_backfill_api_invalid_request.down.sql@@ -0,0 +1,10 @@+-- Reverse the backfill: reset the rows we re-classified back to the+-- legacy 'agent_error' default. The error text we use as the witness is+-- preserved on the row so the same WHERE clause still selects the same+-- set unless someone manually relabels in between.+UPDATE agent_task_queue+SET failure_reason = 'agent_error'+WHERE status = 'failed'+ AND failure_reason = 'api_invalid_request'+ AND error ILIKE '%400%'+ AND error ILIKE '%invalid_request_error%';diff --git a/server/migrations/079_backfill_api_invalid_request.up.sql b/server/migrations/079_backfill_api_invalid_request.up.sqlnew file mode 100644index 0000000000..917ef76f9f--- /dev/null+++ b/server/migrations/079_backfill_api_invalid_request.up.sql@@ -0,0 +1,18 @@+-- Backfill the api_invalid_request poisoned-session classifier introduced+-- in MUL-1921. The daemon now tags failed tasks whose error matches an+-- Anthropic 400 invalid_request_error so GetLastTaskSession excludes them+-- from the (agent_id, issue_id) resume lookup, but that change is+-- forward-only: existing failed rows still carry the default+-- failure_reason='agent_error' and the resume query falls back to them+-- on the next claim, re-poisoning every retry.+--+-- Re-classify any historical row whose error text matches the same+-- canonical shape (case-insensitive substrings "400" and+-- "invalid_request_error") so deploying this PR actually unblocks issues+-- like MUL-1918 instead of just preventing future regressions.+UPDATE agent_task_queue+SET failure_reason = 'api_invalid_request'+WHERE status = 'failed'+ AND COALESCE(failure_reason, '') = 'agent_error'+ AND error ILIKE '%400%'+ AND error ILIKE '%invalid_request_error%';diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 68e3057bb0..9625e6b8ff 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1033,7 +1033,11 @@ SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2AND (status = 'completed'- OR (status = 'failed' AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message'))+ OR (+ status = 'failed'+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request')+ AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')+ ))AND session_id IS NOT NULLORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC@@ -1068,8 +1072,19 @@ 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) when-// it detects the agent emitted a fallback marker instead of a real result.+// 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.).+//+// 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+// row that the old code wrote between migration and rollout, or a future+// error format that escapes the daemon classifier all still get filtered+// here as long as the canonical Anthropic 400 marker is present in the+// error text. Migration 079 backfills the failure_reason column itself,+// so observability stays accurate; this clause guarantees session resume+// never picks up a bad session even when failure_reason hasn't caught up.func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSessionParams) (GetLastTaskSessionRow, error) {row := q.db.QueryRow(ctx, getLastTaskSession, arg.AgentID, arg.IssueID)var i GetLastTaskSessionRowdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 0a80497d97..b6ea988ada 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -240,13 +240,28 @@ 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) when--- it detects the agent emitted a fallback marker instead of a real result.+-- 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.).+--+-- 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+-- row that the old code wrote between migration and rollout, or a future+-- error format that escapes the daemon classifier all still get filtered+-- here as long as the canonical Anthropic 400 marker is present in the+-- error text. Migration 079 backfills the failure_reason column itself,+-- so observability stays accurate; this clause guarantees session resume+-- never picks up a bad session even when failure_reason hasn't caught up.SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2AND (status = 'completed'- OR (status = 'failed' AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message'))+ OR (+ status = 'failed'+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request')+ AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')+ ))AND session_id IS NOT NULLORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC