Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(kiro): recover from oversized-history-image session resume failures
Multica Eve2294f450e80c
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.goindex e6aa8fe010..a7157d633d 100644--- a/server/cmd/server/rerun_session_test.go+++ b/server/cmd/server/rerun_session_test.go@@ -854,3 +854,209 @@ func TestEnqueueTaskForIssueDoesNotForceFreshSession(t *testing.T) {t.Fatal("expected normal enqueue to leave force_fresh_session=false")}}+++// TestGetLastTaskSessionExcludesPoisonedOriginSession is the GH #5975 core+// regression: the SAME session_id appears on an older 'completed' row (the turn+// that first baked the oversized image into history) AND a newer poisoned+// 'failed' row (a later text-only turn that resumed it and hit the same+// rejection). A row-level filter would drop the poisoned row and fall back to+// the completed row — which points at the exact same dead session. The+// per-session-latest-state selection must invalidate the whole session.+func TestGetLastTaskSessionExcludesPoisonedOriginSession(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()++ // Older completed row: the successful turn that consumed the oversized+ // screenshot and stored the session id.+ 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', 'POISON-ORIGIN', '/tmp/origin')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert completed origin task: %v", err)+ }++ // Newer poisoned row on the SAME session: a later text-only turn resumed+ // it and hit the oversized-history-image rejection.+ 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', 'POISON-ORIGIN', '/tmp/origin', 'api_invalid_request',+ 'kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=Encountered an error in the response stream: messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert poisoned resume 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 the poisoned session to be fully invalidated, but query returned %q", prior.SessionID.String)+ }+}++// TestGetLastTaskSessionFallsBackToHealthyDistinctSession asserts that while a+// poisoned session (completed origin + newer poisoned resume, same id) is+// invalidated, a DIFFERENT healthy session on the same issue is still eligible.+func TestGetLastTaskSessionFallsBackToHealthyDistinctSession(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', 'POISON-ORIGIN', '/tmp/origin')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert completed origin 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', 'POISON-ORIGIN', '/tmp/origin', 'api_invalid_request',+ 'session/prompt: Internal error (code=-32603, data=messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert poisoned resume task: %v", err)+ }+ // A separate, healthy session (distinct id) — the eligible fallback.+ 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', 'HEALTHY-DISTINCT', '/tmp/healthy')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert healthy distinct task: %v", err)+ }++ queries := db.New(testPool)+ prior, err := queries.GetLastTaskSession(ctx, db.GetLastTaskSessionParams{+ AgentID: pgtype.UUID{Bytes: parseUUIDBytes(agentID), Valid: true},+ IssueID: pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},+ })+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "HEALTHY-DISTINCT" {+ t.Fatalf("expected fallback to HEALTHY-DISTINCT, got %q", prior.SessionID.String)+ }+}++// TestGetLastTaskSessionExcludesKiroOversizedImageByText is the GH #5975+// defense-in-depth: a row that escaped the daemon classifier (still tagged+// 'agent_error', e.g. a new-server + old-daemon deploy window) must still be+// excluded on error-text shape alone via the oversized-image ILIKE clause.+func TestGetLastTaskSessionExcludesKiroOversizedImageByText(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 '1 minute', now() - interval '1 minute', 'KIRO-OVERSIZED', '/tmp/kiro', 'agent_error',+ 'kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=Encountered an error in the response stream: messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert unclassified kiro oversized 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 the oversized-image session to be filtered by text, got %q", prior.SessionID.String)+ }+}++// TestGetLastTaskSessionRestoresRecoveredSession asserts the per-session-latest+// rule is symmetric: if a session that once failed poisoned later terminates+// cleanly again (a newer 'completed' row on the same id), it becomes resumable+// once more.+func TestGetLastTaskSessionRestoresRecoveredSession(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 '2 minutes', now() - interval '2 minutes', 'RECOVER-SESS', '/tmp/recover', 'api_invalid_request',+ 'session/prompt: Internal error (code=-32603, data=messages.0.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert earlier poisoned 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)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', 'RECOVER-SESS', '/tmp/recover')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert later completed 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 != "RECOVER-SESS" {+ t.Fatalf("expected the recovered session to be resumable again, got %q", prior.SessionID.String)+ }+}+++// TestGetLastTaskSessionKeepsDimensionPhraseWithoutImageMarker is the+// review-tightening negative control: the oversized-image ILIKE now requires+// BOTH the dimension phrase AND the image-content marker, matching the Kiro+// detector / classifyPoisonedError precision. An unrelated error that merely+// mentions image dimensions (without the image.source.base64.data marker) must+// NOT be filtered — otherwise a benign failure would needlessly drop a+// resumable session.+func TestGetLastTaskSessionKeepsDimensionPhraseWithoutImageMarker(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', 'DIM-ONLY-RESUMABLE', '/tmp/dim', 'agent_error',+ 'tool reported: image dimensions exceed max allowed size: 8000 pixels while generating a thumbnail')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert dimension-phrase-only 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 != "DIM-ONLY-RESUMABLE" {+ t.Fatalf("expected the dimension-phrase-only session to stay resumable, got %q (valid=%v)", prior.SessionID.String, prior.SessionID.Valid)+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex b3fa1f45b9..be24d8db1d 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -4819,17 +4819,55 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}if shouldRetryWithFreshSession(result, task.PriorSessionID, tools, provider) {+ firstResult := resultfirstUsage := result.Usage+ firstTools := toolstaskLog.Warn("session resume failed, retrying with fresh session", "error", result.Error)++ // Rebuild cold-session context before the single retry. The prior+ // provider transcript is gone (missing, account-mismatched, or —+ // GH #5975 — carrying history the provider now refuses), so the+ // fresh process must NOT be told it is resuming a conversation:+ // - taskCtx.PriorSessionResumed=false + re-injecting the runtime+ // brief rewrites the on-disk AGENTS.md so it no longer claims+ // "You're resuming the prior session" (which file-based backends+ // 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.+ // task and taskCtx are local (runTask takes task by value), so these+ // mutations only affect the retry.execOpts.ResumeSessionID = ""- retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)- if retryErr != nil {- taskLog.Error("fresh session also failed to start", "error", retryErr)+ task.PriorSessionID = ""+ 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)} else {- result = retryResult- result.Usage = mergeUsage(firstUsage, result.Usage)- tools = retryTools+ runtimeBrief = freshBrief+ if providerNeedsInlineSystemPrompt(provider) {+ execOpts.SystemPrompt = runtimeBrief+ }+ }+ freshPrompt := freshSessionRetryPrompt(BuildPrompt(task, provider))++ retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)+ if retryErr != nil {+ taskLog.Error("fresh session also failed to start; keeping the original poisoned result", "error", retryErr)+ } else if retryResult.Status != "completed" && retryResult.SessionID == "" {+ taskLog.Warn("fresh session retry also failed without establishing a new session; keeping the original poisoned result",+ "retry_status", retryResult.Status,+ "retry_error", retryResult.Error,+ )}+ // The poisoned prior session id lives ONLY on firstResult (classified+ // unrecoverable, so GetLastTaskSession excludes it). reconcile never+ // grafts it onto the retry result: a retry that establishes a new+ // session wins with its own id; a retry that fails without a new+ // session keeps firstResult so the bad session stays excluded rather+ // than being relabeled resumable by a benign-looking second error.+ result, tools = reconcileFreshRetryResult(firstResult, firstUsage, firstTools, retryResult, retryTools, retryErr)}elapsed := time.Since(taskStart).Round(time.Second)@@ -5100,6 +5138,45 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, tooreturn result.SessionID == "" && freshSessionMayHelp(result.Error)}+// reconcileFreshRetryResult picks the authoritative result after the single+// fresh-session retry (see the retry block in runTask). Its one hard invariant:+// the poisoned prior session id — carried only on `first`, whose failure is+// classified unrecoverable so GetLastTaskSession excludes it — must NEVER be+// grafted onto the retry's result, or a later task would resume the bad+// session again and re-form the loop this fix exists to break (GH #5975 review).+//+// - retryErr != nil: the fresh attempt never produced a result. Keep `first`+// so the poisoned session stays recorded as unrecoverable.+// - retry established a new session id: it fully wins, carrying its OWN id.+// A benign retry failure on a real new session is fine to record — it is+// not the poisoned one.+// - retry completed without a session id (e.g. all work via tools): take it,+// but keep the id EMPTY. Never resurrect the poisoned id as a resumable+// success.+// - retry failed AND established no new session: keep `first`. Adopting the+// second result here is exactly the bug — a second error lacking the+// oversized-image markers would be classified resume-safe and the poisoned+// id (were it attached) would be re-selected. We keep the unrecoverable+// first result and only merge usage.+//+// Usage is merged across both attempts in every branch so billing is complete.+func reconcileFreshRetryResult(first agent.Result, firstUsage map[string]agent.TokenUsage, firstTools int32, retry agent.Result, retryTools int32, retryErr error) (agent.Result, int32) {+ switch {+ case retryErr != nil:+ first.Usage = firstUsage+ return first, firstTools+ case retry.SessionID != "":+ retry.Usage = mergeUsage(firstUsage, retry.Usage)+ return retry, retryTools+ case retry.Status == "completed":+ retry.Usage = mergeUsage(firstUsage, retry.Usage)+ return retry, retryTools+ default:+ first.Usage = mergeUsage(firstUsage, retry.Usage)+ return first, firstTools+ }+}+// freshSessionMayHelp reports whether restarting the conversation could// plausibly fix errText. It answers "is this failure about the session at// all?", so every reason with a defined non-session remedy — wait, back off,diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 5b73478a96..9f82eade95 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -636,6 +636,131 @@ 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) {+ t.Parallel()++ base := BuildPrompt(Task{+ IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",+ TriggerCommentID: "c0ffee00-0000-0000-0000-000000000000",+ Agent: &AgentData{Name: "Local Kiro"},+ }, "kiro")++ got := freshSessionRetryPrompt(base)++ // 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)+ }+ }+ if !strings.HasSuffix(got, base) {+ t.Fatal("fresh-retry prompt must preserve the current prompt verbatim as its suffix")+ }+ if strings.Index(got, "brand-new session") > strings.Index(got, base) {+ t.Fatal("context-loss disclosure must precede the preserved prompt")+ }+}++// TestReconcileFreshRetryResult locks the GH #5975 review must-fix: the+// poisoned prior session id (carried only on the first result) must never be+// grafted onto the fresh retry's result, and a fresh retry that does not+// establish a new session must not relabel the poisoned session as resumable.+func TestReconcileFreshRetryResult(t *testing.T) {+ t.Parallel()++ firstUsage := map[string]agent.TokenUsage{"m1": {InputTokens: 5}}+ // The first (poisoned) result keeps its id for classification/auditing;+ // its failure is classified unrecoverable elsewhere.+ first := agent.Result{Status: "failed", Error: "oversized history image", SessionID: "ses_poisoned", Usage: firstUsage}+ const firstTools = int32(0)++ tests := []struct {+ name string+ retry agent.Result+ retryTools int32+ retryErr error+ wantStatus string+ wantSession string+ wantTools int32+ }{+ {+ // Fresh attempt never produced a result — keep the poisoned first+ // result so the bad session stays recorded as unrecoverable.+ name: "retryErr keeps first poisoned result",+ retry: agent.Result{},+ retryErr: context.DeadlineExceeded,+ wantStatus: "failed",+ wantSession: "ses_poisoned",+ wantTools: firstTools,+ },+ {+ // Fresh session established — new result wins with its OWN id.+ name: "new session id wins",+ retry: agent.Result{Status: "completed", Output: "done", SessionID: "ses_new", Usage: map[string]agent.TokenUsage{"m1": {OutputTokens: 7}}},+ retryTools: 2,+ wantStatus: "completed",+ wantSession: "ses_new",+ wantTools: 2,+ },+ {+ // Fresh attempt failed/timed out WITHOUT a new session id — the+ // poisoned id must NOT be resurrected; keep the first result.+ name: "failed retry without new session keeps first",+ retry: agent.Result{Status: "failed", Error: "connection refused", SessionID: ""},+ retryTools: 0,+ wantStatus: "failed",+ wantSession: "ses_poisoned",+ wantTools: firstTools,+ },+ {+ name: "timeout retry without new session keeps first",+ retry: agent.Result{Status: "timeout", Error: "timed out", SessionID: ""},+ wantStatus: "failed",+ wantSession: "ses_poisoned",+ wantTools: firstTools,+ },+ {+ // Fresh attempt succeeded but produced no resumable session id —+ // take the success but keep the id EMPTY, never the poisoned one.+ name: "completed retry with empty session id keeps empty id",+ retry: agent.Result{Status: "completed", Output: "ok", SessionID: "", Usage: map[string]agent.TokenUsage{"m1": {OutputTokens: 3}}},+ retryTools: 1,+ wantStatus: "completed",+ wantSession: "",+ wantTools: 1,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ got, gotTools := reconcileFreshRetryResult(first, firstUsage, firstTools, tt.retry, tt.retryTools, tt.retryErr)+ if got.Status != tt.wantStatus {+ t.Fatalf("status = %q, want %q", got.Status, tt.wantStatus)+ }+ if got.SessionID != tt.wantSession {+ t.Fatalf("session id = %q, want %q (the poisoned id must never leak onto a resumable result)", got.SessionID, tt.wantSession)+ }+ if gotTools != tt.wantTools {+ t.Fatalf("tools = %d, want %d", gotTools, tt.wantTools)+ }+ // Usage is always merged so billing is complete.+ if got.Usage["m1"].InputTokens != 5 {+ t.Fatalf("expected first-attempt input usage to be preserved, got %+v", got.Usage["m1"])+ }+ })+ }+}+func TestBuildPromptNoIssueDetails(t *testing.T) {t.Parallel()@@ -2177,6 +2302,38 @@ func TestShouldRetryWithFreshSession(t *testing.T) {priorSessionID: "stale-id",want: false,},+ {+ // GH #5975: the Kiro backend reports ResumeRejected for an+ // oversized historical image while KEEPING the poisoned session+ // id for auditing. The gate reads the boolean, not an empty id,+ // so a non-empty SessionID must still allow the fresh retry.+ name: "kiro oversized history image retries despite non-empty session id",+ result: agent.Result{+ Status: "failed",+ Error: "kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)",+ SessionID: "ses_poisoned",+ ResumeRejected: true,+ },+ priorSessionID: "ses_poisoned",+ provider: "kiro",+ want: true,+ },+ {+ // Same oversized-image rejection, but a tool already ran this+ // attempt — the retry could duplicate external side effects+ // (comments, commits), so the single-retry gate must refuse.+ name: "kiro oversized history image after a tool ran never retries",+ result: agent.Result{+ Status: "failed",+ Error: "kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)",+ SessionID: "ses_poisoned",+ ResumeRejected: true,+ },+ priorSessionID: "ses_poisoned",+ tools: 1,+ provider: "kiro",+ want: false,+ },}for _, tt := range tests {diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.goindex d168bf6450..7aa28e67b3 100644--- a/server/internal/daemon/poisoned.go+++ b/server/internal/daemon/poisoned.go@@ -106,6 +106,20 @@ func classifyPoisonedError(errMsg string) (string, bool) {return "", false}lowered := strings.ToLower(errMsg)+ // Kiro/ACP replays images baked into a resumed conversation's history;+ // one exceeding the provider's max pixel dimensions is rejected on every+ // session/prompt and cannot be resumed away (GH #5975). The daemon's+ // in-task fresh-session retry recovers the CURRENT turn, but this marks+ // the conversation resume-unsafe so GetLastTaskSession excludes it and no+ // later task re-selects the poisoned session. The offending+ // messages[n].content[m] path and the pixel limit stay in the surfaced+ // error; base64 payloads are never logged. Requiring the image-content+ // marker alongside the dimension phrase keeps this narrow — an unrelated+ // error mentioning dimensions won't trip it.+ if strings.Contains(lowered, "image dimensions exceed max allowed size") &&+ strings.Contains(lowered, "image.source.base64.data") {+ return FailureReasonAPIInvalidRequest, true+ }// 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. Thediff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.goindex 6ce5b7752d..3e653b9a69 100644--- a/server/internal/daemon/poisoned_test.go+++ b/server/internal/daemon/poisoned_test.go@@ -157,6 +157,32 @@ func TestClassifyPoisonedError(t *testing.T) {errMsg: "claude execution timeout after 10m",wantOK: false,},+ {+ // GH #5975: a Kiro resume rejected because the session+ // history replays an image over the provider's max pixel+ // dimensions. The conversation is unresumable, so it must be+ // classified api_invalid_request even though the error is a+ // -32603 "Internal error" (no 400 / invalid_request_error).+ name: "kiro oversized history image",+ errMsg: `kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=Encountered an error in the response stream: messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels)`,+ wantOK: true,+ wantReason: FailureReasonAPIInvalidRequest,+ },+ {+ // A plain -32603 "Internal error" (the transient close+ // handshake) shares the code but names neither image marker,+ // so it must NOT be classified as poisoning.+ name: "plain kiro internal error is not poisoning",+ errMsg: `kiro session/prompt failed: session/prompt: Internal error (code=-32603, data=Kiro failed to generate a response)`,+ wantOK: false,+ },+ {+ // The dimension phrase alone (without the image-content+ // marker) is too weak to classify as a poisoned history.+ name: "dimension phrase without image-content marker",+ errMsg: `some tool reported: image dimensions exceed max allowed size: 8000 pixels`,+ wantOK: false,+ },}for _, tc := range cases {diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex ba340f07f6..4e97c694d5 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -7,6 +7,20 @@ 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+}+// BuildPrompt constructs the task prompt for an agent CLI.// Keep this minimal — detailed instructions live in CLAUDE.md / AGENTS.md// injected by execenv.InjectRuntimeConfig. The provider string is threadeddiff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 66ae73937d..1023be1b7c 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -166,9 +166,15 @@ type Result struct {SessionID stringUsage map[string]TokenUsage // keyed by model name// ResumeRejected is positive evidence that this run's requested resume- // was itself refused — the transcript is gone, or the session belongs to- // another provider account. Only a refused resume can be cured by starting- // over, so it is what the daemon's fresh-session fallback looks for first.+ // was itself refused — the transcript is gone, the session belongs to+ // another provider account, OR the session still exists but its history+ // can no longer be replayed to the provider (e.g. GH #5975: a stored+ // image now exceeds the provider's max dimensions, so every resumed+ // session/prompt is rejected before the turn runs). What unites these is+ // that the resume CANNOT continue and only starting over can cure it, so+ // it is what the daemon's fresh-session fallback looks for first. Note the+ // last case keeps a non-empty SessionID (the id is real, only its history+ // is unusable) — the daemon gates on this boolean, not an empty id.//// false is NOT evidence of the opposite. For a backend listed in// ResumeRejectionUndetectable it means "could not tell"; for every otherdiff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex fff9ca4c98..b513a838d6 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -397,6 +397,24 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio)sessionID = ""resumeRejected = true+ } else if opts.ResumeSessionID != "" && isKiroOversizedHistoryImage(err) {+ // A resumed session whose history contains an image+ // exceeding the provider's max pixel dimensions replays+ // that image on every session/prompt and is rejected+ // before the current turn runs (GH #5975). Unlike a+ // missing session the transcript still exists, so this is+ // permanent for the resume path: only a fresh session+ // without the resume id can recover. Signal+ // ResumeRejected so the daemon retries once from a cold+ // session; keep the (poisoned) session id on the result+ // so it stays visible for auditing — the daemon gates the+ // retry on the boolean, not on an empty id, and a+ // successful fresh retry overwrites it with the new id.+ b.cfg.Logger.Warn("resumed session has an oversized historical image the provider rejects; signaling resume rejection so the daemon retries with a fresh session",+ "backend", "kiro",+ "session_id", sessionID,+ )+ resumeRejected = true}}} else {@@ -480,6 +498,36 @@ func isKiroGoalCompleteCloseError(err error) bool {return strings.Contains(strings.ToLower(rpcErr.Data), "failed to generate a response")}+// isKiroOversizedHistoryImage reports whether err is Kiro/upstream rejecting a+// resumed conversation because an image already baked into the session history+// exceeds the provider's maximum allowed pixel dimensions. Kiro surfaces this+// at session/prompt time as a -32603 whose `data` names the offending+// messages[n].content[m].image.source.base64.data block and the dimension+// limit (GH #5975), e.g.:+//+// session/prompt: Internal error (code=-32603, data=Encountered an error in+// the response stream: messages.14.content.0.image.source.base64.data: At+// least one of the image dimensions exceed max allowed size: 8000 pixels)+//+// Both markers must be present so an unrelated -32603 — a transient "failed to+// generate a response" close, or a mid-command crash producing the same+// result-less shape — is never misread as a permanent history incompatibility.+// This is deliberately distinct from isACPSessionNotFound: the session exists,+// only its historical multimodal content is unusable, so the recovery is a+// fresh session started WITHOUT the resume id rather than clearing a dead id.+func isKiroOversizedHistoryImage(err error) bool {+ var rpcErr *acpRPCError+ if !errors.As(err, &rpcErr) {+ return false+ }+ if rpcErr.Method != "session/prompt" || rpcErr.Code != -32603 {+ return false+ }+ data := strings.ToLower(rpcErr.Data)+ return strings.Contains(data, "image.source.base64.data") &&+ strings.Contains(data, "image dimensions exceed max allowed size")+}+// isKiroIssueCommentAddTool reports whether a tool-use message is a// `multica issue comment add` invocation. It keys purely off the command// payload, not the normalized tool name: GPT-5.6 Sol adapters may title thediff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.goindex e284567c85..e955f2b18e 100644--- a/server/pkg/agent/kiro_test.go+++ b/server/pkg/agent/kiro_test.go@@ -1103,3 +1103,178 @@ func TestKiroLoadIncludesMcpServersFromConfig(t *testing.T) {t.Fatalf("session/load.mcpServers: got %v, want one entry named fetch", servers)}}+++// TestIsKiroOversizedHistoryImage pins the detector for the GH #5975 shape: a+// resumed conversation whose history replays an image exceeding the provider's+// max pixel dimensions, rejected at session/prompt as a -32603 that names the+// image-content path AND the dimension limit. Both markers are required so an+// ordinary -32603 (the "failed to generate a response" close, a mid-command+// crash) is never misread as a permanent history incompatibility.+func TestIsKiroOversizedHistoryImage(t *testing.T) {+ t.Parallel()++ const oversizedData = "Encountered an error in the response stream: messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels"++ tests := []struct {+ name string+ err error+ want bool+ }{+ {+ name: "oversized history image at session/prompt",+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: oversizedData},+ want: true,+ },+ {+ name: "goal-complete close error is not this",+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: "Kiro failed to generate a response"},+ want: false,+ },+ {+ name: "session not found is not this",+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: "No session found with id ses_x"},+ want: false,+ },+ {+ name: "dimension phrase without the image-content marker does not match",+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: "image dimensions exceed max allowed size: 8000 pixels"},+ want: false,+ },+ {+ name: "wrong method does not match",+ err: &acpRPCError{Method: "session/load", Code: -32603, Message: "Internal error", Data: oversizedData},+ want: false,+ },+ {+ name: "wrong code does not match",+ err: &acpRPCError{Method: "session/prompt", Code: -32602, Message: "Invalid params", Data: oversizedData},+ want: false,+ },+ {+ name: "non-acp error does not match",+ err: os.ErrNotExist,+ want: false,+ },+ {+ name: "nil error does not match",+ err: nil,+ want: false,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isKiroOversizedHistoryImage(tt.err); got != tt.want {+ t.Fatalf("isKiroOversizedHistoryImage(%v) = %v, want %v", tt.err, got, tt.want)+ }+ })+ }+}++// fakeKiroACPOversizedHistoryImageScript answers initialize + session/new ++// session/load, then rejects every session/prompt with the GH #5975 oversized+// historical-image -32603.+func fakeKiroACPOversizedHistoryImageScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fresh"}}\n' "$id"+ ;;+ *'"method":"session/load"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"Encountered an error in the response stream: messages.14.content.0.image.source.base64.data: At least one of the image dimensions exceed max allowed size: 8000 pixels"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func runKiroScriptWithOpts(t *testing.T, script string, opts ExecOptions) Result {+ t.Helper()+ fakePath := filepath.Join(t.TempDir(), "kiro-cli")+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new kiro backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ if opts.Timeout == 0 {+ opts.Timeout = 5 * time.Second+ }+ session, err := backend.Execute(ctx, "prompt-ignored", opts)+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ return result+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ return Result{}+ }+}++// TestKiroResumedOversizedHistoryImageSignalsResumeRejected asserts a RESUMED+// session that hits the oversized historical-image rejection fails, reports+// ResumeRejected=true so the daemon retries once from a fresh session, and+// keeps the poisoned session id for auditing/persistent invalidation.+func TestKiroResumedOversizedHistoryImageSignalsResumeRejected(t *testing.T) {+ t.Parallel()++ result := runKiroScriptWithOpts(t, fakeKiroACPOversizedHistoryImageScript(), ExecOptions{+ ResumeSessionID: "ses_poisoned",+ })++ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !result.ResumeRejected {+ t.Fatalf("expected ResumeRejected=true for oversized-history-image resume failure, got false (error=%q)", result.Error)+ }+ if result.SessionID != "ses_poisoned" {+ t.Fatalf("expected the poisoned session id to be preserved for auditing, got %q", result.SessionID)+ }+ if !strings.Contains(result.Error, "image dimensions exceed max allowed size") {+ t.Fatalf("expected the offending-image error to be surfaced, got %q", result.Error)+ }+}++// TestKiroFreshOversizedHistoryImageDoesNotSignalResumeRejected asserts the+// SAME error on a fresh (non-resumed) session does NOT set ResumeRejected — a+// fresh session cannot itself be "resume rejected", and retrying it again would+// be pointless. This guards the opts.ResumeSessionID gate on the branch.+func TestKiroFreshOversizedHistoryImageDoesNotSignalResumeRejected(t *testing.T) {+ t.Parallel()++ result := runKiroScriptWithOpts(t, fakeKiroACPOversizedHistoryImageScript(), ExecOptions{})++ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if result.ResumeRejected {+ t.Fatal("expected ResumeRejected=false on a fresh session, got true")+ }+ if result.SessionID != "ses_fresh" {+ t.Fatalf("expected the fresh session id, got %q", result.SessionID)+ }+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 20027d7065..443b9be2ad 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -2778,18 +2778,27 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI}const getLastTaskSession = `-- name: GetLastTaskSession :one-SELECT session_id, work_dir, runtime_id FROM agent_task_queue-WHERE agent_id = $1 AND issue_id = $2- AND (+WITH latest_per_session AS (+ SELECT DISTINCT ON (session_id)+ session_id, work_dir, runtime_id, status, failure_reason, error,+ COALESCE(completed_at, started_at, dispatched_at, created_at) AS terminal_at+ FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2+ AND session_id IS NOT NULL+ AND status IN ('completed', 'failed')+ ORDER BY session_id, COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+)+SELECT session_id, work_dir, runtime_id FROM latest_per_session+WHERE (status = 'completed'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 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 session_id IS NOT NULL-ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+ORDER BY terminal_at DESCLIMIT 1`@@ -2843,6 +2852,30 @@ type GetLastTaskSessionRow struct {// 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.+//+// Selection is per-session, not per-row: we first reduce to the single most+// recent terminal row FOR EACH session_id (DISTINCT ON), then apply the+// resume-unsafe filter. This closes a poisoning wormhole (GH #5975): when the+// SAME session_id has both an older 'completed' row (the turn that first baked+// in the bad history) and a newer poisoned 'failed' row, a plain row-level+// filter would drop the poisoned row and happily fall back to the older+// completed row — which points at the exact same dead session. Judging by each+// session's LATEST terminal state instead means:+// - a newer poisoned row invalidates the whole session, older completed rows+// included;+// - a different, healthy session (distinct id) is still eligible as a+// fallback;+// - if that same id later terminates cleanly again, the newer completed row+// restores its resumability.+//+// The oversized-image ILIKE (dimension phrase AND image.source.base64.data) is+// the GH #5975 analogue of the api_invalid_request defense-in-depth above: a+// Kiro/ACP resume rejected for an oversized historical image is classified+// 'api_invalid_request' at write time, but this text clause also blocks a+// legacy/unclassified row (or a new-server + old-daemon deploy window) from+// resuming the poisoned session. Both markers are required so the clause stays+// exactly as narrow as classifyPoisonedError and the Kiro detector — an+// unrelated error that only mentions image dimensions is NOT excluded.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 ae4e54575e..79c30184b5 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -719,18 +719,51 @@ RETURNING *;-- 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_queue-WHERE agent_id = $1 AND issue_id = $2- AND (+--+-- Selection is per-session, not per-row: we first reduce to the single most+-- recent terminal row FOR EACH session_id (DISTINCT ON), then apply the+-- resume-unsafe filter. This closes a poisoning wormhole (GH #5975): when the+-- SAME session_id has both an older 'completed' row (the turn that first baked+-- in the bad history) and a newer poisoned 'failed' row, a plain row-level+-- filter would drop the poisoned row and happily fall back to the older+-- completed row — which points at the exact same dead session. Judging by each+-- session's LATEST terminal state instead means:+-- - a newer poisoned row invalidates the whole session, older completed rows+-- included;+-- - a different, healthy session (distinct id) is still eligible as a+-- fallback;+-- - if that same id later terminates cleanly again, the newer completed row+-- restores its resumability.+--+-- The oversized-image ILIKE (dimension phrase AND image.source.base64.data) is+-- the GH #5975 analogue of the api_invalid_request defense-in-depth above: a+-- Kiro/ACP resume rejected for an oversized historical image is classified+-- 'api_invalid_request' at write time, but this text clause also blocks a+-- legacy/unclassified row (or a new-server + old-daemon deploy window) from+-- resuming the poisoned session. Both markers are required so the clause stays+-- exactly as narrow as classifyPoisonedError and the Kiro detector — an+-- unrelated error that only mentions image dimensions is NOT excluded.+WITH latest_per_session AS (+ SELECT DISTINCT ON (session_id)+ session_id, work_dir, runtime_id, status, failure_reason, error,+ COALESCE(completed_at, started_at, dispatched_at, created_at) AS terminal_at+ FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2+ AND session_id IS NOT NULL+ AND status IN ('completed', 'failed')+ ORDER BY session_id, COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+)+SELECT session_id, work_dir, runtime_id FROM latest_per_session+WHERE (status = 'completed'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 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 session_id IS NOT NULL-ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+ORDER BY terminal_at DESCLIMIT 1;-- name: GetLatestTaskRolloutMissing :one