Skip to content

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

Go

MUL-5426: fix(daemon): retire sessions whose history the provider refuses to replay (#6083)

Bohan Jiang30318b79bce6
diff --git a/server/cmd/server/autopilot_listeners_test.go b/server/cmd/server/autopilot_listeners_test.go
index 1251298bd1..d688fd0d43 100644
--- a/server/cmd/server/autopilot_listeners_test.go
+++ b/server/cmd/server/autopilot_listeners_test.go
@@ -37,7 +37,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
{
name: "completed",
finalize: func(task db.AgentTaskQueue) {
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
},
@@ -47,7 +47,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
{
name: "failed",
finalize: func(task db.AgentTaskQueue) {
- if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "agent_error", false); err != nil {
+ if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "agent_error", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
},
@@ -230,7 +230,7 @@ func TestAutopilotCreateIssueTaskNoProgressFailureUpdatesRun(t *testing.T) {
runTaskWithBudget(t, f.queries, f.taskID, 1)
const errMsg = "codex app-server no progress timeout after 30s"
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "codex_semantic_inactivity", false); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "codex_semantic_inactivity", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
@@ -258,7 +258,7 @@ func TestAutopilotCreateIssueTaskAgentErrorFailureUpdatesRun(t *testing.T) {
// agent_error is not in retryableReasons, so the first terminal failure is
// final — the run must fail carrying the agent's error text.
const errMsg = "build failed: ./pkg/foo: undefined: Bar"
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "agent_error", false); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "agent_error", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
@@ -287,7 +287,7 @@ func TestAutopilotCreateIssueTaskRetryPendingKeepsRunOpen(t *testing.T) {
// timeout is retryable, so FailTask enqueues a fresh attempt before it
// broadcasts the failure event.
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime went offline", "", "", "timeout", false); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime went offline", "", "", "timeout", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/cmd/server/quick_create_subscriber_test.go b/server/cmd/server/quick_create_subscriber_test.go
index 23b078e1eb..f5d5c7fd40 100644
--- a/server/cmd/server/quick_create_subscriber_test.go
+++ b/server/cmd/server/quick_create_subscriber_test.go
@@ -85,7 +85,7 @@ func TestQuickCreateCompletion_SubscribesRequester(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issue.ID)
})
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -142,7 +142,7 @@ func TestQuickCreateFailure_DoesNotSubscribeRequester(t *testing.T) {
// No issue with origin_type=quick_create + this task id exists. Completion
// hits the failure branch and writes a failure inbox; no subscriber row.
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -214,7 +214,7 @@ func TestQuickCreateFailure_SurfacesAgentOutput(t *testing.T) {
// only output (per the quick-create prompt contract).
const agentErr = "Error: an active issue already exists: JKY-30 (blocked). Pass --allow-duplicate to override."
result, _ := json.Marshal(map[string]any{"output": agentErr})
- if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -296,7 +296,7 @@ func TestQuickCreateLookupFault_WritesUnconfirmedInbox(t *testing.T) {
result, _ := json.Marshal(map[string]any{
"output": "Error: an active issue already exists: JKY-30 (blocked).",
})
- if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {
+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -368,7 +368,7 @@ func TestQuickCreateFailure_RedactsAgentOutput(t *testing.T) {
result, _ := json.Marshal(map[string]any{
"output": "Error: create failed while authenticating with " + fakeToken,
})
- if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -442,7 +442,7 @@ func TestQuickCreateLookupCancelled_StillWritesUnconfirmedInbox(t *testing.T) {
)
result, _ := json.Marshal(map[string]any{"output": "Error: something went wrong"})
- if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {
+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if ctx.Err() == nil {
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index a7157d633d..ebbcae8a10 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -2,8 +2,10 @@ package main
import (
"context"
+ "errors"
"testing"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
@@ -13,6 +15,25 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+// requireSessionExcluded asserts a resume lookup found nothing BECAUSE the
+// session was excluded — not because the query itself blew up.
+//
+// The bare `if err == nil && prior.SessionID.Valid` form these tests shared is
+// false-green: any real fault (undefined column, syntax error, dead
+// connection) makes err non-nil, the condition false, and the test pass. Run
+// against a database missing this PR's new column, the exclusion tests
+// reported PASS on a SQLSTATE 42703. Requiring pgx.ErrNoRows specifically is
+// what makes a passing test mean "the filter worked".
+func requireSessionExcluded(t *testing.T, sessionID pgtype.Text, err error) {
+ t.Helper()
+ if err == nil {
+ t.Fatalf("expected the session to be excluded, but the lookup returned %q", sessionID.String)
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("lookup failed for an unrelated reason, so this test proves nothing: %v", err)
+ }
+}
+
// setupRerunTestFixture creates an issue assigned to the integration test
// agent and returns (issueID, agentID, runtimeID).
func setupRerunTestFixture(t *testing.T) (string, string, string) {
@@ -156,6 +177,75 @@ func TestGetLastTaskSessionFallsBackWhenLatestSessionBlanked(t *testing.T) {
}
}
+// TestGetLastTaskSessionExcludesEmptyHistoryMessage is the SQL half of the
+// GH #6066 fix. The daemon now classifies an empty-message rejection as
+// api_invalid_request, but daemons upgrade on their own cadence — a self-host
+// install still running an older one writes agent_error.unknown, and only the
+// query's text guard keeps the next task off the poisoned session. This drives
+// that exact row shape.
+func TestGetLastTaskSessionExcludesEmptyHistoryMessage(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 row an un-upgraded daemon writes for GH #6066: the reason is the
+ // catchall, so the failure_reason blacklist does not fire.
+ 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', 'POISONED-EMPTY-MSG', '/tmp/poisoned', 'agent_error.unknown',
+ 'Invalid request: the message at position 37 with role ''assistant'' must not be empty')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert 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},
+ })
+ requireSessionExcluded(t, prior.SessionID, err)
+}
+
+// TestGetLastTaskSessionKeepsToolEmptinessError is the narrowness half: the
+// text guard must not swallow a healthy session because some tool complained
+// that a field was empty. A false positive here silently drops conversation
+// context on every follow-up, which is worse than the bug it guards against.
+func TestGetLastTaskSessionKeepsToolEmptinessError(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', 'HEALTHY-SESSION', '/tmp/healthy', 'agent_error.unknown',
+ 'validation error: field must not be empty')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert 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-SESSION" {
+ t.Fatalf("a tool emptiness error must not retire the session, got %+v", prior.SessionID)
+ }
+}
+
// TestCompletedTaskRolloutMissingWithholdsAndDisclosesGap is the cross-layer
// regression for MUL-5305 Must-fix 1: a COMPLETED follow-up whose Codex rollout
// is missing (the #5934 case — the user waits for each turn to finish) must (1)
@@ -316,9 +406,7 @@ func TestGetLastTaskSessionFallbackPoisonedClassifier(t *testing.T) {
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, got %q", prior.SessionID.String)
- }
+ requireSessionExcluded(t, prior.SessionID, err)
}
// TestGetLastTaskSessionExcludesAPIInvalidRequest covers the MUL-1921
@@ -349,9 +437,7 @@ func TestGetLastTaskSessionExcludesAPIInvalidRequest(t *testing.T) {
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)
- }
+ requireSessionExcluded(t, prior.SessionID, err)
}
// TestGetLastTaskSessionExcludesCodexSemanticInactivity covers Codex
@@ -533,9 +619,7 @@ func TestGetLastTaskSessionExcludesLegacyAPI400(t *testing.T) {
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)
- }
+ requireSessionExcluded(t, prior.SessionID, err)
}
// TestGetLastTaskSessionKeepsBenignAgentErrorWithSession asserts the
@@ -855,7 +939,6 @@ func TestEnqueueTaskForIssueDoesNotForceFreshSession(t *testing.T) {
}
}
-
// 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
@@ -897,9 +980,7 @@ func TestGetLastTaskSessionExcludesPoisonedOriginSession(t *testing.T) {
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)
- }
+ requireSessionExcluded(t, prior.SessionID, err)
}
// TestGetLastTaskSessionFallsBackToHealthyDistinctSession asserts that while a
@@ -976,9 +1057,7 @@ func TestGetLastTaskSessionExcludesKiroOversizedImageByText(t *testing.T) {
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)
- }
+ requireSessionExcluded(t, prior.SessionID, err)
}
// TestGetLastTaskSessionRestoresRecoveredSession asserts the per-session-latest
@@ -1022,7 +1101,6 @@ func TestGetLastTaskSessionRestoresRecoveredSession(t *testing.T) {
}
}
-
// 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
diff --git a/server/cmd/server/retired_session_test.go b/server/cmd/server/retired_session_test.go
new file mode 100644
index 0000000000..3065b4cdfe
--- /dev/null
+++ b/server/cmd/server/retired_session_test.go
@@ -0,0 +1,263 @@
+package main
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// newPoisonTestChatSession creates a chat session for the retired-session
+// regressions and registers its cleanup.
+func newPoisonTestChatSession(t *testing.T, agentID, runtimeID, title string) string {
+ t.Helper()
+ ctx := context.Background()
+ var chatSessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, title, runtimeID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("insert chat_session: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID)
+ testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+ return chatSessionID
+}
+
+// TestGetLastChatTaskSessionDoesNotResurrectFromOlderCompletedRow is the Chat
+// half of the GH #5975 wormhole, which the issue query closed and the chat
+// query never did. Task A completed on session S; task B then resumed S, hit
+// the poisoned history and failed. A row-level filter drops B and falls back to
+// A — same dead session, now looking perfectly healthy. Judging each session by
+// its LATEST terminal state is what stops that.
+func TestGetLastChatTaskSessionDoesNotResurrectFromOlderCompletedRow(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "poison-resurrect")
+ 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', 'POISONED-CHAT', '/tmp/chat')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert task A: %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', 'POISONED-CHAT', '/tmp/chat', 'api_invalid_request',
+ 'Invalid request: the message at position 37 with role ''assistant'' must not be empty')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert task B: %v", err)
+ }
+
+ queries := db.New(testPool)
+ prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ requireSessionExcluded(t, prior.SessionID, err)
+}
+
+// TestGetLastChatTaskSessionKeepsHealthyDistinctSession is the narrowness
+// counterpart: retiring one session must not cost the chat its memory of a
+// genuinely different, healthy one.
+func TestGetLastChatTaskSessionKeepsHealthyDistinctSession(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "poison-distinct")
+ 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, failure_reason, error)
+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '2 minutes', now() - interval '2 minutes', 'CHAT-DEAD', '/tmp/chat', 'api_invalid_request',
+ 'Invalid request: the message at position 37 with role ''assistant'' must not be empty')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert poisoned 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)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', 'CHAT-HEALTHY', '/tmp/chat')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert healthy task: %v", err)
+ }
+
+ queries := db.New(testPool)
+ prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ if err != nil {
+ t.Fatalf("GetLastChatTaskSession failed: %v", err)
+ }
+ if !prior.SessionID.Valid || prior.SessionID.String != "CHAT-HEALTHY" {
+ t.Fatalf("expected the healthy session to remain resumable, got %+v", prior.SessionID)
+ }
+}
+
+// TestRetiredSessionExcludedFromIssueResume covers the case the poison filters
+// structurally cannot see (GH #6066): a fresh-session retry that SUCCEEDS. The
+// recovered task is 'completed' and carries no failure to classify, so the only
+// trace of the abandoned session is retired_session_id — without it, the older
+// completed row still pointing at that session hands it straight back.
+func TestRetiredSessionExcludedFromIssueResume(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()
+
+ // Task A: an ordinary successful turn on session S.
+ 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', 'RETIRED-S', '/tmp/wd')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert task A: %v", err)
+ }
+ // Task B: resumed S, found it unresumable, retried fresh and succeeded
+ // without the backend emitting a new 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, retired_session_id)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', NULL, '/tmp/wd', 'RETIRED-S')
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert task B: %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)
+}
+
+// TestRetiredSessionExcludedFromChatResume is the chat mirror of the above.
+func TestRetiredSessionExcludedFromChatResume(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "poison-retired")
+ 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', 'RETIRED-CHAT-S', '/tmp/chat')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert task A: %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, retired_session_id)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', NULL, '/tmp/chat', 'RETIRED-CHAT-S')
+ `, agentID, runtimeID, chatSessionID); err != nil {
+ t.Fatalf("insert task B: %v", err)
+ }
+
+ queries := db.New(testPool)
+ prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ requireSessionExcluded(t, prior.SessionID, err)
+}
+
+// TestFailTaskClearsPoisonedChatPointer covers the bypass that made the chat
+// SQL guard unreachable (GH #6066). The claim handler reads
+// chat_session.session_id FIRST and only consults GetLastChatTaskSession when
+// it is empty, so a poisoned pointer there is resumed no matter what the query
+// filters. Declining to OVERWRITE the pointer — the old behaviour — left it in
+// place; the fail transaction has to actively clear it.
+func TestFailTaskClearsPoisonedChatPointer(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "poison-pointer")
+ ctx := context.Background()
+
+ // The last good turn pinned S as the chat-level resume pointer.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE chat_session SET session_id = 'CHAT-PTR-S', runtime_id = $2 WHERE id = $1`,
+ chatSessionID, runtimeID); err != nil {
+ t.Fatalf("pin chat pointer: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at, session_id, work_dir)
+ VALUES ($1, $2, $3, 'running', 0, now(), 'CHAT-PTR-S', '/tmp/chat')
+ RETURNING id::text
+ `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {
+ t.Fatalf("insert running task: %v", err)
+ }
+
+ queries := db.New(testPool)
+ taskSvc := service.NewTaskService(queries, testPool, nil, events.New())
+
+ // The un-upgraded-daemon shape: catchall reason, poisoning only in the text.
+ if _, err := taskSvc.FailTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(taskID), Valid: true},
+ "Invalid request: the message at position 37 with role 'assistant' must not be empty",
+ "CHAT-PTR-S", "/tmp/chat", "agent_error.unknown", false, ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+
+ var pointer *string
+ if err := testPool.QueryRow(ctx, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer); err != nil {
+ t.Fatalf("read chat pointer: %v", err)
+ }
+ if pointer != nil {
+ t.Fatalf("poisoned chat pointer must be cleared, still %q", *pointer)
+ }
+}
+
+// TestFailTaskKeepsChatPointerOnTransientFailure is the narrowness guard: a
+// transient failure must keep the pointer, because resuming is exactly how the
+// conversation survives a blip.
+func TestFailTaskKeepsChatPointerOnTransientFailure(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ _, agentID, runtimeID := setupRerunTestFixture(t)
+ chatSessionID := newPoisonTestChatSession(t, agentID, runtimeID, "transient-pointer")
+ ctx := context.Background()
+
+ if _, err := testPool.Exec(ctx,
+ `UPDATE chat_session SET session_id = 'CHAT-KEEP-S', runtime_id = $2 WHERE id = $1`,
+ chatSessionID, runtimeID); err != nil {
+ t.Fatalf("pin chat pointer: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at, session_id, work_dir)
+ VALUES ($1, $2, $3, 'running', 0, now(), 'CHAT-KEEP-S', '/tmp/chat')
+ RETURNING id::text
+ `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {
+ t.Fatalf("insert running task: %v", err)
+ }
+
+ queries := db.New(testPool)
+ taskSvc := service.NewTaskService(queries, testPool, nil, events.New())
+
+ if _, err := taskSvc.FailTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(taskID), Valid: true},
+ "Connection closed mid-response", "CHAT-KEEP-S", "/tmp/chat",
+ "agent_error.provider_network", false, ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+
+ var pointer *string
+ if err := testPool.QueryRow(ctx, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer); err != nil {
+ t.Fatalf("read chat pointer: %v", err)
+ }
+ if pointer == nil || *pointer != "CHAT-KEEP-S" {
+ t.Fatal("a transient failure must keep the chat resume pointer")
+ }
+}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 2621a3aa90..4ac3fb1d64 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -370,7 +370,7 @@ func (c *Client) ReportTaskMessages(ctx context.Context, taskID string, messages
}, nil)
}
-func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool) error {
+func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID string) error {
body := map[string]any{"output": output}
if branchName != "" {
body["branch_name"] = branchName
@@ -384,6 +384,9 @@ func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, s
if sessionRolloutMissing {
body["session_rollout_missing"] = true
}
+ if retiredSessionID != "" {
+ body["retired_session_id"] = retiredSessionID
+ }
return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/complete", taskID), body, nil, defaultTerminalRetrySchedule)
}
@@ -396,7 +399,7 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}, nil)
}
-func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool) error {
+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool, retiredSessionID string) error {
body := map[string]any{"error": errMsg}
if sessionID != "" {
body["session_id"] = sessionID
@@ -410,6 +413,9 @@ func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDi
if sessionRolloutMissing {
body["session_rollout_missing"] = true
}
+ if retiredSessionID != "" {
+ body["retired_session_id"] = retiredSessionID
+ }
return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil, defaultTerminalRetrySchedule)
}
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index 971d652995..360ae181af 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -290,7 +290,7 @@ func TestFailTask_RetriesOnTransient5xxThenSucceeds(t *testing.T) {
defer srv.Close()
c := NewClient(srv.URL)
- if err := c.FailTask(context.Background(), "task-1", "boom", "", "", "timeout", true); err != nil {
+ if err := c.FailTask(context.Background(), "task-1", "boom", "", "", "timeout", true, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
if got := calls.Load(); got != 3 {
@@ -403,3 +403,70 @@ func TestNormalizeGOOS(t *testing.T) {
}
}
}
+
+// TestTerminalReportsCarryRetiredSessionID pins the daemon half of the
+// retire-session contract (GH #6066). Before it, a terminal report could only
+// say "here is a session" or say nothing — and saying nothing was how a
+// recovered turn silently left the poisoned id selectable. The completed path
+// matters most: that is exactly the case where a fresh-session retry SUCCEEDED
+// and the abandoned transcript would otherwise survive on an older row.
+func TestTerminalReportsCarryRetiredSessionID(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ endpoint string
+ call func(*Client) error
+ }{
+ {
+ name: "complete",
+ endpoint: "/api/daemon/tasks/task-1/complete",
+ call: func(c *Client) error {
+ return c.CompleteTask(context.Background(), "task-1", "done", "", "", "/tmp/wd", false, "POISONED-S")
+ },
+ },
+ {
+ name: "fail",
+ endpoint: "/api/daemon/tasks/task-1/fail",
+ call: func(c *Client) error {
+ return c.FailTask(context.Background(), "task-1", "boom", "", "/tmp/wd", "api_invalid_request", false, "POISONED-S")
+ },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != tc.endpoint {
+ t.Errorf("unexpected path %q", r.URL.Path)
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ if err := tc.call(NewClient(srv.URL)); err != nil {
+ t.Fatalf("terminal report: %v", err)
+ }
+ if got, _ := body["retired_session_id"].(string); got != "POISONED-S" {
+ t.Fatalf("retired_session_id = %v, want POISONED-S (body: %v)", body["retired_session_id"], body)
+ }
+ })
+ }
+}
+
+// TestTerminalReportsOmitEmptyRetiredSessionID keeps the common case off the
+// wire: nearly every run retires nothing, and an empty field would be
+// indistinguishable from "retire the empty session".
+func TestTerminalReportsOmitEmptyRetiredSessionID(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ if err := NewClient(srv.URL).CompleteTask(context.Background(), "task-1", "done", "", "sess-1", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ if _, present := body["retired_session_id"]; present {
+ t.Fatalf("retired_session_id must be omitted when nothing was retired, got %v", body)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 7559847a98..3696dcd52e 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -145,6 +145,11 @@ type terminalTaskReport struct {
// session because its rollout was not in the store (MUL-5305). The server
// clears the resume pointer and flags the continuity gap for the next claim.
sessionRolloutMissing bool
+ // retiredSessionID names a session this run was told to resume and then
+ // abandoned as unresumable (GH #6066). The server records it so no later
+ // run on the issue or chat can select it again, however many clean rows
+ // still reference it.
+ retiredSessionID string
}
type executionEnvironmentCommand func() ([]string, error)
@@ -3918,6 +3923,7 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
sessionID: result.SessionID,
workDir: result.WorkDir,
sessionRolloutMissing: result.SessionRolloutMissing,
+ retiredSessionID: result.RetiredSessionID,
})
if err == nil {
return
@@ -3955,6 +3961,7 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
workDir: result.WorkDir,
failureReason: taskfailure.Classify(fallbackErrMsg).String(),
sessionRolloutMissing: result.SessionRolloutMissing,
+ retiredSessionID: result.RetiredSessionID,
}); failErr != nil {
taskLog.Error("fail task fallback also failed", "error", failErr)
}
@@ -3986,6 +3993,7 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
workDir: result.WorkDir,
failureReason: failureReason,
sessionRolloutMissing: result.SessionRolloutMissing,
+ retiredSessionID: result.RetiredSessionID,
}); err != nil {
taskLog.Error("report failed task failed", "error", err)
}
@@ -4003,9 +4011,9 @@ func (d *Daemon) reportTerminalTask(parentCtx context.Context, report terminalTa
switch report.kind {
case terminalTaskReportComplete:
- return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing)
+ return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID)
case terminalTaskReportFail:
- return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.failureReason, report.sessionRolloutMissing)
+ return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID)
default:
return fmt.Errorf("unsupported terminal task report kind %d", report.kind)
}
@@ -5204,10 +5212,20 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
return TaskResult{}, err
}
+ // retiredSessionID is the session this run was told to resume and then
+ // abandoned. Captured before the retry clears task.PriorSessionID, and
+ // reported on EVERY terminal path — the retry succeeding is exactly when
+ // the abandoned id would otherwise survive, unreferenced by this task's
+ // row but still reachable through an older completed row on the issue or
+ // through the chat_session pointer (GH #6066).
+ var retiredSessionID string
+ defer func() { taskResult.RetiredSessionID = retiredSessionID }()
+
if shouldRetryWithFreshSession(result, task.PriorSessionID, tools, provider) {
firstResult := result
firstUsage := result.Usage
firstTools := tools
+ retiredSessionID = task.PriorSessionID
taskLog.Warn("session resume failed, retrying with fresh session", "error", result.Error)
// Rebuild cold-session context before the single retry. The prior
@@ -5503,6 +5521,28 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, too
if result.ResumeRejected {
return true
}
+ // Positive evidence of a different kind: the resume was NOT refused —
+ // the transcript loaded fine — and the provider then refused to replay
+ // it because a message in it is empty. ResumeRejected is false for every
+ // backend here precisely because nothing rejected the resume, which is
+ // why this needs its own branch rather than a phrase added to the
+ // rejection list.
+ //
+ // It applies to all 17 backends, not the ResumeRejectionUndetectable
+ // subset below, and that is deliberate: this is the one failure class
+ // where dropping the session is provably the fix without the backend
+ // having to detect anything. The evidence is in the provider's own error
+ // text, which the common layer already has. Leaving it to each adapter
+ // is how the same bug got fixed three times for Kiro, Kimi and Anthropic
+ // while every other backend stayed broken.
+ //
+ // The tools == 0 gate above still applies unchanged — a run that already
+ // used a tool is never re-run, poisoned history or not. Such a task still
+ // gets its session retired, just by classifyPoisonedError at report time
+ // rather than by an in-turn retry.
+ if taskfailure.UnresumableHistory(result.Error) {
+ return true
+ }
// Everything below is a bounded compatibility path for the backends that
// cannot answer question 1 at all. For every other backend a false
// ResumeRejected is a real answer — it checked and this was not a
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 9f82eade95..ef2b6f13ab 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2390,6 +2390,55 @@ func TestShouldRetryWithFreshSession_CompatPathIsBackendScoped(t *testing.T) {
})
}
+// TestShouldRetryWithFreshSession_UnresumableHistoryIsBackendAgnostic pins the
+// DECISION layer for GH #6066 / GH #5760: given the same provider error, every
+// supported backend gets the same verdict, so recovery is not a property of
+// whichever adapter happened to get a bug report. ResumeRejected is false for
+// all of them here — nothing rejected the resume; the transcript loaded and the
+// provider refused to replay it.
+//
+// Scope, deliberately: this feeds each backend a hand-built agent.Result, so it
+// proves the shared decision ignores the provider NAME. It does not prove all
+// 17 adapters surface an upstream error into Result.Error in the first place —
+// #5760 is the counter-example, where the Kimi/ACP adapter swallowed the error
+// and reported completed. The fix therefore covers every backend that surfaces
+// the error; adapter-level surfacing is tracked separately (#5785 for ACP).
+//
+// The safety half is asserted in the same loop: tools > 0 must still veto the
+// retry for every backend, because re-running a turn that already posted a
+// comment or wrote a commit duplicates that side effect. Those tasks recover
+// on the next trigger instead — classifyPoisonedError retires the session at
+// report time.
+func TestShouldRetryWithFreshSession_UnresumableHistoryIsBackendAgnostic(t *testing.T) {
+ t.Parallel()
+
+ // Both real-world wordings, neither of which the pre-fix detector matched.
+ errors := map[string]string{
+ "gh6066": "Invalid request: the message at position 37 with role 'assistant' must not be empty",
+ "gh5760": "kimi provider error: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty",
+ }
+
+ for _, provider := range agent.SupportedTypes {
+ for label, errMsg := range errors {
+ t.Run(provider+"/"+label+" retries fresh", func(t *testing.T) {
+ t.Parallel()
+ result := agent.Result{Status: "failed", Error: errMsg, SessionID: "poisoned-id"}
+ if !shouldRetryWithFreshSession(result, "poisoned-id", 0, provider) {
+ t.Fatalf("%s: an unresumable history must trigger the fresh-session retry on every backend", provider)
+ }
+ })
+
+ t.Run(provider+"/"+label+" respects the tool gate", func(t *testing.T) {
+ t.Parallel()
+ result := agent.Result{Status: "failed", Error: errMsg, SessionID: "poisoned-id"}
+ if shouldRetryWithFreshSession(result, "poisoned-id", 1, provider) {
+ t.Fatalf("%s: a run that already used a tool must never be re-run automatically", provider)
+ }
+ })
+ }
+ }
+}
+
func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fixture is POSIX-only")
diff --git a/server/internal/daemon/poisoned.go b/server/internal/daemon/poisoned.go
index 7aa28e67b3..0dd0b36492 100644
--- a/server/internal/daemon/poisoned.go
+++ b/server/internal/daemon/poisoned.go
@@ -101,6 +101,12 @@ func classifyPoisonedOutput(output string) (string, bool) {
// 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.
+//
+// That shape is Anthropic's, though, and it is not the only way a provider
+// reports an unprocessable transcript. The final clause delegates to
+// taskfailure.UnresumableHistory, which detects an empty message baked into
+// the conversation by ANY backend — see its doc comment for why the defect
+// has to be recognised by wording rather than by status code or provider.
func classifyPoisonedError(errMsg string) (string, bool) {
if errMsg == "" {
return "", false
@@ -128,6 +134,17 @@ func classifyPoisonedError(errMsg string) (string, bool) {
if strings.Contains(lowered, "invalid_request_error") && strings.Contains(lowered, "400") {
return FailureReasonAPIInvalidRequest, true
}
+ // The same defect reported by a provider that words it differently.
+ // The clause above only fires on the Anthropic shape, so an empty
+ // message baked into the transcript by any other backend used to fall
+ // through to taskfailure.Classify as agent_error.unknown — resume-safe
+ // by omission, which permanently bricked the (agent, issue) pair
+ // (GH #6066, GH #5760). taskfailure.UnresumableHistory recognises the
+ // defect by what the provider says is wrong rather than by which
+ // provider said it.
+ if taskfailure.UnresumableHistory(errMsg) {
+ return FailureReasonAPIInvalidRequest, true
+ }
return "", false
}
diff --git a/server/internal/daemon/poisoned_test.go b/server/internal/daemon/poisoned_test.go
index 3e653b9a69..1618217e0a 100644
--- a/server/internal/daemon/poisoned_test.go
+++ b/server/internal/daemon/poisoned_test.go
@@ -157,6 +157,34 @@ func TestClassifyPoisonedError(t *testing.T) {
errMsg: "claude execution timeout after 10m",
wantOK: false,
},
+ {
+ // GH #6066: a run killed mid-reply left an empty assistant
+ // message in the transcript. The provider refuses to replay it
+ // and words the refusal with neither "invalid_request_error"
+ // nor a bare "400", so before taskfailure.UnresumableHistory
+ // this landed in agent_error.unknown — resume-safe by omission
+ // — and every later task on the issue resumed the dead session.
+ name: "gh6066 empty assistant message in history",
+ errMsg: "Invalid request: the message at position 37 with role 'assistant' must not be empty",
+ wantOK: true,
+ wantReason: FailureReasonAPIInvalidRequest,
+ },
+ {
+ // GH #5760: the same defect on Kimi/ACP. Has a "400" but no
+ // "invalid_request_error", so the Anthropic clause missed it too.
+ name: "gh5760 kimi empty assistant message",
+ errMsg: "kimi provider error: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty",
+ wantOK: true,
+ wantReason: FailureReasonAPIInvalidRequest,
+ },
+ {
+ // The narrowness guard: an emptiness complaint with no locator
+ // into the message history is some tool's validation error, and
+ // discarding a healthy session over it would lose real context.
+ name: "tool validation emptiness is not poisoning",
+ errMsg: "validation error: field must not be empty",
+ wantOK: false,
+ },
{
// GH #5975: a Kiro resume rejected because the session
// history replays an image over the provider's max pixel
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 8a347cdfea..b45060122e 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -263,6 +263,11 @@ type TaskResult struct {
// session because its rollout was not in the store (MUL-5305). Forwarded to
// the terminal report so the server clears the resume pointer and flags the
// continuity gap for the next claim. Not part of the wire result itself.
- SessionRolloutMissing bool `json:"-"`
- Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage
+ SessionRolloutMissing bool `json:"-"`
+ // RetiredSessionID names a session this run was told to resume and then
+ // abandoned as unresumable (GH #6066). Forwarded on every terminal path,
+ // including the completed one: a fresh-session retry that SUCCEEDS is
+ // precisely when the abandoned id would otherwise stay selectable.
+ RetiredSessionID string `json:"-"`
+ Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage
}
diff --git a/server/internal/handler/chat_attachment_reply_test.go b/server/internal/handler/chat_attachment_reply_test.go
index 295a8081c8..65e7299adc 100644
--- a/server/internal/handler/chat_attachment_reply_test.go
+++ b/server/internal/handler/chat_attachment_reply_test.go
@@ -277,7 +277,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"here is the chart"}`), "", "", false); err != nil {
+ parseUUID(taskID), []byte(`{"output":"here is the chart"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
msgID, content, ok := assistantMessageForTask(t, taskID)
@@ -298,7 +298,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":""}`), "", "", false); err != nil {
+ parseUUID(taskID), []byte(`{"output":""}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
msgID, content, ok := assistantMessageForTask(t, taskID)
@@ -317,7 +317,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
t.Run("empty output + no attachment creates no message", func(t *testing.T) {
taskID := seedRunningChatTask(t, agentID, sessionID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":""}`), "", "", false); err != nil {
+ parseUUID(taskID), []byte(`{"output":""}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if _, _, ok := assistantMessageForTask(t, taskID); ok {
@@ -340,7 +340,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, looseID) })
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false); err != nil {
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if got := attachmentMessageID(t, looseID); got != nil {
@@ -378,7 +378,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
}
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false); err != nil {
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
got := attachmentMessageID(t, claimedID)
@@ -391,7 +391,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
taskID := seedRunningChatTask(t, agentID, sessionID)
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.FailTask(context.Background(),
- parseUUID(taskID), "agent crashed", "", "", "", false); err != nil {
+ parseUUID(taskID), "agent crashed", "", "", "", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
if got := attachmentMessageID(t, attID); got != nil {
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index f4fe58f475..10ebacbb96 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -94,7 +94,7 @@ func TestDirectChat_TaskOwnsItsOwnInputBatch(t *testing.T) {
// coalesced pair. The claim leaves T1 dispatched; move it to running so the
// completion CAS (WHERE status='running') applies.
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "上海晴"), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "上海晴"), "", "", false, ""); err != nil {
t.Fatalf("complete first task: %v", err)
}
claimed2 := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
@@ -152,7 +152,7 @@ func TestCompleteTask_ChatEmptyOutputWritesNoResponse(t *testing.T) {
markTaskRunning(t, ctx, taskID)
// Whitespace-only output trims to empty → no_response.
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, " "), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, " "), "", "", false, ""); err != nil {
t.Fatalf("complete task: %v", err)
}
@@ -181,7 +181,7 @@ func TestCompleteTask_ChatNonEmptyOutputWritesMessage(t *testing.T) {
taskID := sendDirectChat(t, ctx, agentID, sessionID, "hello")
markTaskRunning(t, ctx, taskID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "hi there"), "sess-1", "/tmp/wd", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "hi there"), "sess-1", "/tmp/wd", false, ""); err != nil {
t.Fatalf("complete task: %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -208,11 +208,11 @@ func TestCompleteTask_ChatCallbackIdempotent(t *testing.T) {
markTaskRunning(t, ctx, taskID)
res := completeResult(t, "reply")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false, ""); err != nil {
t.Fatalf("first complete: %v", err)
}
// Replay: the status CAS fails, so this is an idempotent no-op success.
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false, ""); err != nil {
t.Fatalf("replayed complete must be idempotent success, got %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 1 {
@@ -233,7 +233,7 @@ func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {
rootID := sendDirectChat(t, ctx, agentID, sessionID, "root question")
markTaskRunning(t, ctx, rootID)
- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(rootID), "runtime went away", "", "", "runtime_offline", false); err != nil {
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(rootID), "runtime went away", "", "", "runtime_offline", false, ""); err != nil {
t.Fatalf("fail task: %v", err)
}
@@ -392,7 +392,7 @@ func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
// Empty output → no row at all.
emptyTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false, ""); err != nil {
t.Fatalf("complete channel task (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
@@ -401,7 +401,7 @@ func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
// Non-empty output → one ordinary message (kind 'message', not no_response).
textTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "channel reply"), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "channel reply"), "", "", false, ""); err != nil {
t.Fatalf("complete channel task (text): %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -427,7 +427,7 @@ func TestCompleteTask_SealedChannelEmptyOutputWritesNoRow(t *testing.T) {
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "sealed channel chat")
emptyTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "[Image]")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel task (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
@@ -436,7 +436,7 @@ func TestCompleteTask_SealedChannelEmptyOutputWritesNoRow(t *testing.T) {
// Non-empty output still writes one ordinary message.
textTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "hello")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "sealed channel reply"), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "sealed channel reply"), "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel task (text): %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -467,7 +467,7 @@ func TestCompleteTask_SealedChannelRetryEmptyOutputWritesNoRow(t *testing.T) {
t.Fatalf("setup: create retry clone: %v", err)
}
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(retryTask), completeResult(t, ""), "", "", false); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(retryTask), completeResult(t, ""), "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel retry (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 99c0b33f0b..44d0460a54 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2920,6 +2920,11 @@ type TaskCompleteRequest struct {
// because its rollout was missing (MUL-5305). Clear the resume pointer and
// flag the continuity gap for the next claim.
SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
+ // RetiredSessionID: a session this run proved unresumable and abandoned
+ // (GH #6066). Distinct from an empty SessionID, which only means "nothing
+ // to report" — this says "never hand this id to a later run". Older
+ // daemons omit it, which is exactly the pre-fix behaviour.
+ RetiredSessionID string `json:"retired_session_id,omitempty"`
}
func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
@@ -2942,7 +2947,7 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
// transaction (force session_id NULL + flag the row), so an auto-retry the
// same commit creates and wakes can never observe the withheld pointer or a
// missing continuity-gap flag.
- task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.SessionRolloutMissing)
+ task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.SessionRolloutMissing, req.RetiredSessionID)
if err != nil {
// A CompleteTask error is an infrastructure failure (transaction /
// assistant-outcome write), not a bad request: an already-finalized
@@ -3575,6 +3580,11 @@ type TaskFailRequest struct {
// because its rollout was missing (MUL-5305). Clear the resume pointer and
// flag the continuity gap for the next claim.
SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
+ // RetiredSessionID: a session this run proved unresumable and abandoned
+ // (GH #6066). Distinct from an empty SessionID, which only means "nothing
+ // to report" — this says "never hand this id to a later run". Older
+ // daemons omit it, which is exactly the pre-fix behaviour.
+ RetiredSessionID string `json:"retired_session_id,omitempty"`
}
func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
@@ -3597,7 +3607,7 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
// keep a stale mid-flight pin) and flagging the row in the same commit that
// creates and wakes the auto-retry, so the retry can never claim the withheld
// pointer or miss the continuity gap.
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason, req.SessionRolloutMissing)
+ task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID)
if err != nil {
// A FailTask error is an infrastructure failure (the terminal
// transaction that also clears the withheld session, writes the
diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.go
index 5dd9d28d8f..e67ab29756 100644
--- a/server/internal/handler/issue_child_done_test.go
+++ b/server/internal/handler/issue_child_done_test.go
@@ -625,7 +625,7 @@ func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {
t.Fatalf("dispatch original leader task: %v", err)
}
- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(originalID), "task preparation timed out after 5m0s", "", "", "timeout", false); err != nil {
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(originalID), "task preparation timed out after 5m0s", "", "", "timeout", false, ""); err != nil {
t.Fatalf("fail original leader task: %v", err)
}
diff --git a/server/internal/service/resume_unsafe_test.go b/server/internal/service/resume_unsafe_test.go
new file mode 100644
index 0000000000..9a107e7648
--- /dev/null
+++ b/server/internal/service/resume_unsafe_test.go
@@ -0,0 +1,77 @@
+package service
+
+import "testing"
+
+// TestResumeUnsafeFailureEmptyHistoryMessage covers the manual-retry half of
+// GH #6066. The claim handler resolves a rerun's session from the exact source
+// task via ResumeUnsafeFailure rather than GetLastTaskSession, so a gap here
+// means clicking Rerun resumes the very transcript the provider just refused —
+// which is what the reporter experienced.
+//
+// The failure_reason cases and the raw-text cases are both exercised because
+// they cover different hosts: a current daemon writes api_invalid_request, an
+// older one (self-host installs upgrade on their own cadence) writes
+// agent_error.unknown and only the text guard saves it.
+func TestResumeUnsafeFailureEmptyHistoryMessage(t *testing.T) {
+ t.Parallel()
+
+ const gh6066 = "Invalid request: the message at position 37 with role 'assistant' must not be empty"
+ const gh5760 = "kimi provider error: provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty"
+
+ cases := []struct {
+ name string
+ failureReason string
+ errorText string
+ want bool
+ }{
+ {
+ name: "current daemon classifies the reason",
+ failureReason: "api_invalid_request",
+ errorText: gh6066,
+ want: true,
+ },
+ {
+ // The row an un-upgraded daemon writes: the text guard is the
+ // only thing standing between Rerun and the poisoned session.
+ name: "older daemon leaves the reason unknown",
+ failureReason: "agent_error.unknown",
+ errorText: gh6066,
+ want: true,
+ },
+ {
+ name: "kimi wording, unknown reason",
+ failureReason: "agent_error.unknown",
+ errorText: gh5760,
+ want: true,
+ },
+ {
+ // Transient failures must stay resumable: the whole point of
+ // reusing the session on retry is to keep the conversation.
+ name: "provider network drop stays resumable",
+ failureReason: "agent_error.provider_network",
+ errorText: "Connection closed mid-response",
+ want: false,
+ },
+ {
+ name: "tool emptiness error stays resumable",
+ failureReason: "agent_error.unknown",
+ errorText: "validation error: field must not be empty",
+ want: false,
+ },
+ {
+ name: "no error text and a benign reason",
+ failureReason: "agent_error.unknown",
+ errorText: "",
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := ResumeUnsafeFailure(tc.failureReason, tc.errorText); got != tc.want {
+ t.Fatalf("ResumeUnsafeFailure(%q, %q) = %v, want %v", tc.failureReason, tc.errorText, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index 08996cdd65..5bf6ea4137 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -132,7 +132,7 @@ func TestFailTaskProviderNetworkBudget(t *testing.T) {
pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE parent_task_id = $1 OR id = $1`, parentID)
})
- if _, err := svc.FailTask(ctx, parentID, "API Error: Connection closed mid-response.", "src-session", "/tmp/src-workdir", "agent_error.provider_network", false); err != nil {
+ if _, err := svc.FailTask(ctx, parentID, "API Error: Connection closed mid-response.", "src-session", "/tmp/src-workdir", "agent_error.provider_network", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 08a6e08167..0f42cb5815 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2754,7 +2754,7 @@ func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID
// queued chat message could be claimed in the window between the task
// flipping to 'completed' and chat_session.session_id being refreshed,
// causing the new task to resume against a stale (or NULL) session.
-func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir string, sessionRolloutMissing bool) (*db.AgentTaskQueue, error) {
+func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
var task db.AgentTaskQueue
// chatAssistantMsg is the single assistant outcome row written for a chat
// task inside the completion transaction below. It is broadcast (chat:done)
@@ -2767,6 +2767,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
SessionRolloutMissing: sessionRolloutMissing,
+ RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
})
if err != nil {
return err
@@ -2792,6 +2793,21 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}); err != nil {
return fmt.Errorf("update chat session resume pointer: %w", err)
}
+ // A turn that recovered by abandoning its session still has to
+ // retire it here. The COALESCE above cannot: a fresh retry that
+ // succeeds without emitting a new id passes sessionID == "", which
+ // preserves the pointer — and the pointer is the poisoned session
+ // (GH #6066). Runs after the update so a real new id wins first and
+ // the match guard then finds nothing to clear.
+ if retiredSessionID != "" {
+ if err := qtx.ClearChatSessionSessionIfMatches(ctx, db.ClearChatSessionSessionIfMatchesParams{
+ ID: t.ChatSessionID,
+ SessionID: pgtype.Text{String: retiredSessionID, Valid: true},
+ RuntimeID: t.RuntimeID,
+ }); err != nil {
+ return fmt.Errorf("clear retired chat session resume pointer: %w", err)
+ }
+ }
// Write the assistant outcome in the SAME transaction as the status
// flip and resume-pointer update (MUL-4351). For a task-owned direct
@@ -3095,7 +3111,7 @@ func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body st
// coarse bucket. Daemon callers that already produced a refined reason
// (via classifyPoisonedError, the timeout / runtime classifier, etc.)
// will have their value preserved untouched.
-func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool) (*db.AgentTaskQueue, error) {
+func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
// MUL-2946: synthesise a refined reason from the error text whenever the
// caller didn't supply one. This is the last write-path guard against
// "agent_error" coarse rows ending up in agent_task_queue.failure_reason
@@ -3167,6 +3183,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
SessionRolloutMissing: sessionRolloutMissing,
+ RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
})
if err != nil {
return err
@@ -3175,7 +3192,49 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// Keep resume-unsafe sessions on the task row for observability, but
// do not promote them to the chat-level resume pointer.
- if t.ChatSessionID.Valid && !resumeUnsafeFailureReason(failureReason) {
+ //
+ // Declining to overwrite is not enough on its own: the claim handler
+ // reads chat_session.session_id BEFORE consulting
+ // GetLastChatTaskSession, so a pointer already holding the dead
+ // session bypasses every filter that query applies and the next turn
+ // resumes it (GH #6066). Clear it in this same transaction, matched on
+ // the exact session and runtime so a concurrent turn's newer pointer
+ // is left alone. ResumeUnsafeFailure (not the reason alone) so an
+ // un-upgraded daemon's agent_error.unknown row is caught by the error
+ // text too.
+ if t.ChatSessionID.Valid && ResumeUnsafeFailure(failureReason, errMsg) {
+ deadSession := sessionID
+ if deadSession == "" {
+ deadSession = t.SessionID.String
+ }
+ if deadSession != "" {
+ if err := qtx.ClearChatSessionSessionIfMatches(ctx, db.ClearChatSessionSessionIfMatchesParams{
+ ID: t.ChatSessionID,
+ SessionID: pgtype.Text{String: deadSession, Valid: true},
+ RuntimeID: t.RuntimeID,
+ }); err != nil {
+ return fmt.Errorf("clear poisoned chat session resume pointer: %w", err)
+ }
+ }
+ }
+ // A session the run explicitly retired must go too, whatever the
+ // terminal status: the fresh-session retry that replaced it may well
+ // have succeeded, and the pointer would otherwise still name the
+ // transcript it retried away from.
+ if t.ChatSessionID.Valid && retiredSessionID != "" {
+ if err := qtx.ClearChatSessionSessionIfMatches(ctx, db.ClearChatSessionSessionIfMatchesParams{
+ ID: t.ChatSessionID,
+ SessionID: pgtype.Text{String: retiredSessionID, Valid: true},
+ RuntimeID: t.RuntimeID,
+ }); err != nil {
+ return fmt.Errorf("clear retired chat session resume pointer: %w", err)
+ }
+ }
+
+ // ResumeUnsafeFailure, not resumeUnsafeFailureReason: the reason-only
+ // check passes an un-upgraded daemon's agent_error.unknown row, which
+ // would re-pin the very session the clear above just removed.
+ if t.ChatSessionID.Valid && !ResumeUnsafeFailure(failureReason, errMsg) {
// Pin the chat_session's runtime_id alongside the session_id so the
// next claim can apply the runtime-guard. Both fields move together:
// when there's no session_id to record, leave runtime_id untouched
@@ -3412,7 +3471,14 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {
return true
}
lower := strings.ToLower(errorText)
- return strings.Contains(lower, "400") && strings.Contains(lower, "invalid_request_error")
+ if strings.Contains(lower, "400") && strings.Contains(lower, "invalid_request_error") {
+ return true
+ }
+ // Same defense-in-depth for the provider-agnostic empty-message shape:
+ // a daemon too old to carry classifyPoisonedError's new branch reports
+ // agent_error.unknown, and without this the manual-retry path would
+ // happily resume the transcript the provider just refused (GH #6066).
+ return taskfailure.UnresumableHistory(errorText)
}
// retryEligible reports whether a failed task qualifies for an automatic retry
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 653588c0fe..ef8bde0d79 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -110,7 +110,7 @@ func TestCompleteTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.CompleteTask(context.Background(), taskID, nil, "", "", false)
+ got, err := svc.CompleteTask(context.Background(), taskID, nil, "", "", false, "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
@@ -152,7 +152,7 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", false)
+ got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", false, "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
diff --git a/server/migrations/234_agent_task_queue_retired_session_id.down.sql b/server/migrations/234_agent_task_queue_retired_session_id.down.sql
new file mode 100644
index 0000000000..bfa299910a
--- /dev/null
+++ b/server/migrations/234_agent_task_queue_retired_session_id.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS retired_session_id;
diff --git a/server/migrations/234_agent_task_queue_retired_session_id.up.sql b/server/migrations/234_agent_task_queue_retired_session_id.up.sql
new file mode 100644
index 0000000000..ae211f63d6
--- /dev/null
+++ b/server/migrations/234_agent_task_queue_retired_session_id.up.sql
@@ -0,0 +1,16 @@
+-- retired_session_id records an agent session this task proved unresumable and
+-- that must never be handed to a later run, on ANY path.
+--
+-- The daemon already knew this and had no way to say it. A terminal report
+-- carries one session_id, and an empty one meant both "no session to report"
+-- and "forget the old session" — so after a fresh-session retry recovered a
+-- turn, the poisoned id it retried away from stayed selectable: an older
+-- completed row on the issue still pointed at it, and the chat_session pointer
+-- still held it. The next run resumed the same dead transcript (GH #6066).
+--
+-- Nullable and write-once per row: set only when a run abandons a session it
+-- was told to resume. NULL — the overwhelming majority of rows — means nothing
+-- was retired. No index: every reader already scopes by (agent_id, issue_id)
+-- or chat_session_id, both of which are indexed, and the retired set within a
+-- scope is tiny.
+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS retired_session_id TEXT;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 425cd5dcc8..66b067570b 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -196,7 +196,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -251,6 +251,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -259,7 +260,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -325,6 +326,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -340,7 +342,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Cancels active tasks belonging to a chat session. Called from
@@ -406,6 +408,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -421,7 +424,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -487,6 +490,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -502,7 +506,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -572,6 +576,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -588,7 +593,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -653,6 +658,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -673,9 +679,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id
)
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM cancelled
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -732,6 +738,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
AccountableUserID pgtype.UUID `json:"accountable_user_id"`
SessionRolloutMissing bool `json:"session_rollout_missing"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -792,6 +799,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -808,7 +816,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -869,6 +877,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -909,7 +918,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type ClaimAgentTaskParams struct {
@@ -978,6 +987,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -986,7 +996,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1043,6 +1053,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -1232,9 +1243,10 @@ SET status = 'completed', completed_at = now(), result = $2,
session_id = CASE WHEN $5 THEN NULL ELSE $3 END,
work_dir = $4,
session_rollout_missing = $5,
+ retired_session_id = COALESCE($6, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CompleteAgentTaskParams struct {
@@ -1243,6 +1255,7 @@ type CompleteAgentTaskParams struct {
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
SessionRolloutMissing bool `json:"session_rollout_missing"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
// session_rollout_missing (MUL-5305): when true the daemon withheld this task's
@@ -1250,6 +1263,12 @@ type CompleteAgentTaskParams struct {
// session_id NULL and flagging the row happen in THIS terminal transaction so an
// auto-retry created and woken by the same commit can never observe the bad
// pointer or a missing gap flag.
+//
+// retired_session_id (GH #6066): a session this run abandoned as unresumable.
+// Recorded even on the completed path, because that is exactly the case the
+// resume lookups could not see — a fresh-session retry that SUCCEEDS still has
+// to retire the transcript it retried away from, or an older completed row
+// pointing at the same id resurrects it on the next run.
func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, completeAgentTask,
arg.ID,
@@ -1257,6 +1276,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
arg.SessionID,
arg.WorkDir,
arg.SessionRolloutMissing,
+ arg.RetiredSessionID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -1308,6 +1328,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -1524,7 +1545,7 @@ VALUES (
$21,
$22
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateAgentTaskParams struct {
@@ -1634,6 +1655,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -1660,7 +1682,7 @@ VALUES (
$15,
$16
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateDeferredAgentTaskParams struct {
@@ -1758,6 +1780,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -1778,7 +1801,7 @@ VALUES (
$10,
$11
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateQuickCreateTaskParams struct {
@@ -1865,6 +1888,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -1900,7 +1924,7 @@ SELECT
p.chat_input_task_id, $2
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateRetryTaskParams struct {
@@ -2021,6 +2045,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -2057,7 +2082,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id
`
type ExpireStaleQueuedTasksParams struct {
@@ -2146,6 +2171,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -2164,7 +2190,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -2229,6 +2255,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -2242,9 +2269,10 @@ SET status = 'failed',
session_id = CASE WHEN $4 THEN NULL ELSE COALESCE($5, session_id) END,
work_dir = COALESCE($6, work_dir),
session_rollout_missing = $4,
+ retired_session_id = COALESCE($7, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type FailAgentTaskParams struct {
@@ -2254,6 +2282,7 @@ type FailAgentTaskParams struct {
SessionRolloutMissing bool `json:"session_rollout_missing"`
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
// Marks a task as failed. session_id and work_dir are merged via COALESCE so
@@ -2279,6 +2308,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
arg.SessionRolloutMissing,
arg.SessionID,
arg.WorkDir,
+ arg.RetiredSessionID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -2330,6 +2360,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -2354,7 +2385,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type FailStaleTasksParams struct {
@@ -2458,6 +2489,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -2643,7 +2675,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE id = $1
`
@@ -2699,12 +2731,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2773,29 +2806,38 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
const getLastTaskSession = `-- name: GetLastTaskSession :one
-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
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.agent_id = $1 AND r.issue_id = $2
+ AND r.retired_session_id IS NOT NULL
+), 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,
+ COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.issue_id = $2
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed')
+ ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC
)
SELECT session_id, work_dir, runtime_id FROM latest_per_session
-WHERE (
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
+ AND (
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 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]')
)
)
ORDER BY terminal_at DESC
@@ -2876,6 +2918,25 @@ type GetLastTaskSessionRow struct {
// 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.
+//
+// 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
+// taskfailure.UnresumableHistory reports an empty-message rejection as
+// agent_error.unknown and would otherwise keep resuming the transcript the
+// provider just refused (GH #6066). Both regexes must match — an emptiness
+// complaint AND a locator pointing into the message history — mirroring
+// emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.
+// Keep the three in sync.
+//
+// retired_sessions is the explicit half of the same rule (GH #6066). The
+// per-session latest state above can only judge sessions that some row still
+// POINTS at, so it cannot see a session a run deliberately abandoned: a fresh
+// retry that succeeded reports its own new id (or none), leaving the poisoned
+// id visible on nothing but an older completed row, which then looks perfectly
+// healthy. retired_session_id records the abandonment itself, so one row
+// retiring a session removes it from every later lookup no matter how many
+// clean rows still reference it.
func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSessionParams) (GetLastTaskSessionRow, error) {
row := q.db.QueryRow(ctx, getLastTaskSession, arg.AgentID, arg.IssueID)
var i GetLastTaskSessionRow
@@ -3355,7 +3416,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -3423,6 +3484,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -3435,7 +3497,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -3498,6 +3560,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -3685,7 +3748,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -3758,6 +3821,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -3770,7 +3834,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -3833,6 +3897,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -3845,7 +3910,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3916,6 +3981,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -3928,7 +3994,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -4001,6 +4067,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -4013,7 +4080,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -4076,6 +4143,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -4088,16 +4156,16 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -4190,6 +4258,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -4383,7 +4452,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -4453,6 +4522,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -4461,7 +4531,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -4518,6 +4588,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -4660,7 +4731,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -4721,6 +4792,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -4738,7 +4810,7 @@ SET status = 'queued'
WHERE runtime_id = ANY($1::uuid[])
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
@@ -4801,6 +4873,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -4901,7 +4974,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -4967,6 +5040,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -4986,7 +5060,7 @@ WHERE id IN (
LIMIT $4::int
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -5066,6 +5140,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -5086,7 +5161,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -5153,6 +5228,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -5291,7 +5367,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -5357,6 +5433,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -5457,7 +5534,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -5518,6 +5595,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 839eb345e2..fcf59fd1c6 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -288,7 +288,7 @@ VALUES (
$10,
$11
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateAutopilotTaskParams struct {
@@ -384,6 +384,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -745,7 +746,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -805,6 +806,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 5e7bb35906..db12a6d767 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -66,6 +66,41 @@ func (q *Queries) ClearChatSessionProjectByProject(ctx context.Context, arg Clea
return err
}
+const clearChatSessionSessionIfMatches = `-- name: ClearChatSessionSessionIfMatches :exec
+UPDATE chat_session
+SET session_id = NULL,
+ runtime_id = NULL,
+ updated_at = now()
+WHERE id = $1
+ AND session_id = $2
+ AND runtime_id = $3
+`
+
+type ClearChatSessionSessionIfMatchesParams struct {
+ ID pgtype.UUID `json:"id"`
+ SessionID pgtype.Text `json:"session_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+}
+
+// Drops the chat session's resume pointer, but only while it still points at
+// the exact session the caller proved unresumable.
+//
+// The claim handler reads chat_session.session_id FIRST and only falls back to
+// GetLastChatTaskSession when it is empty, so a poisoned pointer here bypasses
+// every filter that query applies. Declining to OVERWRITE the pointer on a
+// resume-unsafe failure — which is all the fail path used to do — leaves the
+// dead session in place and the next turn resumes it (GH #6066).
+//
+// The session_id + runtime_id predicate is what makes this safe to run in the
+// fail transaction: a concurrent turn that has already written a NEW pointer
+// does not match, so its healthy session survives instead of being cleared by
+// a slower sibling's failure. work_dir is deliberately left alone — the
+// directory is still reusable, only the conversation is not.
+func (q *Queries) ClearChatSessionSessionIfMatches(ctx context.Context, arg ClearChatSessionSessionIfMatchesParams) error {
+ _, err := q.db.Exec(ctx, clearChatSessionSessionIfMatches, arg.ID, arg.SessionID, arg.RuntimeID)
+ return err
+}
+
const createChatDraftRestore = `-- name: CreateChatDraftRestore :one
INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
VALUES ($1, $2, $3, $4, $5)
@@ -236,7 +271,7 @@ VALUES (
$14,
$6::timestamptz
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CreateChatTaskParams struct {
@@ -326,6 +361,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -343,7 +379,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -404,6 +440,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
@@ -630,17 +667,32 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess
}
const getLastChatTaskSession = `-- name: GetLastChatTaskSession :one
-SELECT session_id, work_dir, runtime_id FROM agent_task_queue
-WHERE chat_session_id = $1
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.chat_session_id = $1
+ AND r.retired_session_id IS NOT NULL
+), 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
+ FROM agent_task_queue t
+ WHERE t.chat_session_id = $1
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed')
+ ORDER BY t.session_id, t.completed_at DESC
+)
+SELECT session_id, work_dir, runtime_id FROM latest_per_session
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
AND (
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, '') ~* '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]')
)
)
- AND session_id IS NOT NULL
ORDER BY completed_at DESC
LIMIT 1
`
@@ -659,6 +711,20 @@ type GetLastChatTaskSessionRow struct {
// excluded because replaying those sessions deterministically reproduces the
// same terminal state. Keep this list in sync with resumeUnsafeFailureReason
// and GetLastTaskSession.
+//
+// The regex pair mirrors GetLastTaskSession's provider-agnostic guard for an
+// empty message baked into the conversation history: both must match, and
+// both track emptyContentRe / historyMessageLocatorRe in
+// pkg/taskfailure/resume.go (GH #6066).
+//
+// Selection is per-session, not per-row, and retired sessions are excluded —
+// both mirroring GetLastTaskSession, which this query had drifted away from.
+// A plain row-level filter reopens the poisoning wormhole GH #5975 closed on
+// the issue side: it drops the newest poisoned row for a session and then
+// happily falls back to an OLDER completed row carrying the same dead
+// session_id. Judging each session by its LATEST terminal state means a newer
+// poisoned row invalidates the whole session, while a genuinely different
+// healthy session stays eligible.
func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {
row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)
var i GetLastChatTaskSessionRow
@@ -1437,7 +1503,7 @@ WHERE task.chat_session_id = $1
AND message.role = 'user'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -1501,6 +1567,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -1598,7 +1665,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -1660,6 +1727,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 254f8ab582..4b69ee183a 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -151,6 +151,7 @@ type AgentTaskQueue struct {
// The one human accountable for this run, for audit / visibility / cost only — NEVER consulted for authorization (that is originator_user_id). Invariant: when originator_user_id IS NOT NULL, this equals it; the two diverge only when originator_user_id IS NULL (autopilot rule_owner / degraded owner_fallback name an accountable human while authorization carries none). No FK, no cascade (MUL-4302 §1/§7). NULL means no accountable human was resolved: a pre-migration row, OR a NEW row whose audit source is not-yet-resolved / unattributed (e.g. run_only autopilot until rule_owner lands) — NOT pre-migration only.
AccountableUserID pgtype.UUID `json:"accountable_user_id"`
SessionRolloutMissing bool `json:"session_rollout_missing"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
type AgentToLabel struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index fbde167cd0..e2e302f262 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -96,6 +96,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
@@ -227,7 +228,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -291,6 +292,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.TriggerEvidenceRefID,
&i.AccountableUserID,
&i.SessionRolloutMissing,
+ &i.RetiredSessionID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 21238aeed8..5967c0c4f2 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -685,11 +685,18 @@ RETURNING *;
-- session_id NULL and flagging the row happen in THIS terminal transaction so an
-- auto-retry created and woken by the same commit can never observe the bad
-- pointer or a missing gap flag.
+--
+-- retired_session_id (GH #6066): a session this run abandoned as unresumable.
+-- Recorded even on the completed path, because that is exactly the case the
+-- resume lookups could not see — a fresh-session retry that SUCCEEDS still has
+-- to retire the transcript it retried away from, or an older completed row
+-- pointing at the same id resurrects it on the next run.
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2,
session_id = CASE WHEN sqlc.arg('session_rollout_missing') THEN NULL ELSE $3 END,
work_dir = $4,
session_rollout_missing = sqlc.arg('session_rollout_missing'),
+ retired_session_id = COALESCE(sqlc.narg('retired_session_id'), retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
RETURNING *;
@@ -758,24 +765,51 @@ RETURNING *;
-- 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
+--
+-- 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
+-- taskfailure.UnresumableHistory reports an empty-message rejection as
+-- agent_error.unknown and would otherwise keep resuming the transcript the
+-- provider just refused (GH #6066). Both regexes must match — an emptiness
+-- complaint AND a locator pointing into the message history — mirroring
+-- emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.
+-- Keep the three in sync.
+--
+-- retired_sessions is the explicit half of the same rule (GH #6066). The
+-- per-session latest state above can only judge sessions that some row still
+-- POINTS at, so it cannot see a session a run deliberately abandoned: a fresh
+-- retry that succeeded reports its own new id (or none), leaving the poisoned
+-- id visible on nothing but an older completed row, which then looks perfectly
+-- healthy. retired_session_id records the abandonment itself, so one row
+-- retiring a session removes it from every later lookup no matter how many
+-- clean rows still reference it.
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.agent_id = $1 AND r.issue_id = $2
+ AND r.retired_session_id IS NOT NULL
+), 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,
+ COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.issue_id = $2
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed')
+ ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC
)
SELECT session_id, work_dir, runtime_id FROM latest_per_session
-WHERE (
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
+ AND (
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 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]')
)
)
ORDER BY terminal_at DESC
@@ -843,6 +877,7 @@ SET status = 'failed',
session_id = CASE WHEN sqlc.arg('session_rollout_missing') THEN NULL ELSE COALESCE(sqlc.narg('session_id'), session_id) END,
work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),
session_rollout_missing = sqlc.arg('session_rollout_missing'),
+ retired_session_id = COALESCE(sqlc.narg('retired_session_id'), retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
RETURNING *;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 8374a34615..92064e500f 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -136,6 +136,29 @@ SET session_id = COALESCE(sqlc.narg('session_id'), session_id),
updated_at = now()
WHERE id = sqlc.arg('id');
+-- name: ClearChatSessionSessionIfMatches :exec
+-- Drops the chat session's resume pointer, but only while it still points at
+-- the exact session the caller proved unresumable.
+--
+-- The claim handler reads chat_session.session_id FIRST and only falls back to
+-- GetLastChatTaskSession when it is empty, so a poisoned pointer here bypasses
+-- every filter that query applies. Declining to OVERWRITE the pointer on a
+-- resume-unsafe failure — which is all the fail path used to do — leaves the
+-- dead session in place and the next turn resumes it (GH #6066).
+--
+-- The session_id + runtime_id predicate is what makes this safe to run in the
+-- fail transaction: a concurrent turn that has already written a NEW pointer
+-- does not match, so its healthy session survives instead of being cleared by
+-- a slower sibling's failure. work_dir is deliberately left alone — the
+-- directory is still reusable, only the conversation is not.
+UPDATE chat_session
+SET session_id = NULL,
+ runtime_id = NULL,
+ updated_at = now()
+WHERE id = sqlc.arg('id')
+ AND session_id = sqlc.arg('session_id')
+ AND runtime_id = sqlc.arg('runtime_id');
+
-- name: LockChatSessionForDelete :one
-- Acquires an exclusive (FOR UPDATE) row lock on chat_session(id). Used by
-- the delete path so that a concurrent SendChatMessage cannot enqueue a new
@@ -387,17 +410,46 @@ RETURNING *;
-- excluded because replaying those sessions deterministically reproduces the
-- same terminal state. Keep this list in sync with resumeUnsafeFailureReason
-- and GetLastTaskSession.
-SELECT session_id, work_dir, runtime_id FROM agent_task_queue
-WHERE chat_session_id = $1
+--
+-- The regex pair mirrors GetLastTaskSession's provider-agnostic guard for an
+-- empty message baked into the conversation history: both must match, and
+-- both track emptyContentRe / historyMessageLocatorRe in
+-- pkg/taskfailure/resume.go (GH #6066).
+--
+-- Selection is per-session, not per-row, and retired sessions are excluded —
+-- both mirroring GetLastTaskSession, which this query had drifted away from.
+-- A plain row-level filter reopens the poisoning wormhole GH #5975 closed on
+-- the issue side: it drops the newest poisoned row for a session and then
+-- happily falls back to an OLDER completed row carrying the same dead
+-- session_id. Judging each session by its LATEST terminal state means a newer
+-- poisoned row invalidates the whole session, while a genuinely different
+-- healthy session stays eligible.
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.chat_session_id = $1
+ AND r.retired_session_id IS NOT NULL
+), 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
+ FROM agent_task_queue t
+ WHERE t.chat_session_id = $1
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed')
+ ORDER BY t.session_id, t.completed_at DESC
+)
+SELECT session_id, work_dir, runtime_id FROM latest_per_session
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
AND (
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, '') ~* '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]')
)
)
- AND session_id IS NOT NULL
ORDER BY completed_at DESC
LIMIT 1;
diff --git a/server/pkg/taskfailure/resume.go b/server/pkg/taskfailure/resume.go
new file mode 100644
index 0000000000..9cbb6d4e8f
--- /dev/null
+++ b/server/pkg/taskfailure/resume.go
@@ -0,0 +1,55 @@
+package taskfailure
+
+import "regexp"
+
+// UnresumableHistory reports whether an agent error means the conversation
+// history itself can no longer be sent to the provider: a message already
+// baked into the transcript carries empty content, so every resume of that
+// session replays the same body and reproduces the same rejection.
+//
+// This predicate is deliberately provider-agnostic, and that is the whole
+// point. The original detector paired "400" with "invalid_request_error"
+// (see classifyPoisonedError in internal/daemon), which is the Anthropic wire
+// shape. The identical defect is reported by other providers with neither
+// token present:
+//
+// Invalid request: the message at position 37 with role 'assistant' must not be empty (GH #6066)
+// provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty (GH #5760)
+// messages.37: all messages must have non-empty content ... (Anthropic)
+// messages[43].content: content must not be empty
+//
+// Keying on a status code or a provider name means missing the next backend
+// that words it differently — Multica supports 17 of them and holds only an
+// opaque session id, so it cannot know which CLIs write a truncated
+// transcript. What all of these DO state is the two things that define the
+// defect: that some content is empty, and which message in the history it
+// belongs to.
+//
+// Both signals are required, and that is what keeps the predicate narrow. A
+// tool reporting "commit message must not be empty" has no message locator
+// and does not match; a diff mentioning "messages[3]" without an emptiness
+// complaint does not match either. Erring toward NOT matching is the safe
+// direction: a miss leaves today's behaviour (the task fails and the user
+// retries), while a false positive would discard a healthy session pointer
+// and lose conversation context.
+func UnresumableHistory(errText string) bool {
+ if errText == "" {
+ return false
+ }
+ return emptyContentRe.MatchString(errText) && historyMessageLocatorRe.MatchString(errText)
+}
+
+// emptyContentRe matches the provider's complaint that a content field is
+// empty, in the wordings observed across providers.
+var emptyContentRe = regexp.MustCompile(`(?i)must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty`)
+
+// historyMessageLocatorRe matches the part of the error that points at a
+// message inside the conversation history — a role name, an index, or a
+// position. Without one of these an emptiness complaint is about some other
+// field entirely and says nothing about the transcript.
+//
+// Keep in sync with the equivalent regex in the GetLastTaskSession /
+// GetLastChatTaskSession resume queries (pkg/db/queries), which apply the same
+// text guard server-side for rows an older daemon classified as
+// agent_error.unknown.
+var historyMessageLocatorRe = regexp.MustCompile(`(?i)role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]`)
diff --git a/server/pkg/taskfailure/resume_test.go b/server/pkg/taskfailure/resume_test.go
new file mode 100644
index 0000000000..35d69b8dfa
--- /dev/null
+++ b/server/pkg/taskfailure/resume_test.go
@@ -0,0 +1,146 @@
+package taskfailure
+
+import "testing"
+
+// TestUnresumableHistory pins the predicate against the real provider wordings
+// collected from the field. The positives are verbatim strings from user
+// reports; the negatives are the shapes that must keep resuming, because a
+// false positive throws away a healthy conversation.
+func TestUnresumableHistory(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ errMsg string
+ want bool
+ }{
+ // --- Positives: an empty message is baked into the transcript. ---
+ {
+ // GH #6066, verbatim from the reporter's screenshot. Carries
+ // neither "invalid_request_error" nor a bare "400", which is
+ // exactly why the Anthropic-shaped detector missed it.
+ name: "gh6066 invalid request with position and role",
+ errMsg: "Invalid request: the message at position 37 with role 'assistant' must not be empty",
+ want: true,
+ },
+ {
+ // GH #5760, from a manual `kimi -S <session> -p ping` repro.
+ name: "gh5760 kimi provider api_error",
+ errMsg: "provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty",
+ want: true,
+ },
+ {
+ name: "kimi wrapped by the acp sniffer",
+ errMsg: "kimi provider error: the message at position 43 with role 'assistant' must not be empty",
+ want: true,
+ },
+ {
+ // Anthropic's own wording for the same defect.
+ name: "anthropic indexed message non-empty content",
+ errMsg: `API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.37: all messages must have non-empty content except for the optional final assistant message"}}`,
+ want: true,
+ },
+ {
+ name: "openai-compatible indexed content field",
+ errMsg: "messages[43].content: content must not be empty",
+ want: true,
+ },
+ {
+ name: "double-quoted role",
+ errMsg: `Invalid request: the message with role "assistant" must not be empty`,
+ want: true,
+ },
+ {
+ name: "unspaced role token",
+ errMsg: "invalid_request: role=assistant content cannot be empty",
+ want: true,
+ },
+ {
+ name: "prose wording",
+ errMsg: "The final assistant message must not be empty.",
+ want: true,
+ },
+
+ // --- Negatives: emptiness complaints that are NOT about history. ---
+ {
+ // The single most likely false positive: a tool or validator
+ // complaining about a field. No locator into the message history.
+ name: "tool validation error",
+ errMsg: "validation error: field must not be empty",
+ want: false,
+ },
+ {
+ name: "git commit message",
+ errMsg: "Aborting commit due to empty commit message: commit message must not be empty",
+ want: false,
+ },
+ {
+ name: "empty api key",
+ errMsg: "config error: api key must not be empty",
+ want: false,
+ },
+
+ // --- Negatives: history locator without an emptiness complaint. ---
+ {
+ name: "oversized image in history",
+ errMsg: "messages[3].content[0].image.source.base64.data: image dimensions exceed max allowed size",
+ want: false,
+ },
+ {
+ name: "assistant message mentioned in a normal error",
+ errMsg: "could not render assistant message: template failure",
+ want: false,
+ },
+
+ // --- Negatives: transient failures that MUST keep the session. ---
+ {
+ name: "rate limit",
+ errMsg: "API Error: 429 rate_limit_error: too many requests",
+ want: false,
+ },
+ {
+ name: "provider 5xx",
+ errMsg: "provider.api_error: 503 upstream temporarily unavailable",
+ want: false,
+ },
+ {
+ name: "network drop",
+ errMsg: "Connection closed mid-response",
+ want: false,
+ },
+ {
+ name: "empty input",
+ errMsg: "",
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := UnresumableHistory(tc.errMsg); got != tc.want {
+ t.Fatalf("UnresumableHistory(%q) = %v, want %v", tc.errMsg, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestUnresumableHistoryIsStatusAndProviderAgnostic is the regression that
+// keeps this from sliding back into a per-provider string match. The same
+// defect wearing four different provider costumes must classify identically —
+// that is the property GH #6066 and GH #5760 both needed and neither had.
+func TestUnresumableHistoryIsStatusAndProviderAgnostic(t *testing.T) {
+ t.Parallel()
+
+ sameDefect := []string{
+ "Invalid request: the message at position 37 with role 'assistant' must not be empty",
+ "provider.api_error: 400 the message at position 43 with role 'assistant' must not be empty",
+ "kimi provider error: the message at position 1 with role 'assistant' must not be empty",
+ "messages.12: all messages must have non-empty content",
+ }
+ for _, errMsg := range sameDefect {
+ if !UnresumableHistory(errMsg) {
+ t.Errorf("provider wording must not change the verdict, missed: %q", errMsg)
+ }
+ }
+}