Skip to content

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

Go

fix(task): auto-retry transient "Connection closed mid-response" like chat (MUL-4910) (#5565)

Bohan Jiang6dba74c3c1b3
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
new file mode 100644
index 0000000000..5c3b545811
--- /dev/null
+++ b/server/internal/service/retry_deferred_test.go
@@ -0,0 +1,169 @@
+package service
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestCreateRetryTaskFireAtControlsDeferral locks in the SQL half of the
+// three-tier provider_network schedule (MUL-4910): CreateRetryTask inserts a
+// 'deferred' child carrying fire_at when the fire_at param is set (the final,
+// backed-off attempt) and an immediately-claimable 'queued' child when it is
+// NULL (every other retry). Both continue the resume chain — force_fresh_session
+// stays false for a provider_network parent.
+func TestCreateRetryTaskFireAtControlsDeferral(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ _, _, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // agent_task_queue.runtime_id is NOT NULL; reuse the fixture agent's runtime.
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("read agent runtime: %v", err)
+ }
+
+ // Parent: a provider_network failure on its second attempt — the point at
+ // which the schedule wants the next (final) retry deferred.
+ var parentID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts, failure_reason, session_id, work_dir)
+ VALUES ($1, $2, $3, 'failed', 0, 2, 2, 'agent_error.provider_network', 'src-session', '/tmp/src-workdir')
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&parentID); err != nil {
+ t.Fatalf("insert parent task: %v", err)
+ }
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE parent_task_id = $1 OR id = $1`, parentID)
+ })
+
+ cases := []struct {
+ name string
+ fireAt pgtype.Timestamptz
+ maxAttempts pgtype.Int4
+ wantStatus string
+ wantFireAt bool
+ wantMaxAttempts int32
+ }{
+ // Final tier: deferred, and the effective budget (3) written into the row
+ // so it self-describes as attempt=3/max_attempts=3, not attempt=3/max=2.
+ {"deferred final tier persists budget", pgtype.Timestamptz{Time: time.Now().Add(5 * time.Second), Valid: true}, pgtype.Int4{Int32: 3, Valid: true}, "deferred", true, 3},
+ // NULL max_attempts inherits the parent's column (COALESCE fallback).
+ {"queued immediate tier inherits budget", pgtype.Timestamptz{}, pgtype.Int4{}, "queued", false, 2},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ child, err := q.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: parentID, FireAt: tc.fireAt, MaxAttempts: tc.maxAttempts})
+ if err != nil {
+ t.Fatalf("CreateRetryTask: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, child.ID) })
+
+ if child.Status != tc.wantStatus {
+ t.Errorf("status = %q, want %q", child.Status, tc.wantStatus)
+ }
+ if child.FireAt.Valid != tc.wantFireAt {
+ t.Errorf("fire_at valid = %v, want %v", child.FireAt.Valid, tc.wantFireAt)
+ }
+ if child.Attempt != 3 {
+ t.Errorf("attempt = %d, want 3 (parent attempt 2 + 1)", child.Attempt)
+ }
+ if child.MaxAttempts != tc.wantMaxAttempts {
+ t.Errorf("max_attempts = %d, want %d", child.MaxAttempts, tc.wantMaxAttempts)
+ }
+ // provider_network is resume-safe: the retry must continue the session.
+ if child.ForceFreshSession {
+ t.Errorf("force_fresh_session = true, want false (provider_network resumes) for %s", util.UUIDToString(child.ID))
+ }
+ })
+ }
+}
+
+// TestFailTaskProviderNetworkBudget is the end-to-end guard for Elon's must-fix
+// (MUL-4910): FailTask must (1) grant provider_network its raised budget and
+// persist a self-consistent child (attempt=3, max_attempts=3), and (2) still
+// honour max_attempts=1 as "auto-retry disabled" — no child at all.
+func TestFailTaskProviderNetworkBudget(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ _, _, agentID, issueID := seedAttributionFixture(t, pool)
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("read agent runtime: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ attempt int32
+ maxAttempts int32
+ wantChild bool
+ wantAttempt int32
+ wantMax int32
+ wantDeferred bool
+ }{
+ // Default budget, failing on the 2nd attempt → deferred final tier that
+ // records attempt=3 AND max_attempts=3 (no contradictory row).
+ {"final tier persists raised budget", 2, 2, true, 3, 3, true},
+ // Default budget, failing on the 1st attempt → immediate 2nd tier.
+ {"first retry is immediate", 1, 2, true, 2, 3, false},
+ // max_attempts=1 disables auto-retry — even provider_network gets none.
+ {"disabled budget is never revived", 1, 1, false, 0, 0, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var parentID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts, session_id, work_dir)
+ VALUES ($1, $2, $3, 'running', 0, $4, $5, 'src-session', '/tmp/src-workdir')
+ RETURNING id
+ `, agentID, runtimeID, issueID, tc.attempt, tc.maxAttempts).Scan(&parentID); err != nil {
+ t.Fatalf("insert parent task: %v", err)
+ }
+ t.Cleanup(func() {
+ 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"); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+
+ var (
+ childAttempt, childMax int32
+ childStatus string
+ n int
+ )
+ row := pool.QueryRow(ctx, `SELECT count(*), coalesce(max(attempt),0), coalesce(max(max_attempts),0), coalesce(max(status),'') FROM agent_task_queue WHERE parent_task_id = $1`, parentID)
+ if err := row.Scan(&n, &childAttempt, &childMax, &childStatus); err != nil {
+ t.Fatalf("read child: %v", err)
+ }
+ if !tc.wantChild {
+ if n != 0 {
+ t.Fatalf("expected no retry child, got %d", n)
+ }
+ return
+ }
+ if n != 1 {
+ t.Fatalf("expected exactly one retry child, got %d", n)
+ }
+ if childAttempt != tc.wantAttempt {
+ t.Errorf("child attempt = %d, want %d", childAttempt, tc.wantAttempt)
+ }
+ if childMax != tc.wantMax {
+ t.Errorf("child max_attempts = %d, want %d (self-consistent budget)", childMax, tc.wantMax)
+ }
+ gotDeferred := childStatus == "deferred"
+ if gotDeferred != tc.wantDeferred {
+ t.Errorf("child status = %q, want deferred=%v", childStatus, tc.wantDeferred)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 3b08eb215d..2900d42085 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2924,8 +2924,10 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// here — before the transaction — and only for retryable failures, so the
// common agent_error path skips this work entirely.
var (
- wantRetry bool
- retryOverlay runtimeMCPOverlayData
+ wantRetry bool
+ retryOverlay runtimeMCPOverlayData
+ retryFireAt pgtype.Timestamptz
+ retryMaxAttempts pgtype.Int4
)
if retryableReasons[failureReason] {
if parent, perr := s.Queries.GetAgentTask(ctx, taskID); perr != nil {
@@ -2933,6 +2935,16 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
"task_id", util.UUIDToString(taskID), "error", perr)
} else if retryEligible(failureReason, parent) {
wantRetry = true
+ // Persist the reason-aware effective budget into the child so the
+ // retry chain self-describes (e.g. provider_network → max_attempts=3),
+ // rather than leaking a contradictory attempt=N/max_attempts=2 row.
+ retryMaxAttempts = pgtype.Int4{Int32: retryAttemptCeiling(failureReason, parent.MaxAttempts), Valid: true}
+ // Defer this attempt when the reason's schedule calls for a backoff
+ // (provider_network's final attempt waits ~5s); a zero delay leaves
+ // fire_at NULL so the child is created immediately-claimable.
+ if delay := retryDelayForAttempt(failureReason, parent.Attempt); delay > 0 {
+ retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
+ }
if agent, aerr := s.Queries.GetAgent(ctx, parent.AgentID); aerr != nil {
// Best-effort: a missing overlay is not retry-fatal — the child
// simply runs without the Composio overlay.
@@ -2987,6 +2999,8 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
if wantRetry {
child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{
ID: taskID,
+ FireAt: retryFireAt,
+ MaxAttempts: retryMaxAttempts,
RuntimeMcpOverlay: retryOverlay.Overlay,
RuntimeConnectedApps: retryOverlay.ConnectedApps,
})
@@ -3029,7 +3043,9 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// The auto-retry child (if any) was created inside the transaction above so
// no newer chat task could jump ahead of it. Surface it now: broadcast
// queued first, then notify the daemon — see EnqueueTaskForIssue for the
- // ordering rationale.
+ // ordering rationale. A deferred child (backoff armed via fire_at) is NOT
+ // queued yet: PromoteDueDeferredTasksForRuntime emits its queued event and
+ // daemon wakeup when fire_at arrives, so announcing it here would be wrong.
if retried != nil {
slog.Info("task auto-retry enqueued",
"parent_task_id", util.UUIDToString(task.ID),
@@ -3037,9 +3053,12 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
"reason", failureReason,
"attempt", retried.Attempt,
"max_attempts", retried.MaxAttempts,
+ "status", retried.Status,
)
- s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, *retried)
- s.NotifyTaskEnqueued(ctx, *retried)
+ if retried.Status == "queued" {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, *retried)
+ s.NotifyTaskEnqueued(ctx, *retried)
+ }
}
// Skip the per-failure system comment when we'll immediately retry —
@@ -3093,11 +3112,65 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// allowed to act on. Agent-side errors (compile failures, model rejections,
// etc.) are intentionally excluded — those are real problems that the user
// should see, not infrastructure flakiness.
+//
+// The one agent_error.* exception is provider_network: a mid-stream provider
+// disconnect (e.g. Claude Code's "API Error: Connection closed mid-response")
+// is transient infrastructure flakiness, not an agent decision. Unattended
+// issue runs otherwise terminate on it, while interactive chat only survives
+// because the CLI's own in-process retry happens to recover first — so we make
+// the platform retry it directly (MUL-4910). It is resume-safe (not in
+// resumeUnsafeFailureReason), so the retry child inherits the session and
+// continues the truncated conversation rather than restarting from scratch.
var retryableReasons = map[string]bool{
"runtime_offline": true,
"runtime_recovery": true,
"timeout": true,
"codex_semantic_inactivity": true,
+ string(taskfailure.ReasonAgentProviderNetwork): true,
+}
+
+// Transient provider stream cuts (provider_network) get a bespoke three-tier
+// schedule (MUL-4910): first run + immediate retry + one retry deferred ~5s.
+// A blip that survives the immediate retry gets a short cooldown before the
+// final attempt instead of firing back-to-back. Every other retryable reason
+// keeps the task's generic max_attempts ceiling and retries immediately.
+const (
+ providerNetworkMaxAttempts = 3
+ providerNetworkFinalRetryWait = 5 * time.Second
+)
+
+// retryAttemptCeiling reports how many attempts the auto-retry path allows for
+// a failure reason. It only ever WIDENS the task's generic max_attempts, and
+// only for reasons with a bespoke schedule; everything else keeps the column's
+// value (default 2 = first run + one retry).
+//
+// max_attempts <= 1 explicitly disables auto-retry (055_task_lease_and_retry.up
+// .sql: "1 disables retry"), so it is never overridden — a disabled task must
+// not be revived by a raised ceiling. Callers persist this value into the retry
+// child (CreateRetryTask's max_attempts) so the row stays self-consistent:
+// provider_network's chain records attempt=3, max_attempts=3, not a
+// contradictory attempt=3, max_attempts=2 (MUL-4910).
+func retryAttemptCeiling(reason string, taskMaxAttempts int32) int32 {
+ if taskMaxAttempts <= 1 {
+ return taskMaxAttempts
+ }
+ if reason == string(taskfailure.ReasonAgentProviderNetwork) && taskMaxAttempts < providerNetworkMaxAttempts {
+ return providerNetworkMaxAttempts
+ }
+ return taskMaxAttempts
+}
+
+// retryDelayForAttempt reports how long to defer the NEXT attempt after a
+// failure at failedAttempt. Only provider_network's final attempt is deferred
+// (~5s); every other retry — including provider_network's first — is immediate
+// (zero delay → the child is created 'queued', claimable at once). Callers pass
+// the returned delay to CreateRetryTask via fire_at.
+func retryDelayForAttempt(reason string, failedAttempt int32) time.Duration {
+ if reason == string(taskfailure.ReasonAgentProviderNetwork) &&
+ failedAttempt >= providerNetworkMaxAttempts-1 {
+ return providerNetworkFinalRetryWait
+ }
+ return 0
}
func resumeUnsafeFailureReason(reason string) bool {
@@ -3143,7 +3216,7 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {
// so both agree on which failures re-run.
func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
return retryableReasons[failureReason] &&
- t.Attempt < t.MaxAttempts &&
+ t.Attempt < retryAttemptCeiling(failureReason, t.MaxAttempts) &&
!t.AutopilotRunID.Valid &&
(t.IssueID.Valid || t.ChatSessionID.Valid)
}
@@ -3169,11 +3242,17 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
if !retryableReasons[reason] {
return nil, nil
}
- if parent.Attempt >= parent.MaxAttempts {
+ // Use the reason-aware ceiling, not the raw max_attempts column, so an
+ // orphaned provider_network task recovered on its 2nd attempt is still
+ // allowed its deferred 3rd attempt (retryAttemptCeiling raises the ceiling
+ // to 3). Kept in sync with retryEligible below, which applies the same
+ // ceiling to the primary FailTask path.
+ if parent.Attempt >= retryAttemptCeiling(reason, parent.MaxAttempts) {
slog.Info("task auto-retry skipped: budget exhausted",
"task_id", util.UUIDToString(parent.ID),
"attempt", parent.Attempt,
"max_attempts", parent.MaxAttempts,
+ "ceiling", retryAttemptCeiling(reason, parent.MaxAttempts),
)
return nil, nil
}
@@ -3198,8 +3277,18 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
} else {
runtimeMCPOverlay = s.buildRuntimeMCPOverlay(ctx, parent.OriginatorUserID, agent)
}
+ // Mirror FailTask's in-tx backoff + effective-budget persistence: defer the
+ // final provider_network attempt ~5s via fire_at (zero delay leaves fire_at
+ // NULL for an immediate child), and write the reason-aware ceiling into the
+ // child's max_attempts so the retry chain stays self-consistent.
+ var retryFireAt pgtype.Timestamptz
+ if delay := retryDelayForAttempt(reason, parent.Attempt); delay > 0 {
+ retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
+ }
child, err := s.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{
ID: parent.ID,
+ FireAt: retryFireAt,
+ MaxAttempts: pgtype.Int4{Int32: retryAttemptCeiling(reason, parent.MaxAttempts), Valid: true},
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
})
@@ -3217,13 +3306,16 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
"reason", reason,
"attempt", child.Attempt,
"max_attempts", child.MaxAttempts,
+ "status", child.Status,
)
- // Retry creates a fresh queued row, same status transition (∅ → queued)
- // as EnqueueTaskFor*. Broadcast queued first, then notify the daemon —
- // see EnqueueTaskForIssue for ordering rationale.
- //
- s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, child)
- s.NotifyTaskEnqueued(ctx, child)
+ // A queued child transitions ∅ → queued (same as EnqueueTaskFor*): broadcast
+ // queued first, then notify the daemon — see EnqueueTaskForIssue for ordering
+ // rationale. A deferred child (backoff armed) stays inert until
+ // PromoteDueDeferredTasksForRuntime fires its queued event + wakeup.
+ if child.Status == "queued" {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, child)
+ s.NotifyTaskEnqueued(ctx, child)
+ }
return &child, nil
}
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 14d96089cc..dfa1a60b9a 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -4,6 +4,7 @@ import (
"context"
"strings"
"testing"
+ "time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
@@ -167,6 +168,80 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
}
}
+// TestProviderNetworkRetrySchedule locks in the three-tier schedule for a
+// transient provider stream cut (MUL-4910): first run + immediate retry + one
+// retry deferred ~5s, and only for provider_network — other retryable reasons
+// keep their generic max_attempts=2 (single, immediate retry).
+func TestProviderNetworkRetrySchedule(t *testing.T) {
+ const provNet = "agent_error.provider_network"
+
+ // Attempt ceiling: provider_network is raised to 3, but only ever WIDENS the
+ // budget and never overrides the max_attempts<=1 "retry disabled" contract.
+ ceilingCases := []struct {
+ reason string
+ max int32
+ want int32
+ }{
+ {provNet, 2, providerNetworkMaxAttempts}, // default budget → raised to 3
+ {provNet, 1, 1}, // disabled → stays disabled, not revived
+ {provNet, 5, 5}, // higher configured budget → kept (widen-only)
+ {"timeout", 2, 2}, // unrelated reason → column value untouched
+ {"timeout", 1, 1}, // unrelated + disabled → untouched
+ }
+ for _, tc := range ceilingCases {
+ if got := retryAttemptCeiling(tc.reason, tc.max); got != tc.want {
+ t.Errorf("ceiling(%q, %d) = %d, want %d", tc.reason, tc.max, got, tc.want)
+ }
+ }
+
+ // Backoff: only provider_network's final attempt (after the 2nd failure) is
+ // deferred; its first retry and every other reason are immediate.
+ delayCases := []struct {
+ reason string
+ failedAttempt int32
+ want time.Duration
+ }{
+ {provNet, 1, 0}, // first failure → immediate retry
+ {provNet, 2, providerNetworkFinalRetryWait}, // second failure → 5s-deferred retry
+ {"timeout", 2, 0}, // unrelated reason → never deferred
+ }
+ for _, tc := range delayCases {
+ if got := retryDelayForAttempt(tc.reason, tc.failedAttempt); got != tc.want {
+ t.Errorf("retryDelayForAttempt(%q, %d) = %s, want %s", tc.reason, tc.failedAttempt, got, tc.want)
+ }
+ }
+
+ // Eligibility across the whole chain. mkTask has an issue link and no
+ // autopilot run so only the reason/attempt/ceiling gate is exercised.
+ mkTask := func(attempt, max int32) db.AgentTaskQueue {
+ return db.AgentTaskQueue{
+ Attempt: attempt,
+ MaxAttempts: max,
+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},
+ }
+ }
+ eligCases := []struct {
+ name string
+ reason string
+ attempt int32
+ max int32
+ want bool
+ }{
+ {"provider_network first run retries", provNet, 1, 2, true},
+ {"provider_network second run still retries (deferred tier)", provNet, 2, 2, true},
+ {"provider_network third run is the ceiling", provNet, 3, 2, false},
+ {"provider_network with retry disabled (max_attempts=1) never retries", provNet, 1, 1, false},
+ {"timeout keeps single immediate retry", "timeout", 1, 2, true},
+ {"timeout exhausts at attempt 2", "timeout", 2, 2, false},
+ {"non-retryable reason never retries", "agent_error.unknown", 1, 2, false},
+ }
+ for _, tc := range eligCases {
+ if got := retryEligible(tc.reason, mkTask(tc.attempt, tc.max)); got != tc.want {
+ t.Errorf("%s: retryEligible(%q, attempt=%d/max=%d) = %v, want %v", tc.name, tc.reason, tc.attempt, tc.max, got, tc.want)
+ }
+ }
+}
+
func TestTaskFailureClassifiers(t *testing.T) {
cases := []struct {
reason string
@@ -176,6 +251,9 @@ func TestTaskFailureClassifiers(t *testing.T) {
}{
{reason: "timeout", wantType: "timeout", wantResumeOK: true, wantRetry: true},
{reason: "codex_semantic_inactivity", wantType: "timeout", wantResumeOK: false, wantRetry: true},
+ // Transient mid-stream provider disconnect (MUL-4910): retryable, and
+ // resume-safe so the retry continues the truncated conversation.
+ {reason: "agent_error.provider_network", wantType: "agent_error", wantResumeOK: true, wantRetry: true},
{reason: "runtime_recovery", wantType: "runtime", wantResumeOK: true, wantRetry: true},
{reason: "iteration_limit", wantType: "agent_output", wantResumeOK: false, wantRetry: false},
{reason: "api_invalid_request", wantType: "agent_error", wantResumeOK: false, wantRetry: false},
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 7c7f7c4968..00da62d99e 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -1788,35 +1788,37 @@ INSERT INTO agent_task_queue (
squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
- chat_input_task_id
+ chat_input_task_id, fire_at
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued',
+ CASE WHEN $2::timestamptz IS NOT NULL THEN 'deferred' ELSE 'queued' END,
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
- p.attempt + 1, p.max_attempts, p.id,
+ p.attempt + 1, COALESCE($3::int, p.max_attempts), p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
p.is_leader_task,
p.squad_id,
p.originator_user_id,
p.accountable_user_id,
- $2,
- $3,
+ $4,
+ $5,
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
- p.chat_input_task_id
+ 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
`
type CreateRetryTaskParams struct {
- ID pgtype.UUID `json:"id"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ ID pgtype.UUID `json:"id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ MaxAttempts pgtype.Int4 `json:"max_attempts"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
}
// Clones a parent task into a fresh queued attempt. Carries forward the
@@ -1857,8 +1859,28 @@ type CreateRetryTaskParams struct {
// queued while the failing turn was still running — the retry continues the
// older turn first. Combined with creating the retry inside FailTask's
// transaction, this leaves no window for a newer input task to jump ahead.
+//
+// fire_at arms a backoff before the retry: when non-NULL the child is inserted
+// as 'deferred' with that fire_at and stays inert until the existing
+// PromoteDueDeferredTasksForRuntime sweeper (run promote-first on every claim
+// poll) flips it to 'queued'. Used for provider_network's final attempt so it
+// waits ~5s instead of firing back-to-back with the immediate retry (MUL-4910).
+// NULL keeps the historical behaviour: an immediately-claimable 'queued' child.
+//
+// max_attempts overrides the inherited budget when non-NULL (NULL inherits
+// p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
+// here so the row stays self-consistent — e.g. provider_network's chain records
+// attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
+// task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
+// disabled (max_attempts<=1) task, so this only ever widens, never revives.
func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, createRetryTask, arg.ID, arg.RuntimeMcpOverlay, arg.RuntimeConnectedApps)
+ row := q.db.QueryRow(ctx, createRetryTask,
+ arg.ID,
+ arg.FireAt,
+ arg.MaxAttempts,
+ arg.RuntimeMcpOverlay,
+ arg.RuntimeConnectedApps,
+ )
var i AgentTaskQueue
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 0a07179fe3..2a45a938a4 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -326,6 +326,20 @@ WHERE id = $1 AND issue_id IS NULL;
-- queued while the failing turn was still running — the retry continues the
-- older turn first. Combined with creating the retry inside FailTask's
-- transaction, this leaves no window for a newer input task to jump ahead.
+--
+-- fire_at arms a backoff before the retry: when non-NULL the child is inserted
+-- as 'deferred' with that fire_at and stays inert until the existing
+-- PromoteDueDeferredTasksForRuntime sweeper (run promote-first on every claim
+-- poll) flips it to 'queued'. Used for provider_network's final attempt so it
+-- waits ~5s instead of firing back-to-back with the immediate retry (MUL-4910).
+-- NULL keeps the historical behaviour: an immediately-claimable 'queued' child.
+--
+-- max_attempts overrides the inherited budget when non-NULL (NULL inherits
+-- p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
+-- here so the row stays self-consistent — e.g. provider_network's chain records
+-- attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
+-- task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
+-- disabled (max_attempts<=1) task, so this only ever widens, never revives.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
@@ -334,16 +348,16 @@ INSERT INTO agent_task_queue (
squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
- chat_input_task_id
+ chat_input_task_id, fire_at
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued',
+ CASE WHEN sqlc.narg(fire_at)::timestamptz IS NOT NULL THEN 'deferred' ELSE 'queued' END,
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
- p.attempt + 1, p.max_attempts, p.id,
+ p.attempt + 1, COALESCE(sqlc.narg(max_attempts)::int, p.max_attempts), p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
p.is_leader_task,
p.squad_id,
@@ -353,7 +367,7 @@ SELECT
sqlc.narg(runtime_connected_apps),
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
- p.chat_input_task_id
+ p.chat_input_task_id, sqlc.narg(fire_at)
FROM agent_task_queue p
WHERE p.id = $1
RETURNING *;
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 86dbda1335..9e33d41a93 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -23,9 +23,11 @@ var providerHTTP5xxRe = regexp.MustCompile(`(^|[^0-9])5[0-9][0-9]([^0-9]|$)`)
// e.g. "402913 tokens", "15290ms", "exit status 4030" — misclassifying process
// or unknown failures as provider billing / rate-limit errors. That pollutes
// failure observability: a genuine process crash gets filed under a provider
-// bucket, masking the real cause on failure dashboards. (It does not change
-// auto-retry — Classify only ever returns agent_error.* reasons, none of which
-// are in internal/service/task.go's retryableReasons set.) The 5xx bucket was
+// bucket, masking the real cause on failure dashboards. (A misfire here still
+// can't cause a spurious retry: the auth / quota / capacity buckets these
+// regexes guard are all non-retryable. The only agent_error.* reason on
+// internal/service/task.go's retryableReasons allowlist is provider_network
+// — MUL-4910 — and these regexes never route into it.) The 5xx bucket was
// already anchored for exactly this reason (MUL-1949); these codes were not.
var (
httpAuthCodeRe = regexp.MustCompile(`(^|[^0-9])(401|403)([^0-9]|$)`)
@@ -158,9 +160,18 @@ func Classify(rawError string) Reason {
return ReasonAgentProviderServerError
// 7. Provider network. Stream cut, dial failures, DNS / I/O
- // timeout below the HTTP layer.
+ // timeout below the HTTP layer. "connection closed" / "mid-response"
+ // catch the Claude Code CLI's mid-stream disconnect
+ // ("API Error: Connection closed mid-response. ...") so a transient cut
+ // lands in the retryable provider_network bucket (with session resume)
+ // instead of falling through to agent_error.unknown / process_failure
+ // and terminating the task (MUL-4910). Checked before rule 13 so the
+ // "... exited with error: exit status N ..." variant still routes here.
+ // Mirror these substrings into the MUL-1949 offline backfill SQL.
case containsAny(lower,
"stream disconnected",
+ "connection closed",
+ "mid-response",
"error sending request",
"unable to connect",
"dial tcp",
diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.go
index 181aea14b3..acdb7dd577 100644
--- a/server/pkg/taskfailure/classify_test.go
+++ b/server/pkg/taskfailure/classify_test.go
@@ -93,6 +93,8 @@ func TestClassifyRules(t *testing.T) {
// 7. Provider network.
{"stream disconnected", "stream disconnected before completion", ReasonAgentProviderNetwork},
+ {"connection closed mid-response", "API Error: Connection closed mid-response. The response above may be incomplete.", ReasonAgentProviderNetwork},
+ {"connection closed with exit status wins over process failure", "claude exited with error: exit status 1\nAPI Error: Connection closed mid-response.", ReasonAgentProviderNetwork},
{"error sending request", "error sending request for url (https://api.example.com/v1)", ReasonAgentProviderNetwork},
{"unable to connect", "unable to connect to provider", ReasonAgentProviderNetwork},
{"dial tcp", "dial tcp 1.2.3.4:443: connect: connection refused", ReasonAgentProviderNetwork},