Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5651: preserve tasks through runtime network partitions (#7129)
Multica Eve22db0b0a2c31
diff --git a/.env.example b/.env.exampleindex 6860330dfd..0c76f9d6e2 100644--- a/.env.example+++ b/.env.example@@ -64,6 +64,10 @@ MULTICA_PUBLIC_URL=# preserves the default behavior and starts shutdown immediately. The platform# termination grace period must cover this hold plus the later shutdown work.MULTICA_SHUTDOWN_HOLD_DURATION=+# How long an offline runtime may reconnect before its in-flight tasks fail.+# Accepts a positive Go duration. The default is 3h; values below 150s are+# clamped to the runtime heartbeat freshness window.+MULTICA_RUNTIME_RECONNECT_GRACE=3h# Comma-separated CIDR list of reverse proxies whose X-Forwarded-For /# X-Real-IP headers the per-IP webhook rate limiter is allowed to trust.# Empty (the default) means "trust no headers" — the limiter usesdiff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 46e8c0d66d..91c7b1fb83 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -39,6 +39,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `AUTH_TOKEN_TTL` | `720h`(30 日) | ブラウザ JWT と cookie の有効期間。Go duration または正の整数秒を受け付けます || `LOG_LEVEL` | アプリのデフォルト | ログレベル || `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 終了シグナル受信後、グレースフルシャットダウンを開始するまでの待機時間 |+| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | オフラインのランタイムが処理中の作業を失敗させずに再接続できる猶予時間。`150s` 未満は `150s` に補正されます |Kubernetes で shutdown hold を設定する場合、`terminationGracePeriodSeconds` は hold と実際のシャットダウンにかかる時間の合計より大きくしてください。diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 97138ede16..befe83c1d0 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -39,6 +39,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `AUTH_TOKEN_TTL` | `720h`(30일) | 브라우저 JWT와 cookie 유효 기간. Go duration 또는 양의 정수 초 허용 || `LOG_LEVEL` | 앱 기본값 | 로그 수준 || `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 종료 신호를 받은 뒤 graceful shutdown을 시작하기 전 대기 시간 |+| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 오프라인 런타임이 진행 중인 작업을 실패시키지 않고 재연결할 수 있는 유예 시간. `150s` 미만은 `150s`로 조정됨 |Kubernetes에서 shutdown hold를 설정하면 `terminationGracePeriodSeconds`가 hold와 실제 종료에 필요한 시간의 합보다 커야 합니다.diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 3eacefaa90..61195a6c26 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -39,6 +39,7 @@ Do not use the default `JWT_SECRET` in production, and do not set `MULTICA_DEV_V| `AUTH_TOKEN_TTL` | `720h` (30 days) | Lifetime of browser JWTs and cookies; accepts a Go duration or a positive integer of seconds || `LOG_LEVEL` | application default | Log level || `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | How long to wait after a termination signal before graceful shutdown begins |+| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | How long an offline runtime may reconnect before its in-flight tasks fail; values below `150s` are clamped |When setting a shutdown hold on Kubernetes, `terminationGracePeriodSeconds` must exceed the hold plus the time the actual shutdown needs.diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex f2ca1a7479..c8ed4ccfff 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -39,6 +39,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `AUTH_TOKEN_TTL` | `720h`(30 天) | 浏览器 JWT 与 cookie 有效期;接受 Go duration 或正整数秒数 || `LOG_LEVEL` | 应用默认 | 日志级别 || `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 收到终止信号后,开始优雅退出前等待多久 |+| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 运行时离线后可重新连接且不终止在途 task 的宽限时间;低于 `150s` 时按 `150s` 处理 |在 Kubernetes 中设置 shutdown hold 时,`terminationGracePeriodSeconds` 要大于 hold 与实际退出所需时间之和。diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 1d9f8e010a..2ca3241017 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -97,6 +97,7 @@ services:MULTICA_DEV_VERIFICATION_CODE: ${MULTICA_DEV_VERIFICATION_CODE:-}MULTICA_APP_URL: ${MULTICA_APP_URL:-http://localhost:3000}MULTICA_SHUTDOWN_HOLD_DURATION: ${MULTICA_SHUTDOWN_HOLD_DURATION:-}+ MULTICA_RUNTIME_RECONNECT_GRACE: ${MULTICA_RUNTIME_RECONNECT_GRACE:-}ALLOW_SIGNUP: ${ALLOW_SIGNUP:-true}ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 9912d6fd78..110b7ebf4e 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -185,6 +185,7 @@ export type TaskFailureReason =| "timeout"| "codex_semantic_inactivity"| "runtime_offline"+ | "runtime_reconnect_timeout"| "runtime_recovery"| "manual";diff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.tsindex 55483e86e6..db2fdef05f 100644--- a/packages/views/agents/components/tabs/task-failure.test.ts+++ b/packages/views/agents/components/tabs/task-failure.test.ts@@ -40,6 +40,12 @@ describe("cancelReasonLabel", () => {});describe("failureReasonLabel", () => {+ it("explains a runtime that never returned during reconnect grace", () => {+ expect(failureReasonLabel("runtime_reconnect_timeout")).toBe(+ "Daemon did not reconnect in time",+ );+ });+it("covers the local_directory bucket the worktree paths write", () => {expect(failureReasonLabel("local_directory_error")).toBe("Local directory error");});diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex ef349f8767..01277f1d98 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -7,7 +7,7 @@// failed tasks no longer have a top-level workload state; failure context// is purely a detail-page concern now.//-// Covers the canonical taxonomy in server/pkg/taskfailure — 7 platform-side+// Covers the canonical taxonomy in server/pkg/taskfailure — platform-side// reasons plus 14 `agent_error.*` sub-reasons — and the pre-MUL-1949 coarse// values still present on historical rows. This used to be a// `Record<TaskFailureReason, string>` indexed with a cast, which silently@@ -18,6 +18,7 @@ const REASON_LABEL: Record<string, string> = {// Platform / scheduler side.queued_expired: "Expired in queue",runtime_offline: "Daemon offline",+ runtime_reconnect_timeout: "Daemon did not reconnect in time",runtime_recovery: "Daemon restarted",timeout: "Task timed out",iteration_limit: "Hit the iteration limit",diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex e8f1d7459f..ac57c5553c 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -469,7 +469,15 @@ func main() {}// Start background sweeper to mark stale runtimes as offline.- go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus)+ runtimeReconnectGrace := envDuration("MULTICA_RUNTIME_RECONNECT_GRACE", defaultRuntimeReconnectGrace)+ if runtimeReconnectGrace < minimumRuntimeReconnectGrace {+ slog.Warn("runtime reconnect grace is shorter than heartbeat freshness; clamping",+ "configured", runtimeReconnectGrace,+ "minimum", minimumRuntimeReconnectGrace,+ )+ runtimeReconnectGrace = minimumRuntimeReconnectGrace+ }+ go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus, runtimeReconnectGrace)go heartbeatScheduler.Run(sweepCtx)go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())go runDBStatsLogger(sweepCtx, pool)diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 00b295bf64..857d80b78b 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -25,15 +25,25 @@ const (// sweepInterval is how often we check for stale runtimes and tasks.sweepInterval = 30 * time.Second// staleThresholdSeconds marks runtimes offline if no heartbeat for this- // long. Must be strictly greater than runtimeHeartbeatDBFlushInterval- // (60s in handler/daemon.go) plus one daemon heartbeat cycle (~15s)- // plus the BatchedHeartbeatScheduler tick interval (~30s) so the DB- // stale window never trips on an alive-but-DB-lagging runtime when the- // sweeper's Redis check errors and we fall back to the DB.- // 150s leaves a 45s buffer above the 105s worst-case DB age, and keeps- // detection latency for a genuinely-dead runtime under staleThreshold +- // sweepInterval = 180s (~3 minutes).- staleThresholdSeconds = 150.0+ // long. The heartbeat timing derivation lives with the shared service+ // constant so every task release path uses the same eligibility window.+ staleThresholdSeconds = service.RuntimeClaimFreshnessSeconds+ // defaultRuntimeReconnectGrace keeps locally-running work alive through a+ // sustained API/network partition. Runtime state still flips offline after+ // staleThresholdSeconds so the UI remains truthful; only task termination is+ // delayed. A daemon that actually restarts bypasses this grace through the+ // explicit RecoverOrphanedTasksForRuntime path.+ defaultRuntimeReconnectGrace = 3 * time.Hour+ // A reconnect grace below the heartbeat freshness window would allow the+ // stale-task backstop to fail work while the same runtime was still eligible+ // to claim new work. Clamp configuration to keep those policies ordered.+ minimumRuntimeReconnectGrace = time.Duration(staleThresholdSeconds) * time.Second+ // offlineTaskFailBatchSize bounds in-flight tasks failed for long-offline+ // runtimes in one tick.+ offlineTaskFailBatchSize = 500+ // reconnectRetryExpireBatchSize bounds deferred recovery retries that reach+ // their terminal reconnect deadline in one tick.+ reconnectRetryExpireBatchSize = 500// offlineRuntimeTTLSeconds deletes offline runtimes with no active agents// after this duration. 7 days gives users plenty of time to restart daemons.offlineRuntimeTTLSeconds = 7 * 24 * 3600.0@@ -111,7 +121,7 @@ type runtimeGCTxStarter interface {// hot heartbeat path; the DB is allowed to lag up to runtimeHeartbeatDBFlushInterval).// When liveness is unavailable or errors, we fall back to trusting the DB// stale window — that is the original behavior.-func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {+func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration) {ticker := time.NewTicker(sweepInterval)defer ticker.Stop()@@ -121,7 +131,9 @@ func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queriereturncase <-ticker.C:sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)- sweepStaleTasks(ctx, queries, taskSvc, bus)+ sweepOfflineRuntimeTasks(ctx, queries, taskSvc, reconnectGrace)+ sweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)+ sweepStaleTasks(ctx, queries, taskSvc, bus, reconnectGrace)sweepExpiredQueuedTasks(ctx, queries, taskSvc)sweepDeferredChatFinalizations(ctx, queries, taskSvc)gcRuntimes(ctx, txStarter, queries, taskSvc.Metrics, bus)@@ -129,8 +141,9 @@ func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, querie}}-// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated,-// then fails any tasks belonging to those offline runtimes.+// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated. Task+// termination is a separate every-tick stage so reconnect grace is measured+// independently of the one tick where the runtime first flips offline.func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {candidates, err := queries.SelectStaleOnlineRuntimes(ctx, staleThresholdSeconds)if err != nil {@@ -189,15 +202,6 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handlslog.Info("runtime sweeper: marked stale runtimes offline", "count", len(staleRows), "workspaces", len(workspaces))- // Fail orphaned tasks (dispatched/running) whose runtimes just went offline.- failedTasks, err := queries.FailTasksForOfflineRuntimes(ctx)- if err != nil {- slog.Warn("runtime sweeper: failed to clean up stale tasks", "error", err)- } else if len(failedTasks) > 0 {- slog.Info("runtime sweeper: failed orphaned tasks", "count", len(failedTasks))- taskSvc.HandleFailedTasks(ctx, failedTasks)- }-// Notify frontend clients so they re-fetch runtime list.for wsID := range workspaces {bus.Publish(events.Event{@@ -211,6 +215,48 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handl}}+// sweepOfflineRuntimeTasks terminates work only after the runtime's last+// heartbeat has exceeded the bounded reconnect grace. Running it every tick is+// essential: the grace usually expires long after sweepStaleRuntimes performed+// the one-time online→offline transition.+func sweepOfflineRuntimeTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) {+ failedTasks, err := queries.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{+ ReconnectGraceSecs: reconnectGrace.Seconds(),+ MaxPerTick: offlineTaskFailBatchSize,+ })+ if err != nil {+ slog.Warn("runtime sweeper: failed to clean up long-offline tasks", "error", err)+ return+ }+ if len(failedTasks) == 0 {+ return+ }++ slog.Info("runtime sweeper: failed tasks beyond reconnect grace", "count", len(failedTasks))+ taskSvc.HandleFailedTasks(ctx, failedTasks)+}++// sweepExpiredRuntimeReconnectRetries gives health-gated retry waiting a+// bounded terminal path. Without this stage a daemon that never returns leaves+// the issue active and prevents its runtime from ever becoming GC-eligible.+func sweepExpiredRuntimeReconnectRetries(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) {+ failedTasks, err := queries.FailExpiredRuntimeReconnectRetries(ctx, db.FailExpiredRuntimeReconnectRetriesParams{+ ReconnectGraceSecs: reconnectGrace.Seconds(),+ RuntimeStaleSecs: staleThresholdSeconds,+ MaxPerTick: reconnectRetryExpireBatchSize,+ })+ if err != nil {+ slog.Warn("runtime sweeper: failed to expire reconnect retries", "error", err)+ return+ }+ if len(failedTasks) == 0 {+ return+ }++ slog.Info("runtime sweeper: expired reconnect retries", "count", len(failedTasks))+ taskSvc.HandleFailedTasks(ctx, failedTasks)+}+// filterStaleRuntimesByLiveness narrows a SELECT-of-stale-candidates down to// the set that should actually be flipped offline. When liveness is available// and reports a candidate as alive, we skip it (DB is just lagging). When the@@ -424,13 +470,14 @@ func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Qu// in the same tick; this function is a defensive backstop for the residual// edge where a runtime row lingers online-with-stale-heartbeat past the// wall clock (MUL-4107).-func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {+func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration) {failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{DispatchTimeoutSecs: dispatchTimeoutSeconds,RunningTimeoutSecs: runningTimeoutSeconds,// Reuse the runtime stale window so the running-task backstop// exactly matches what sweepStaleRuntimes considers "not alive".- RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: reconnectGrace.Seconds(),})if err != nil {slog.Warn("task sweeper: failed to clean up stale tasks", "error", err)diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.goindex 55866dbbfb..82372c5d15 100644--- a/server/cmd/server/runtime_sweeper_test.go+++ b/server/cmd/server/runtime_sweeper_test.go@@ -104,6 +104,24 @@ func ageOutAgentRuntime(t *testing.T, agentID string, staleAgo time.Duration) {})}+func setAgentRuntimeOffline(t *testing.T, agentID string, lastSeenAgo time.Duration) {+ t.Helper()+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_runtime+ SET status = 'offline', last_seen_at = now() - make_interval(secs => $1)+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $2)+ `, lastSeenAgo.Seconds(), agentID); err != nil {+ t.Fatalf("failed to mark agent runtime offline: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `+ UPDATE agent_runtime SET status = 'online', last_seen_at = now()+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $1)+ `, agentID)+ })+}+func TestRefreshAgentStatusFromTasks(t *testing.T) {if testPool == nil {t.Skip("no database connection")@@ -234,7 +252,7 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {// The running-task sweep now requires the task's runtime to be NOT// heartbeating (MUL-4107). Age the runtime out so this test still// exercises the sweeper wall clock rather than being silently skipped.- ageOutAgentRuntime(t, agentID, 10*time.Minute)+ ageOutAgentRuntime(t, agentID, defaultRuntimeReconnectGrace+time.Hour)queries := db.New(testPool)bus := events.New()@@ -250,9 +268,10 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {// Use very short timeouts to trigger the sweep on our test taskfailedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0, // 1 second — our task is 3 hours old- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0, // 1 second — our task is 3 hours old+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks query failed: %v", err)@@ -327,7 +346,7 @@ func TestSweepStaleTasksReconcileAgentStatus(t *testing.T) {issueID, agentID, _ := setupSweeperTestFixture(t, "running")t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })// Runtime must be stale for the running-task wall clock to fire (MUL-4107).- ageOutAgentRuntime(t, agentID, 10*time.Minute)+ ageOutAgentRuntime(t, agentID, defaultRuntimeReconnectGrace+time.Hour)queries := db.New(testPool)bus := events.New()@@ -343,9 +362,10 @@ func TestSweepStaleTasksReconcileAgentStatus(t *testing.T) {// Fail stale tasks with short timeoutfailedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0,- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -409,7 +429,8 @@ func TestSweepDispatchedStaleTask(t *testing.T) {RunningTimeoutSecs: 9000.0,// RuntimeStaleSecs only affects the running branch — irrelevant for// this dispatched-timeout test, but wired for API consistency.- RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -462,6 +483,42 @@ func TestSweepDispatchedStaleTask(t *testing.T) {}}+// TestSweepDispatchedTaskWaitsThroughReconnectGrace locks the network-partition+// behavior for the pre-start window: an expired prepare lease must not consume+// a retry while the runtime has only recently gone offline.+func TestSweepDispatchedTaskWaitsThroughReconnectGrace(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ issueID, agentID, taskID := setupSweeperTestFixture(t, "dispatched")+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })+ setAgentRuntimeOffline(t, agentID, 10*time.Minute)++ failedTasks, err := db.New(testPool).FailStaleTasks(context.Background(), db.FailStaleTasksParams{+ DispatchTimeoutSecs: 1.0,+ RunningTimeoutSecs: 9000.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),+ })+ if err != nil {+ t.Fatalf("FailStaleTasks failed: %v", err)+ }+ for _, task := range failedTasks {+ if task.ID.Bytes == parseUUIDBytes(taskID) {+ t.Fatal("dispatched task was failed inside reconnect grace")+ }+ }++ var status string+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read task status: %v", err)+ }+ if status != "dispatched" {+ t.Fatalf("task status = %q, want dispatched", status)+ }+}+// TestSweepRunningTaskSkippedWhenRuntimeFresh is the MUL-4107 regression test:// a running task whose wall-clock deadline has already passed MUST NOT be// killed by the sweeper as long as its owning runtime is 'online' and its@@ -481,9 +538,10 @@ func TestSweepRunningTaskSkippedWhenRuntimeFresh(t *testing.T) {// alone — but the runtime is proving liveness, so the sweeper must skip it.queries := db.New(testPool)failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0,- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -506,27 +564,57 @@ func TestSweepRunningTaskSkippedWhenRuntimeFresh(t *testing.T) {}}-// TestSweepRunningTaskKilledWhenRuntimeStale is the companion coverage: with-// the same wall-clock deadline elapsed, a running task IS killed when its-// runtime's DB heartbeat is stale (simulates the "runtime lingers online-// with a stale heartbeat past the wall clock" pathological case that the-// wall-clock branch is the defensive backstop for). Note that in production-// the daemon-dead case is normally reclaimed sooner by sweepStaleRuntimes;-// this test asserts the residual backstop still fires when it needs to.-func TestSweepRunningTaskKilledWhenRuntimeStale(t *testing.T) {+func TestSweepRunningTaskWaitsThroughReconnectGrace(t *testing.T) {if testPool == nil {t.Skip("no database connection")}issueID, agentID, taskID := setupSweeperTestFixture(t, "running")t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })- ageOutAgentRuntime(t, agentID, 10*time.Minute)+ setAgentRuntimeOffline(t, agentID, 10*time.Minute)++ failedTasks, err := db.New(testPool).FailStaleTasks(context.Background(), db.FailStaleTasksParams{+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),+ })+ if err != nil {+ t.Fatalf("FailStaleTasks failed: %v", err)+ }+ for _, task := range failedTasks {+ if task.ID.Bytes == parseUUIDBytes(taskID) {+ t.Fatal("long-running task was failed inside reconnect grace")+ }+ }++ var status string+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read task status: %v", err)+ }+ if status != "running" {+ t.Fatalf("task status = %q, want running", status)+ }+}++// TestSweepRunningTaskKilledBeyondReconnectGrace is the companion coverage: a+// running task is killed once both its own deadline and the runtime reconnect+// grace have elapsed.+func TestSweepRunningTaskKilledBeyondReconnectGrace(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })+ ageOutAgentRuntime(t, agentID, defaultRuntimeReconnectGrace+time.Hour)queries := db.New(testPool)failedTasks, err := queries.FailStaleTasks(context.Background(), db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0,- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -554,6 +642,167 @@ func TestSweepRunningTaskKilledWhenRuntimeStale(t *testing.T) {}}+func TestOfflineRuntimeTasksRespectReconnectGrace(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ ctx := context.Background()+ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })+ setAgentRuntimeOffline(t, agentID, 10*time.Minute)+ queries := db.New(testPool)++ failed, err := queries.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{+ ReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),+ MaxPerTick: offlineTaskFailBatchSize,+ })+ if err != nil {+ t.Fatalf("FailTasksForOfflineRuntimes inside grace: %v", err)+ }+ for _, task := range failed {+ if task.ID.Bytes == parseUUIDBytes(taskID) {+ t.Fatal("running task was failed inside reconnect grace")+ }+ }++ if _, err := testPool.Exec(ctx, `+ UPDATE agent_runtime+ SET last_seen_at = now() - make_interval(secs => $1)+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $2)+ `, (defaultRuntimeReconnectGrace + time.Hour).Seconds(), agentID); err != nil {+ t.Fatalf("age runtime beyond grace: %v", err)+ }++ failed, err = queries.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{+ ReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),+ MaxPerTick: offlineTaskFailBatchSize,+ })+ if err != nil {+ t.Fatalf("FailTasksForOfflineRuntimes beyond grace: %v", err)+ }+ found := false+ for _, task := range failed {+ if task.ID.Bytes == parseUUIDBytes(taskID) {+ found = true+ if !task.FailureReason.Valid || task.FailureReason.String != "runtime_offline" {+ t.Fatalf("failure reason = %q, want runtime_offline", task.FailureReason.String)+ }+ }+ }+ if !found {+ t.Fatal("task was not failed after reconnect grace elapsed")+ }+}++func TestRuntimeReconnectRetryHasBoundedTerminalPath(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }++ ctx := context.Background()+ issueID, agentID, parentID := setupSweeperTestFixture(t, "running")+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })+ setAgentRuntimeOffline(t, agentID, defaultRuntimeReconnectGrace+time.Hour)++ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'failed', completed_at = now(), failure_reason = 'runtime_offline'+ WHERE id = $1+ `, parentID); err != nil {+ t.Fatalf("fail runtime_offline parent: %v", err)+ }+ if _, err := testPool.Exec(ctx, `UPDATE issue SET status = 'in_progress' WHERE id = $1`, issueID); err != nil {+ t.Fatalf("mark issue in progress: %v", err)+ }++ var retryID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, fire_at,+ parent_task_id, retry_of_task_id, attempt, max_attempts+ )+ SELECT agent_id, runtime_id, issue_id, 'deferred', priority,+ now() - interval '10 minutes', id, id, attempt + 1, max_attempts+ FROM agent_task_queue WHERE id = $1+ RETURNING id+ `, parentID).Scan(&retryID); err != nil {+ t.Fatalf("insert deferred retry: %v", err)+ }++ queries := db.New(testPool)+ params := db.FailExpiredRuntimeReconnectRetriesParams{+ ReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),+ RuntimeStaleSecs: staleThresholdSeconds,+ MaxPerTick: reconnectRetryExpireBatchSize,+ }++ failed, err := queries.FailExpiredRuntimeReconnectRetries(ctx, params)+ if err != nil {+ t.Fatalf("expire retry inside grace: %v", err)+ }+ if len(failed) != 0 {+ t.Fatalf("retry failed inside reconnect grace: got %d rows", len(failed))+ }++ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET fire_at = now() - make_interval(secs => $1)+ WHERE id = $2+ `, (defaultRuntimeReconnectGrace + time.Hour).Seconds(), retryID); err != nil {+ t.Fatalf("age retry beyond reconnect grace: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_runtime SET status = 'online', last_seen_at = now()+ WHERE id = (SELECT runtime_id FROM agent WHERE id = $1)+ `, agentID); err != nil {+ t.Fatalf("restore healthy runtime: %v", err)+ }++ failed, err = queries.FailExpiredRuntimeReconnectRetries(ctx, params)+ if err != nil {+ t.Fatalf("expire retry after healthy reconnect: %v", err)+ }+ if len(failed) != 0 {+ t.Fatalf("healthy runtime lost reconnect race: got %d rows", len(failed))+ }++ setAgentRuntimeOffline(t, agentID, defaultRuntimeReconnectGrace+time.Hour)+ failed, err = queries.FailExpiredRuntimeReconnectRetries(ctx, params)+ if err != nil {+ t.Fatalf("expire retry beyond grace: %v", err)+ }+ if len(failed) != 1 || failed[0].ID.Bytes != parseUUIDBytes(retryID) {+ t.Fatalf("expired retries = %d, want retry %s", len(failed), retryID)+ }+ if !failed[0].FailureReason.Valid || failed[0].FailureReason.String != "runtime_reconnect_timeout" {+ t.Fatalf("failure reason = %q, want runtime_reconnect_timeout", failed[0].FailureReason.String)+ }++ taskSvc := service.NewTaskService(queries, testPool, nil, events.New())+ taskSvc.HandleFailedTasks(ctx, failed)++ var issueStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM issue WHERE id = $1`, issueID).Scan(&issueStatus); err != nil {+ t.Fatalf("read issue status: %v", err)+ }+ if issueStatus != "todo" {+ t.Fatalf("issue status = %q, want todo after terminal reconnect timeout", issueStatus)+ }++ var undrained, retryChildren int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FILTER (WHERE completed_at IS NULL),+ count(*) FILTER (WHERE parent_task_id = $1)+ FROM agent_task_queue WHERE issue_id = $2+ `, retryID, issueID).Scan(&undrained, &retryChildren); err != nil {+ t.Fatalf("read terminal retry state: %v", err)+ }+ if undrained != 0 || retryChildren != 0 {+ t.Fatalf("terminal retry leaked work: undrained=%d child_retries=%d", undrained, retryChildren)+ }+}+// TestSweepResetsInProgressIssueToTodo verifies the core fix: when the sweeper// force-fails a stale task whose issue is still in_progress (because the daemon// crashed mid-run), the issue is reset back to todo so the daemon can re-queue it.@@ -611,13 +860,14 @@ func TestSweepResetsInProgressIssueToTodo(t *testing.T) {bus := events.New()// Runtime must be stale for the running-task wall clock to fire (MUL-4107).- ageOutAgentRuntime(t, agentID, 10*time.Minute)+ ageOutAgentRuntime(t, agentID, defaultRuntimeReconnectGrace+time.Hour)// Fail the stale task (running timeout of 1 second — our task is 3 hours old).failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0,- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -700,12 +950,13 @@ func TestSweepDoesNotResetIssueAlreadyInReview(t *testing.T) {bus := events.New()// Runtime must be stale for the running-task wall clock to fire (MUL-4107).- ageOutAgentRuntime(t, agentID, 10*time.Minute)+ ageOutAgentRuntime(t, agentID, defaultRuntimeReconnectGrace+time.Hour)failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{- DispatchTimeoutSecs: 300.0,- RunningTimeoutSecs: 1.0,- RuntimeStaleSecs: staleThresholdSeconds,+ DispatchTimeoutSecs: 300.0,+ RunningTimeoutSecs: 1.0,+ RuntimeStaleSecs: staleThresholdSeconds,+ RuntimeReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),})if err != nil {t.Fatalf("FailStaleTasks failed: %v", err)@@ -767,9 +1018,10 @@ func TestExpireStaleQueuedTasks(t *testing.T) {}oldIssueID := mkIssue("Queued TTL test (old)")freshIssueID := mkIssue("Queued TTL test (fresh)")+ recoveryIssueID := mkIssue("Queued TTL test (runtime recovery)")t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2)`, oldIssueID, freshIssueID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id IN ($1, $2)`, oldIssueID, freshIssueID)+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id IN ($1, $2, $3)`, oldIssueID, freshIssueID, recoveryIssueID)+ testPool.Exec(ctx, `DELETE FROM issue WHERE id IN ($1, $2, $3)`, oldIssueID, freshIssueID, recoveryIssueID)})var oldTaskID, freshTaskID string@@ -787,6 +1039,21 @@ func TestExpireStaleQueuedTasks(t *testing.T) {`, agentID, runtimeID, freshIssueID).Scan(&freshTaskID); err != nil {t.Fatalf("failed to insert fresh queued task: %v", err)}+ var recoveryParentID, recoveryTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at, completed_at, failure_reason)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '5 hours', now() - interval '5 hours', 'runtime_offline')+ RETURNING id+ `, agentID, runtimeID, recoveryIssueID).Scan(&recoveryParentID); err != nil {+ t.Fatalf("failed to insert runtime_offline parent: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at, parent_task_id, retry_of_task_id)+ VALUES ($1, $2, $3, 'queued', 0, now() - interval '5 hours', $4, $4)+ RETURNING id+ `, agentID, runtimeID, recoveryIssueID, recoveryParentID).Scan(&recoveryTaskID); err != nil {+ t.Fatalf("failed to insert runtime recovery retry: %v", err)+ }queries := db.New(testPool)failed, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{@@ -830,6 +1097,14 @@ func TestExpireStaleQueuedTasks(t *testing.T) {if freshStatus != "queued" {t.Fatalf("fresh task: expected status=queued, got %q", freshStatus)}++ var recoveryStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, recoveryTaskID).Scan(&recoveryStatus); err != nil {+ t.Fatalf("failed to read runtime recovery retry: %v", err)+ }+ if recoveryStatus != "queued" {+ t.Fatalf("runtime recovery retry: expected status=queued, got %q", recoveryStatus)+ }}// TestExpireStaleQueuedTasksRespectsBatchLimit verifies the per-tick cap sodiff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.goindex 8dfbb9f811..0d37b14d15 100644--- a/server/internal/handler/agent_builder_test.go+++ b/server/internal/handler/agent_builder_test.go@@ -1072,6 +1072,9 @@ func TestDeleteBuilderSessionLocksAgentBeforeTasks(t *testing.T) {ctx := context.Background()created := newBuilderSession(t)taskID := insertPendingChatTask(t, created.BuilderAgentID, created.SessionID, "queued")+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, testRuntimeID); err != nil {+ t.Fatalf("refresh builder runtime heartbeat: %v", err)+ }claimTx, err := testPool.Begin(ctx)if err != nil {@@ -1103,7 +1106,9 @@ func TestDeleteBuilderSessionLocksAgentBeforeTasks(t *testing.T) {}claimed, err := qtx.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{AgentID: agent.ID,+ RuntimeID: agent.RuntimeID,PrepareLeaseSecs: 30,+ RuntimeStaleSecs: service.RuntimeClaimFreshnessSeconds,})if err != nil {t.Fatalf("claim while delete waits for agent lock: %v", err)diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.goindex cfe9422f99..77d706703e 100644--- a/server/internal/handler/chat_input_ownership_test.go+++ b/server/internal/handler/chat_input_ownership_test.go@@ -223,6 +223,7 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {RuntimeID: parseUUID(runtimeID),ClaimRecoverySecs: 0,PrepareLeaseSecs: 60,+ RuntimeStaleSecs: service.RuntimeClaimFreshnessSeconds,})if err != nil {t.Fatalf("reclaim B dispatch: %v", err)@@ -467,8 +468,9 @@ func TestCompleteTask_ChatCallbackIdempotent(t *testing.T) {// TestFailTask_ChatRetryInheritsInputOwnerAndPriority: a transient failure of a// task-owned direct task creates a retry child that reuses the SAME input owner-// (so it reads the same user messages) and is queued at a bumped priority so it-// is claimed ahead of fresh chat tasks.+// (so it reads the same user messages) and keeps a bumped priority. A+// runtime_offline retry remains deferred until the runtime is healthy, then is+// claimed ahead of fresh chat tasks.func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -498,8 +500,8 @@ func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {if childPriority < 3 {t.Fatalf("chat retry must be bumped above fresh chat priority (2); got %d", childPriority)}- if childStatus != "queued" {- t.Fatalf("retry child must be queued, got %q", childStatus)+ if childStatus != "deferred" {+ t.Fatalf("runtime_offline retry child must be deferred, got %q", childStatus)}// The root direct task starts at attempt 1, so its first retry is attempt 2.var rootAttempt intdiff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.goindex ec131f80cf..efef6c01af 100644--- a/server/internal/service/retry_deferred_test.go+++ b/server/internal/service/retry_deferred_test.go@@ -85,6 +85,89 @@ func TestCreateRetryTaskFireAtControlsDeferral(t *testing.T) {}}+// TestRuntimeOfflineRetryWaitsForHealthyRuntime covers the complete recovery+// boundary: runtime_offline creates a deferred child, an offline runtime cannot+// promote or claim it even after fire_at is due, and a fresh online heartbeat+// releases that exact child without consuming another retry.+func TestRuntimeOfflineRetryWaitsForHealthyRuntime(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ _, _, agentID, issueID := seedAttributionFixture(t, pool)++ 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)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(), `UPDATE agent_runtime SET status='online', last_seen_at=now() WHERE id=$1`, runtimeID)+ })+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status='offline', last_seen_at=now() - interval '4 hours' WHERE id=$1`, runtimeID); err != nil {+ t.Fatalf("mark runtime offline: %v", err)+ }++ 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, 1, 2, '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)+ })++ svc := NewTaskService(q, pool, nil, events.New())+ if _, err := svc.FailTask(ctx, parentID, "runtime went offline", "src-session", "/tmp/src-workdir", "", "runtime_offline", false, ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }++ var childID pgtype.UUID+ var childStatus string+ var fireAt pgtype.Timestamptz+ if err := pool.QueryRow(ctx, `+ SELECT id, status, fire_at FROM agent_task_queue WHERE parent_task_id = $1+ `, parentID).Scan(&childID, &childStatus, &fireAt); err != nil {+ t.Fatalf("read retry child: %v", err)+ }+ if childStatus != "deferred" || !fireAt.Valid {+ t.Fatalf("runtime_offline child = status:%q fire_at_valid:%v, want deferred with fire_at", childStatus, fireAt.Valid)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET fire_at=now() - interval '1 second' WHERE id=$1`, childID); err != nil {+ t.Fatalf("make retry due: %v", err)+ }++ claimed, err := svc.ClaimTaskForRuntime(ctx, util.MustParseUUID(runtimeID))+ if err != nil {+ t.Fatalf("claim while offline: %v", err)+ }+ if claimed != nil {+ t.Fatalf("offline runtime claimed retry %s", util.UUIDToString(claimed.ID))+ }+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id=$1`, childID).Scan(&childStatus); err != nil {+ t.Fatalf("read child after offline claim: %v", err)+ }+ if childStatus != "deferred" {+ t.Fatalf("offline claim changed child to %q, want deferred", childStatus)+ }++ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status='online', last_seen_at=now() WHERE id=$1`, runtimeID); err != nil {+ t.Fatalf("restore runtime heartbeat: %v", err)+ }+ claimed, err = svc.ClaimTaskForRuntime(ctx, util.MustParseUUID(runtimeID))+ if err != nil {+ t.Fatalf("claim after reconnect: %v", err)+ }+ if claimed == nil || claimed.ID != childID {+ got := "nil"+ if claimed != nil {+ got = util.UUIDToString(claimed.ID)+ }+ t.Fatalf("claimed task = %s, want retry child %s", got, util.UUIDToString(childID))+ }+}+// 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) stilldiff --git a/server/internal/service/runtime_health_gate_test.go b/server/internal/service/runtime_health_gate_test.gonew file mode 100644index 0000000000..c0c598ebc0--- /dev/null+++ b/server/internal/service/runtime_health_gate_test.go@@ -0,0 +1,159 @@+package service++import (+ "context"+ "errors"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestRuntimeHealthGatesClaimsAndStaleDispatchRecovery directly covers every+// SQL release path that can hand work to a daemon. Offline, stale, or wrong+// runtimes must leave the row untouched; a fresh scoped runtime may claim or+// recover the exact task.+func TestRuntimeHealthGatesClaimsAndStaleDispatchRecovery(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ _, _, agentID, issueID := seedAttributionFixture(t, pool)++ 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)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(), `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, runtimeID)+ pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ })++ var taskID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {+ t.Fatalf("insert queued task: %v", err)+ }++ claim := func(runtime string) (db.AgentTaskQueue, error) {+ return q.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{+ AgentID: util.MustParseUUID(agentID),+ RuntimeID: util.MustParseUUID(runtime),+ PrepareLeaseSecs: 60,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })+ }+ assertNoClaim := func(label, runtime string) {+ t.Helper()+ if _, err := claim(runtime); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("%s: ClaimAgentTask error = %v, want no rows", label, err)+ }+ var status string+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("%s: read task status: %v", label, err)+ }+ if status != "queued" {+ t.Fatalf("%s: task status = %q, want queued", label, status)+ }+ }++ assertNoClaim("wrong runtime scope", "00000000-0000-0000-0000-000000000001")+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'offline', last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("mark runtime offline: %v", err)+ }+ assertNoClaim("offline runtime", runtimeID)++ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() - interval '10 minutes' WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("make runtime heartbeat stale: %v", err)+ }+ assertNoClaim("stale runtime heartbeat", runtimeID)++ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("refresh runtime heartbeat: %v", err)+ }+ claimed, err := claim(runtimeID)+ if err != nil {+ t.Fatalf("fresh runtime claim: %v", err)+ }+ if util.UUIDToString(claimed.ID) != taskID {+ t.Fatalf("claimed task = %s, want %s", util.UUIDToString(claimed.ID), taskID)+ }++ resetStaleDispatch := func() {+ t.Helper()+ if _, err := pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'dispatched', started_at = NULL,+ dispatched_at = now() - interval '10 minutes',+ prepare_lease_expires_at = now() - interval '1 minute'+ WHERE id = $1+ `, taskID); err != nil {+ t.Fatalf("reset stale dispatch: %v", err)+ }+ }+ reclaimOne := func() (db.AgentTaskQueue, error) {+ return q.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{+ RuntimeID: util.MustParseUUID(runtimeID),+ PrepareLeaseSecs: 60,+ ClaimRecoverySecs: 30,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })+ }++ resetStaleDispatch()+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'offline', last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("mark runtime offline before singular reclaim: %v", err)+ }+ if _, err := reclaimOne(); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("offline singular reclaim error = %v, want no rows", err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() - interval '10 minutes' WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("make runtime stale before singular reclaim: %v", err)+ }+ if _, err := reclaimOne(); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("stale singular reclaim error = %v, want no rows", err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("refresh runtime before singular reclaim: %v", err)+ }+ reclaimed, err := reclaimOne()+ if err != nil {+ t.Fatalf("fresh singular reclaim: %v", err)+ }+ if util.UUIDToString(reclaimed.ID) != taskID {+ t.Fatalf("singular reclaimed task = %s, want %s", util.UUIDToString(reclaimed.ID), taskID)+ }++ resetStaleDispatch()+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'offline', last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("mark runtime offline before batch reclaim: %v", err)+ }+ batchParams := db.ReclaimStaleDispatchedTasksForRuntimesParams{+ RuntimeIds: []pgtype.UUID{util.MustParseUUID(runtimeID)},+ PrepareLeaseSecs: 60,+ ClaimRecoverySecs: 30,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ MaxTasks: 10,+ }+ batch, err := q.ReclaimStaleDispatchedTasksForRuntimes(ctx, batchParams)+ if err != nil {+ t.Fatalf("offline batch reclaim: %v", err)+ }+ if len(batch) != 0 {+ t.Fatalf("offline batch reclaimed %d tasks, want 0", len(batch))+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("refresh runtime before batch reclaim: %v", err)+ }+ batch, err = q.ReclaimStaleDispatchedTasksForRuntimes(ctx, batchParams)+ if err != nil {+ t.Fatalf("fresh batch reclaim: %v", err)+ }+ if len(batch) != 1 || util.UUIDToString(batch[0].ID) != taskID {+ t.Fatalf("batch reclaimed %d tasks, want task %s", len(batch), taskID)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex c92248d31f..6b2efdc2c1 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -163,6 +163,14 @@ func truncateFallbackCommentBody(body string, maxRunes int) string {const (taskAnalyticsContextCacheMax = 4096+ // RuntimeClaimFreshnessSeconds is the maximum DB heartbeat age accepted by+ // every task release path (deferred promotion, stale-dispatch reclaim, and+ // fresh claim). It must exceed the 60s DB heartbeat flush interval, one ~15s+ // daemon heartbeat, and the ~30s batch scheduler tick. 150s leaves a 45s+ // buffer above that 105s worst-case age. Keep the runtime sweeper threshold+ // aligned: a runtime must not start work after it is stale enough to be+ // marked offline.+ RuntimeClaimFreshnessSeconds = 150.0// claimResponseRecoveryWindow must exceed daemon client.Timeout for// /tasks/claim (30s) plus /tasks/{id}/start (30s) plus scheduling slack.// Longer pre-start work is protected by prepareLeaseDuration instead of@@ -2922,9 +2930,18 @@ func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.})}-// ClaimTask atomically claims the next queued task for an agent,-// respecting max_concurrent_tasks.+// ClaimTask atomically claims the next queued task for an agent on its current+// runtime, respecting max_concurrent_tasks.func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {+ return s.claimTask(ctx, agentID, pgtype.UUID{})+}++// claimTask is the runtime-scoped claim primitive used by daemon poll paths.+// The exported ClaimTask wrapper omits runtimeID and therefore resolves the+// agent's currently bound runtime. Scoping the SQL claim itself prevents an+// offline candidate on runtime A from causing the same agent's task on runtime+// B to be dispatched and then dropped by the caller's runtime guard.+func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {start := time.Now()outcome := "unknown"var getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64@@ -2941,6 +2958,14 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.Aoutcome = "error_get_agent"return fmt.Errorf("agent not found: %w", err)}+ claimRuntimeID := runtimeID+ if !claimRuntimeID.Valid {+ claimRuntimeID = agent.RuntimeID+ }+ if !claimRuntimeID.Valid {+ outcome = "no_runtime"+ return nil+ }t0 = time.Now()running, err := qtx.CountRunningTasks(ctx, agentID)@@ -2958,7 +2983,9 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.At0 = time.Now()task, err := qtx.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{AgentID: agentID,+ RuntimeID: claimRuntimeID,PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,})claimAgentMs = time.Since(t0).Milliseconds()if err != nil {@@ -3071,6 +3098,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.RuntimeID: runtimeID,ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,})if err == nil {outcome = "reclaimed_dispatched"@@ -3126,7 +3154,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.triedAgents[agentKey] = struct{}{}tried++- task, err := s.ClaimTask(ctx, candidate.AgentID)+ task, err := s.claimTask(ctx, candidate.AgentID, runtimeID)if err != nil {loopMs = time.Since(loopStart).Milliseconds()outcome = "error_claim"@@ -3238,9 +3266,9 @@ func (s *TaskService) RequeueTaskAfterClaimFailure(ctx context.Context, task db.// invalidation version for the rest BEFORE the candidate SELECT;// 4. list queued candidates across the non-empty set (one SELECT);// 5. mark still-empty runtimes so their next idle poll skips Postgres;-// 6. claim per distinct agent via ClaimTask (unchanged — preserves the+// 6. claim per distinct agent via the runtime-scoped helper, preserving// per-(issue, agent) serialization, the agent concurrency cap, and every-// dispatch side effect) until maxTasks is reached.+// dispatch side effect until maxTasks is reached.//// The returned slice contains both reclaimed and freshly-claimed tasks, each// already carrying its runtime_id so the daemon routes it to the matching@@ -3276,7 +3304,10 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg// MarkEmpty from a prior idle poll would short-circuit the runtime and the// promoted task would sit unclaimed until the empty key's TTL. Also emits// the deferred→queued UI event and the enqueue analytics sample.- promoted, err := s.Queries.PromoteDueDeferredTasksForRuntimes(ctx, uniqueIDs)+ promoted, err := s.Queries.PromoteDueDeferredTasksForRuntimes(ctx, db.PromoteDueDeferredTasksForRuntimesParams{+ RuntimeIds: uniqueIDs,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })if err != nil {return nil, fmt.Errorf("promote deferred tasks: %w", err)}@@ -3295,6 +3326,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgRuntimeIds: uniqueIDs,ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,MaxTasks: int32(maxTasks),})if err != nil {@@ -3361,9 +3393,8 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg}}- // 6. Claim per distinct agent (unchanged path → same per-(issue, agent)- // serialization, capacity cap, and dispatch side effects) until maxTasks is- // reached.+ // 6. Claim per distinct agent through the runtime-scoped helper, preserving+ // per-(issue, agent) serialization, capacity caps, and dispatch side effects.triedAgents := make(map[string]struct{}, len(candidates))for i := range candidates {if len(claimed) >= maxTasks {@@ -3375,9 +3406,9 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg}triedAgents[agentKey] = struct{}{}- task, err := s.ClaimTask(ctx, candidates[i].AgentID)+ task, err := s.claimTask(ctx, candidates[i].AgentID, candidates[i].RuntimeID)if err != nil {- // Each ClaimTask commits in its own transaction, so earlier+ // Each scoped claim commits in its own transaction, so earlier// iterations (and step-2 reclaims) are already dispatched// server-side. Returning nil here would drop them and force the// daemon to double-claim via HTTP fallback (MUL-4257). Return the@@ -3392,12 +3423,9 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgif task == nil {continue}- // ClaimAgentTask selects by agent only; guard that the claimed task- // belongs to a runtime this daemon hosts. An agent with a- // higher-priority queued task on ANOTHER daemon's runtime could- // otherwise be dispatched here and dropped — matching the singular- // path's runtime_id guard. Such a stray dispatch is recovered by the- // reclaim path on the owning daemon's next poll.+ // The SQL claim is scoped to the candidate runtime. Retain this guard as+ // a defensive contract check so a future query change cannot route work+ // to a runtime this daemon does not host.if _, ok := runtimeInSet[util.UUIDToString(task.RuntimeID)]; !ok {continue}@@ -3408,7 +3436,10 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg}func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) error {- tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, runtimeID)+ tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, db.PromoteDueDeferredTasksForRuntimeParams{+ RuntimeID: runtimeID,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })if err != nil {return fmt.Errorf("promote due deferred tasks: %w", err)}@@ -4273,20 +4304,28 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,// that did download is already cached on disk — a retry resumes from there// instead of re-fetching the whole set (MUL-5370).var retryableReasons = map[string]bool{- "runtime_offline": true,- "runtime_recovery": true,- "timeout": true,- "codex_semantic_inactivity": true,+ string(taskfailure.ReasonRuntimeOffline): true,+ string(taskfailure.ReasonRuntimeRecovery): true,+ string(taskfailure.ReasonTimeout): true,+ "codex_semantic_inactivity": true,string(taskfailure.ReasonAgentProviderNetwork): true,string(taskfailure.ReasonSkillBundleUnavailable): true,}+// runtime_offline retries start deferred, not queued: their positive fire_at+// routes them through health-gated promotion after a fresh runtime heartbeat+// returns. The queue sweeper also exempts this retry lineage, covering the race+// where a runtime disconnects again after promotion but before claim. This+// delay is only a state marker, not the reconnect policy; the heartbeat gate is+// authoritative.+//// 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 (+ runtimeOfflineRetryDeferral = time.SecondproviderNetworkMaxAttempts = 3providerNetworkFinalRetryWait = 5 * time.Second)@@ -4313,11 +4352,15 @@ func retryAttemptCeiling(reason string, taskMaxAttempts int32) int32 {}// 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.+// failure at failedAttempt. runtime_offline always gets a positive fire_at so+// it waits for the health-gated promotion path. provider_network's final+// attempt is deferred ~5s; every other retry remains 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.ReasonRuntimeOffline) {+ return runtimeOfflineRetryDeferral+ }if reason == string(taskfailure.ReasonAgentProviderNetwork) &&failedAttempt >= providerNetworkMaxAttempts-1 {return providerNetworkFinalRetryWaitdiff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.goindex ba95376630..e8b21ccbf1 100644--- a/server/internal/service/task_complete_race_test.go+++ b/server/internal/service/task_complete_race_test.go@@ -171,8 +171,9 @@ 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).+// retry deferred ~5s. runtime_offline uses a separate deferred marker so its+// retry waits for a healthy runtime; other retryable reasons keep their generic+// max_attempts=2 (single, immediate retry).func TestProviderNetworkRetrySchedule(t *testing.T) {const provNet = "agent_error.provider_network"@@ -195,8 +196,8 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {}}- // Backoff: only provider_network's final attempt (after the 2nd failure) is- // deferred; its first retry and every other reason are immediate.+ // Backoff / deferral: runtime_offline always waits for health-gated+ // promotion; provider_network only defers its final tier.delayCases := []struct {reason stringfailedAttempt int32@@ -204,6 +205,7 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {}{{provNet, 1, 0}, // first failure → immediate retry{provNet, 2, providerNetworkFinalRetryWait}, // second failure → 5s-deferred retry+ {"runtime_offline", 1, runtimeOfflineRetryDeferral},{"timeout", 2, 0}, // unrelated reason → never deferred}for _, tc := range delayCases {diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 6da1b13af8..dd6dc6cb9a 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1204,10 +1204,19 @@ const claimAgentTask = `-- name: ClaimAgentTask :oneUPDATE agent_task_queueSET status = 'dispatched',dispatched_at = now(),- prepare_lease_expires_at = now() + make_interval(secs => $2::double precision)+ prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)WHERE id = (SELECT atq.id FROM agent_task_queue atq- WHERE atq.agent_id = $1 AND atq.status = 'queued'+ WHERE atq.agent_id = $2+ AND atq.runtime_id = $3+ AND atq.status = 'queued'+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $4::double precision)+ )AND NOT EXISTS (SELECT 1 FROM agent_task_queue activeWHERE active.agent_id = atq.agent_id@@ -1233,11 +1242,14 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c`type ClaimAgentTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`PrepareLeaseSecs float64 `json:"prepare_lease_secs"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`}-// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:+// Claims the next queued task for an agent on one healthy runtime, enforcing+// per-(issue, agent) serialization:// a task is only claimable when no other task for the same issue AND same agent is// already dispatched or running. This allows different agents to work on the same// issue in parallel while preventing a single agent from running duplicate tasks.@@ -1247,7 +1259,12 @@ type ClaimAgentTaskParams struct {// otherwise a user mashing the create button could fire concurrent quick-creates// whose completion lookup would race over "most recent issue by this agent".func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams) (AgentTaskQueue, error) {- row := q.db.QueryRow(ctx, claimAgentTask, arg.AgentID, arg.PrepareLeaseSecs)+ row := q.db.QueryRow(ctx, claimAgentTask,+ arg.PrepareLeaseSecs,+ arg.AgentID,+ arg.RuntimeID,+ arg.RuntimeStaleSecs,+ )var i AgentTaskQueueerr := row.Scan(&i.ID,@@ -2495,9 +2512,10 @@ type CreateRetryTaskParams struct {// 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.+// poll) flips it to 'queued'. Used for runtime_offline so the child waits for a+// healthy runtime, and 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@@ -2679,6 +2697,11 @@ WITH victims AS (SELECT id FROM agent_task_queueWHERE status = 'queued'AND created_at < now() - make_interval(secs => $1::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue retry_parent+ WHERE retry_parent.id = agent_task_queue.parent_task_id+ AND retry_parent.failure_reason = 'runtime_offline'+ )ORDER BY created_at ASCLIMIT $2::intFOR UPDATE SKIP LOCKED@@ -2693,6 +2716,11 @@ FROM victims vWHERE t.id = v.idAND t.status = 'queued'AND t.created_at < now() - make_interval(secs => $1::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue retry_parent+ WHERE retry_parent.id = t.parent_task_id+ AND retry_parent.failure_reason = 'runtime_offline'+ )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, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.plugin_execution_manifest_id, t.branch_name`@@ -2707,7 +2735,9 @@ type ExpireStaleQueuedTasksParams struct {// is offline, we still need to drain the historical 87k+ doomed rows and// handle edge cases where a runtime goes offline AFTER a task is already// queued (the admission check protects new enqueues, not in-flight queue-// depth).+// depth). A retry created by runtime_offline is exempt: it deliberately waits+// for that runtime to reconnect, so time spent in this recovery state must not+// consume the generic queue TTL.//// Concurrency safety: the daemon's claim path may race with this sweeper to// transition the same row out of 'queued'. We protect against that two@@ -2991,6 +3021,138 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (Areturn i, err}+const failExpiredRuntimeReconnectRetries = `-- name: FailExpiredRuntimeReconnectRetries :many+WITH victims AS (+ SELECT retry.id+ FROM agent_task_queue retry+ JOIN agent_task_queue parent ON parent.id = retry.parent_task_id+ WHERE retry.status = 'deferred'+ AND retry.fire_at < now() - make_interval(secs => $1::double precision)+ AND parent.failure_reason = 'runtime_offline'+ AND NOT EXISTS (+ SELECT 1 FROM agent_runtime runtime+ WHERE runtime.id = retry.runtime_id+ AND runtime.status = 'online'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=+ now() - make_interval(secs => $2::double precision)+ )+ ORDER BY retry.fire_at, retry.created_at+ LIMIT $3::int+ FOR UPDATE OF retry SKIP LOCKED+)+UPDATE agent_task_queue AS retry+SET status = 'failed',+ completed_at = now(),+ error = 'runtime did not reconnect within the configured grace period',+ failure_reason = 'runtime_reconnect_timeout',+ wait_reason = NULL,+ prepare_lease_expires_at = NULL+FROM victims+WHERE retry.id = victims.id+ AND retry.status = 'deferred'+ AND retry.fire_at < now() - make_interval(secs => $1::double precision)+ AND EXISTS (+ SELECT 1 FROM agent_task_queue parent+ WHERE parent.id = retry.parent_task_id+ AND parent.failure_reason = 'runtime_offline'+ )+ AND NOT EXISTS (+ SELECT 1 FROM agent_runtime runtime+ WHERE runtime.id = retry.runtime_id+ AND runtime.status = 'online'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=+ now() - make_interval(secs => $2::double precision)+ )+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.plugin_execution_manifest_id, retry.branch_name+`++type FailExpiredRuntimeReconnectRetriesParams struct {+ ReconnectGraceSecs float64 `json:"reconnect_grace_secs"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+ MaxPerTick int32 `json:"max_per_tick"`+}++// A runtime_offline retry waits in deferred until its runtime returns healthy.+// Give that recovery state a bounded exit: after one full reconnect grace,+// fail it with a non-retryable reason so issues, agents, and runtime GC can+// converge. A runtime that is healthy when this query runs wins the race and+// remains deferred for the next daemon poll to promote. The parent join is the+// lineage discriminator; provider backoff and other deferred task types are+// intentionally excluded.+func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg FailExpiredRuntimeReconnectRetriesParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, failExpiredRuntimeReconnectRetries, arg.ReconnectGraceSecs, arg.RuntimeStaleSecs, arg.MaxPerTick)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.PluginExecutionManifestID,+ &i.BranchName,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const failStaleTasks = `-- name: FailStaleTasks :manyUPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'task timed out',@@ -3000,24 +3162,48 @@ WHERE (status = 'dispatched'AND dispatched_at < now() - make_interval(secs => $1::double precision)AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())+ AND (+ runtime_id IS NULL+ OR NOT EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ )+ OR EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND (+ (+ r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $2::double precision)+ )+ OR COALESCE(r.last_seen_at, r.updated_at) <+ now() - make_interval(secs => $3::double precision)+ )+ )+ ))OR (status = 'running'- AND started_at < now() - make_interval(secs => $2::double precision)- AND NOT EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = agent_task_queue.runtime_id- AND r.status = 'online'- AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)+ AND started_at < now() - make_interval(secs => $4::double precision)+ AND (+ runtime_id IS NULL+ OR NOT EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND COALESCE(r.last_seen_at, r.updated_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, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name`type FailStaleTasksParams struct {- DispatchTimeoutSecs float64 `json:"dispatch_timeout_secs"`- RunningTimeoutSecs float64 `json:"running_timeout_secs"`- RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+ DispatchTimeoutSecs float64 `json:"dispatch_timeout_secs"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+ RuntimeReconnectGraceSecs float64 `json:"runtime_reconnect_grace_secs"`+ RunningTimeoutSecs float64 `json:"running_timeout_secs"`}// Fails tasks stuck in dispatched/running beyond the given thresholds.@@ -3028,25 +3214,20 @@ type FailStaleTasksParams struct {//// - Dispatched: `prepare_lease_expires_at` is refreshed every 15s by the// daemon between claim and StartTask (see startTaskPrepareLeaseExtender).-// A live lease excludes the row.+// A live lease excludes the row. An expired lease may fail immediately on+// a healthy runtime, but a disconnected runtime gets the same reconnect+// grace as a running task.//// - Running: no per-task lease is renewed once StartTask fires, so we key// off the daemon-wide heartbeat instead — `agent_runtime.last_seen_at`,-// which the daemon bumps every ~15s while it is up. A running task whose-// runtime is `online` AND whose `last_seen_at` is within-// @runtime_stale_secs is treated as alive and is NOT killed by this-// wall-clock backstop, even after `started_at` exceeds the running-// timeout. This is what lets healthy multi-hour research / training runs-// survive on self-hosted deployments (MUL-4107): the daemon side is-// bounded only by inactivity watchdogs (idle / per-tool), so the-// server-side wall clock must not shadow that with a coarser cap.+// which the daemon bumps every ~15s while it is up. A running task is not+// killed until that heartbeat has been absent for the full reconnect+// grace, even when its own wall-clock timeout elapsed earlier. This keeps+// healthy multi-hour work alive through a network partition.//-// The daemon-dead case is the primary responsibility of `sweepStaleRuntimes`-// (which mixes DB `last_seen_at` with the Redis LivenessStore and calls-// `FailTasksForOfflineRuntimes` in the same tick). The wall-clock branch-// here is a defensive backstop for pathological cases where a runtime row-// somehow retains status='online' with a stale DB heartbeat for longer than-// the wall clock allows.+// The daemon-dead case is recovered immediately when that daemon restarts via+// RecoverOrphanedTasksForRuntime. Until then, this query and+// FailTasksForOfflineRuntimes share the same bounded reconnect grace.//// runtime_id IS NULL: a running row with no runtime is by definition not// proving liveness, so the wall clock is allowed to fire — same shape as@@ -3058,7 +3239,12 @@ type FailStaleTasksParams struct {// "stuck". If the daemon dies, RecoverOrphanedTasksForRuntime reclaims// those rows at restart.func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, failStaleTasks, arg.DispatchTimeoutSecs, arg.RunningTimeoutSecs, arg.RuntimeStaleSecs)+ rows, err := q.db.Query(ctx, failStaleTasks,+ arg.DispatchTimeoutSecs,+ arg.RuntimeStaleSecs,+ arg.RuntimeReconnectGraceSecs,+ arg.RunningTimeoutSecs,+ )if err != nil {return nil, err}@@ -5794,11 +5980,23 @@ SET status = 'queued'WHERE runtime_id = $1AND status = 'deferred'AND fire_at <= now()+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $2::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, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name`-func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntime, runtimeID)+type PromoteDueDeferredTasksForRuntimeParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+}++func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg PromoteDueDeferredTasksForRuntimeParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntime, arg.RuntimeID, arg.RuntimeStaleSecs)if err != nil {return nil, err}@@ -5877,13 +6075,25 @@ SET status = 'queued'WHERE runtime_id = ANY($1::uuid[])AND status = 'deferred'AND fire_at <= now()+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $2::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, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name`+type PromoteDueDeferredTasksForRuntimesParams struct {+ RuntimeIds []pgtype.UUID `json:"runtime_ids"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+}+// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all// due deferred tasks across the runtime set in one UPDATE.-func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtimeIds []pgtype.UUID) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntimes, runtimeIds)+func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg PromoteDueDeferredTasksForRuntimesParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntimes, arg.RuntimeIds, arg.RuntimeStaleSecs)if err != nil {return nil, err}@@ -6041,6 +6251,13 @@ WHERE id = (AND atq.started_at IS NULLAND atq.dispatched_at < now() - make_interval(secs => $3::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $4::double precision)+ )ORDER BY atq.priority DESC, atq.dispatched_at ASCLIMIT 1FOR UPDATE SKIP LOCKED@@ -6052,6 +6269,7 @@ type ReclaimStaleDispatchedTaskForRuntimeParams struct {RuntimeID pgtype.UUID `json:"runtime_id"`PrepareLeaseSecs float64 `json:"prepare_lease_secs"`ClaimRecoverySecs float64 `json:"claim_recovery_secs"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`}// Re-delivers a task whose previous claim likely succeeded server-side but@@ -6060,7 +6278,12 @@ type ReclaimStaleDispatchedTaskForRuntimeParams struct {// Refresh dispatched_at so the server-side dispatch timeout measures from the// recovered delivery attempt.func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg ReclaimStaleDispatchedTaskForRuntimeParams) (AgentTaskQueue, error) {- row := q.db.QueryRow(ctx, reclaimStaleDispatchedTaskForRuntime, arg.RuntimeID, arg.PrepareLeaseSecs, arg.ClaimRecoverySecs)+ row := q.db.QueryRow(ctx, reclaimStaleDispatchedTaskForRuntime,+ arg.RuntimeID,+ arg.PrepareLeaseSecs,+ arg.ClaimRecoverySecs,+ arg.RuntimeStaleSecs,+ )var i AgentTaskQueueerr := row.Scan(&i.ID,@@ -6131,8 +6354,15 @@ WHERE id IN (AND atq.started_at IS NULLAND atq.dispatched_at < now() - make_interval(secs => $3::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $4::double precision)+ )ORDER BY atq.priority DESC, atq.dispatched_at ASC- LIMIT $4::int+ LIMIT $5::intFOR 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, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name@@ -6142,6 +6372,7 @@ type ReclaimStaleDispatchedTasksForRuntimesParams struct {PrepareLeaseSecs float64 `json:"prepare_lease_secs"`RuntimeIds []pgtype.UUID `json:"runtime_ids"`ClaimRecoverySecs float64 `json:"claim_recovery_secs"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`MaxTasks int32 `json:"max_tasks"`}@@ -6157,6 +6388,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ararg.PrepareLeaseSecs,arg.RuntimeIds,arg.ClaimRecoverySecs,+ arg.RuntimeStaleSecs,arg.MaxTasks,)if err != nil {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 1c7d110c1f..3dec3529d2 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -229,22 +229,43 @@ func (q *Queries) DeleteSystemAgentsByRuntime(ctx context.Context, runtimeID pgt}const failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :many-UPDATE agent_task_queue+WITH victims AS (+ SELECT task.id+ FROM agent_task_queue task+ JOIN agent_runtime runtime ON runtime.id = task.runtime_id+ WHERE task.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND runtime.status = 'offline'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) <+ now() - make_interval(secs => $1::double precision)+ ORDER BY COALESCE(runtime.last_seen_at, runtime.updated_at), task.created_at+ LIMIT $2::int+ FOR UPDATE OF task SKIP LOCKED+)+UPDATE agent_task_queue AS taskSET status = 'failed', completed_at = now(), error = 'runtime went offline',failure_reason = 'runtime_offline',wait_reason = NULL-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, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name+FROM victims+WHERE task.id = victims.id+ AND task.status IN ('dispatched', 'running', 'waiting_local_directory')+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, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name`+type FailTasksForOfflineRuntimesParams struct {+ ReconnectGraceSecs float64 `json:"reconnect_grace_secs"`+ MaxPerTick int32 `json:"max_per_tick"`+}+// Marks dispatched/running/waiting_local_directory tasks as failed when-// their runtime is offline. This cleans up orphaned tasks after a daemon-// crash or network partition.-func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, failTasksForOfflineRuntimes)+// their runtime has remained offline beyond the reconnect grace. A short or+// medium network partition must not terminate a daemon process that is still+// running locally; a real daemon restart is recovered separately through+// RecoverOrphanedTasksForRuntime. Bounded per tick so a large recovery backlog+// cannot monopolise the sweeper transaction. last_seen_at is normally set by+// the first heartbeat; updated_at is only the fallback for a never-heartbeated+// runtime, and a forced-offline write starts its grace from that update.+func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasksForOfflineRuntimesParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, failTasksForOfflineRuntimes, arg.ReconnectGraceSecs, arg.MaxPerTick)if err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex d519b875fa..281d70f6b5 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -539,9 +539,10 @@ WHERE id = $1 AND issue_id IS NULL-- 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.+-- poll) flips it to 'queued'. Used for runtime_offline so the child waits for a+-- healthy runtime, and 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@@ -653,7 +654,8 @@ JOIN agent a ON a.id = atq.agent_idWHERE atq.id = $1 AND a.workspace_id = $2;-- name: ClaimAgentTask :one--- Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:+-- Claims the next queued task for an agent on one healthy runtime, enforcing+-- per-(issue, agent) serialization:-- a task is only claimable when no other task for the same issue AND same agent is-- already dispatched or running. This allows different agents to work on the same-- issue in parallel while preventing a single agent from running duplicate tasks.@@ -668,7 +670,16 @@ SET status = 'dispatched',prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)WHERE id = (SELECT atq.id FROM agent_task_queue atq- WHERE atq.agent_id = $1 AND atq.status = 'queued'+ WHERE atq.agent_id = @agent_id+ AND atq.runtime_id = @runtime_id+ AND atq.status = 'queued'+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )AND NOT EXISTS (SELECT 1 FROM agent_task_queue activeWHERE active.agent_id = atq.agent_id@@ -751,6 +762,13 @@ WHERE id = (AND atq.started_at IS NULLAND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )ORDER BY atq.priority DESC, atq.dispatched_at ASCLIMIT 1FOR UPDATE SKIP LOCKED@@ -775,6 +793,13 @@ WHERE id IN (AND atq.started_at IS NULLAND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = atq.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )ORDER BY atq.priority DESC, atq.dispatched_at ASCLIMIT @max_tasks::intFOR UPDATE SKIP LOCKED@@ -1131,25 +1156,20 @@ RETURNING *;---- * Dispatched: `prepare_lease_expires_at` is refreshed every 15s by the-- daemon between claim and StartTask (see startTaskPrepareLeaseExtender).--- A live lease excludes the row.+-- A live lease excludes the row. An expired lease may fail immediately on+-- a healthy runtime, but a disconnected runtime gets the same reconnect+-- grace as a running task.---- * Running: no per-task lease is renewed once StartTask fires, so we key-- off the daemon-wide heartbeat instead — `agent_runtime.last_seen_at`,--- which the daemon bumps every ~15s while it is up. A running task whose--- runtime is `online` AND whose `last_seen_at` is within--- @runtime_stale_secs is treated as alive and is NOT killed by this--- wall-clock backstop, even after `started_at` exceeds the running--- timeout. This is what lets healthy multi-hour research / training runs--- survive on self-hosted deployments (MUL-4107): the daemon side is--- bounded only by inactivity watchdogs (idle / per-tool), so the--- server-side wall clock must not shadow that with a coarser cap.+-- which the daemon bumps every ~15s while it is up. A running task is not+-- killed until that heartbeat has been absent for the full reconnect+-- grace, even when its own wall-clock timeout elapsed earlier. This keeps+-- healthy multi-hour work alive through a network partition.----- The daemon-dead case is the primary responsibility of `sweepStaleRuntimes`--- (which mixes DB `last_seen_at` with the Redis LivenessStore and calls--- `FailTasksForOfflineRuntimes` in the same tick). The wall-clock branch--- here is a defensive backstop for pathological cases where a runtime row--- somehow retains status='online' with a stale DB heartbeat for longer than--- the wall clock allows.+-- The daemon-dead case is recovered immediately when that daemon restarts via+-- RecoverOrphanedTasksForRuntime. Until then, this query and+-- FailTasksForOfflineRuntimes share the same bounded reconnect grace.---- runtime_id IS NULL: a running row with no runtime is by definition not-- proving liveness, so the wall clock is allowed to fire — same shape as@@ -1168,15 +1188,38 @@ WHERE (status = 'dispatched'AND dispatched_at < now() - make_interval(secs => @dispatch_timeout_secs::double precision)AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())+ AND (+ runtime_id IS NULL+ OR NOT EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ )+ OR EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND (+ (+ r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )+ OR COALESCE(r.last_seen_at, r.updated_at) <+ now() - make_interval(secs => @runtime_reconnect_grace_secs::double precision)+ )+ )+ ))OR (status = 'running'AND started_at < now() - make_interval(secs => @running_timeout_secs::double precision)- AND NOT EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = agent_task_queue.runtime_id- AND r.status = 'online'- AND r.last_seen_at >= now() - make_interval(secs => @runtime_stale_secs::double precision)+ AND (+ runtime_id IS NULL+ OR NOT EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_reconnect_grace_secs::double precision)+ )))RETURNING *;@@ -1188,7 +1231,9 @@ RETURNING *;-- is offline, we still need to drain the historical 87k+ doomed rows and-- handle edge cases where a runtime goes offline AFTER a task is already-- queued (the admission check protects new enqueues, not in-flight queue--- depth).+-- depth). A retry created by runtime_offline is exempt: it deliberately waits+-- for that runtime to reconnect, so time spent in this recovery state must not+-- consume the generic queue TTL.---- Concurrency safety: the daemon's claim path may race with this sweeper to-- transition the same row out of 'queued'. We protect against that two@@ -1208,6 +1253,11 @@ WITH victims AS (SELECT id FROM agent_task_queueWHERE status = 'queued'AND created_at < now() - make_interval(secs => @ttl_secs::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue retry_parent+ WHERE retry_parent.id = agent_task_queue.parent_task_id+ AND retry_parent.failure_reason = 'runtime_offline'+ )ORDER BY created_at ASCLIMIT @max_per_tick::intFOR UPDATE SKIP LOCKED@@ -1222,8 +1272,64 @@ FROM victims vWHERE t.id = v.idAND t.status = 'queued'AND t.created_at < now() - make_interval(secs => @ttl_secs::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue retry_parent+ WHERE retry_parent.id = t.parent_task_id+ AND retry_parent.failure_reason = 'runtime_offline'+ )RETURNING t.*;+-- name: FailExpiredRuntimeReconnectRetries :many+-- A runtime_offline retry waits in deferred until its runtime returns healthy.+-- Give that recovery state a bounded exit: after one full reconnect grace,+-- fail it with a non-retryable reason so issues, agents, and runtime GC can+-- converge. A runtime that is healthy when this query runs wins the race and+-- remains deferred for the next daemon poll to promote. The parent join is the+-- lineage discriminator; provider backoff and other deferred task types are+-- intentionally excluded.+WITH victims AS (+ SELECT retry.id+ FROM agent_task_queue retry+ JOIN agent_task_queue parent ON parent.id = retry.parent_task_id+ WHERE retry.status = 'deferred'+ AND retry.fire_at < now() - make_interval(secs => @reconnect_grace_secs::double precision)+ AND parent.failure_reason = 'runtime_offline'+ AND NOT EXISTS (+ SELECT 1 FROM agent_runtime runtime+ WHERE runtime.id = retry.runtime_id+ AND runtime.status = 'online'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )+ ORDER BY retry.fire_at, retry.created_at+ LIMIT @max_per_tick::int+ FOR UPDATE OF retry SKIP LOCKED+)+UPDATE agent_task_queue AS retry+SET status = 'failed',+ completed_at = now(),+ error = 'runtime did not reconnect within the configured grace period',+ failure_reason = 'runtime_reconnect_timeout',+ wait_reason = NULL,+ prepare_lease_expires_at = NULL+FROM victims+WHERE retry.id = victims.id+ AND retry.status = 'deferred'+ AND retry.fire_at < now() - make_interval(secs => @reconnect_grace_secs::double precision)+ AND EXISTS (+ SELECT 1 FROM agent_task_queue parent+ WHERE parent.id = retry.parent_task_id+ AND parent.failure_reason = 'runtime_offline'+ )+ AND NOT EXISTS (+ SELECT 1 FROM agent_runtime runtime+ WHERE runtime.id = retry.runtime_id+ AND runtime.status = 'online'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )+RETURNING retry.*;+-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL@@ -1597,6 +1703,13 @@ SET status = 'queued'WHERE runtime_id = @runtime_idAND status = 'deferred'AND fire_at <= now()+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )RETURNING *;-- name: ListQueuedClaimCandidatesByRuntimes :many@@ -1622,6 +1735,13 @@ SET status = 'queued'WHERE runtime_id = ANY(@runtime_ids::uuid[])AND status = 'deferred'AND fire_at <= now()+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = agent_task_queue.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )RETURNING *;-- name: CancelDeferredEscalationsForTask :manydiff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex ea2ec39020..af7712bc9b 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -243,17 +243,33 @@ RETURNING id, workspace_id, owner_id, daemon_id, provider;-- name: FailTasksForOfflineRuntimes :many-- Marks dispatched/running/waiting_local_directory tasks as failed when--- their runtime is offline. This cleans up orphaned tasks after a daemon--- crash or network partition.-UPDATE agent_task_queue+-- their runtime has remained offline beyond the reconnect grace. A short or+-- medium network partition must not terminate a daemon process that is still+-- running locally; a real daemon restart is recovered separately through+-- RecoverOrphanedTasksForRuntime. Bounded per tick so a large recovery backlog+-- cannot monopolise the sweeper transaction. last_seen_at is normally set by+-- the first heartbeat; updated_at is only the fallback for a never-heartbeated+-- runtime, and a forced-offline write starts its grace from that update.+WITH victims AS (+ SELECT task.id+ FROM agent_task_queue task+ JOIN agent_runtime runtime ON runtime.id = task.runtime_id+ WHERE task.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND runtime.status = 'offline'+ AND COALESCE(runtime.last_seen_at, runtime.updated_at) <+ now() - make_interval(secs => @reconnect_grace_secs::double precision)+ ORDER BY COALESCE(runtime.last_seen_at, runtime.updated_at), task.created_at+ LIMIT @max_per_tick::int+ FOR UPDATE OF task SKIP LOCKED+)+UPDATE agent_task_queue AS taskSET status = 'failed', completed_at = now(), error = 'runtime went offline',failure_reason = 'runtime_offline',wait_reason = NULL-WHERE status IN ('dispatched', 'running', 'waiting_local_directory')- AND runtime_id IN (- SELECT id FROM agent_runtime WHERE status = 'offline'- )-RETURNING *;+FROM victims+WHERE task.id = victims.id+ AND task.status IN ('dispatched', 'running', 'waiting_local_directory')+RETURNING task.*;-- name: ListAgentRuntimesByOwner :manySELECT * FROM agent_runtimediff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex 534d899a82..dfa72b9d73 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -63,7 +63,7 @@ func Classify(rawError string) Reason {trimmed := strings.TrimSpace(rawError)if trimmed == "" {// SQL maps NULL/empty to a separate bucket ("empty_error"),- // but that bucket is not part of the canonical 22. In-flight+ // but that bucket is not part of the canonical taxonomy. In-flight// callers should never hand us empty input — if they do, the// safest landing is the catchall.return ReasonAgentUnknowndiff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex fa01478590..430e7be85d 100644--- a/server/pkg/taskfailure/failure.go+++ b/server/pkg/taskfailure/failure.go@@ -12,20 +12,20 @@// This package lifts that classifier into the in-flight write path so the// stored failure_reason is already refined when the row is first// persisted, and so server / daemon / cloud share a single source of-// truth for the canonical 22 values. PR1 of the Grafana board plan+// truth for the canonical values. PR1 of the Grafana board plan// ([MUL-2946](https://multica/issues/MUL-2946)). Subsequent PRs use// AllReasons() to pre-warm the Prometheus failure_reason label set.//-// The 22 canonical values fall into two groups:+// The canonical values fall into two groups://-// - 8 platform-side values (no `agent_error.` prefix) emitted by the+// - Platform-side values (no `agent_error.` prefix) emitted by the// server-side sweepers and daemon classifiers when the failure is// attributable to the platform/scheduler/runtime layer rather than// anything the agent process did://-// queued_expired, runtime_offline, runtime_recovery, timeout,-// iteration_limit, agent_blocked, api_invalid_request,-// skill_bundle_unavailable+// queued_expired, runtime_offline, runtime_reconnect_timeout,+// runtime_recovery, timeout, iteration_limit, agent_blocked,+// api_invalid_request, skill_bundle_unavailable//// - 14 agent-side values (with `agent_error.` prefix) produced by// Classify(rawError) when the agent process surfaced an error string.@@ -33,9 +33,9 @@//// Wire stability: the string forms of these constants are persisted into// the database and surfaced as Prometheus labels. Renaming a value is a-// breaking change. New values may be added — but only after the SQL-// classifier in MUL-1949 grows a matching rule and a backfill migration-// re-classifies historical rows.+// breaking change. New classifier-derived values also require a matching SQL+// backfill rule; new platform-side events may be added directly because no+// historical rows need reclassification.package taskfailureimport "strings"@@ -48,7 +48,7 @@ type Reason string// agentErrorPrefix marks the 14 sub-reasons that originate inside the// agent process (provider error, runner crash, context overflow, etc.)-// as opposed to the 8 platform-side reasons (queue expiry, runtime+// as opposed to the platform-side reasons (queue expiry, runtime// offline, sweeper timeout, etc.). IsAgentError uses this prefix so// callers don't have to enumerate the agent-side reasons by hand.const agentErrorPrefix = "agent_error."@@ -71,6 +71,12 @@ const (// task went offline. Written by FailTasksForOfflineRuntimes.ReasonRuntimeOffline Reason = "runtime_offline"+ // ReasonRuntimeReconnectTimeout: a retry waiting for an offline runtime+ // remained deferred for the full reconnect grace. Non-retryable: the+ // runtime must return before a user starts another attempt. Written by+ // FailExpiredRuntimeReconnectRetries.+ ReasonRuntimeReconnectTimeout Reason = "runtime_reconnect_timeout"+// ReasonRuntimeRecovery: the daemon restarted while the task was// in flight; the prior session is unrecoverable. Written by// RecoverOrphanedTasksForRuntime at daemon startup.@@ -199,6 +205,7 @@ var allReasons = []Reason{// Platform / scheduler side.ReasonQueuedExpired,ReasonRuntimeOffline,+ ReasonRuntimeReconnectTimeout,ReasonRuntimeRecovery,ReasonTimeout,ReasonIterationLimit,@@ -244,7 +251,7 @@ func (r Reason) IsAgentError() bool {return strings.HasPrefix(string(r), agentErrorPrefix)}-// AllReasons returns the canonical 22 reasons in a stable order. The+// AllReasons returns the canonical reasons in a stable order. The// caller MUST NOT mutate the returned slice; a copy is returned so// concurrent callers can append to their local copy without corrupting// the package-level fixture.diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.goindex 4f1a9a980d..1080fff541 100644--- a/server/pkg/taskfailure/failure_test.go+++ b/server/pkg/taskfailure/failure_test.go@@ -21,6 +21,7 @@ func TestReasonStringWireValues(t *testing.T) {// Platform-side.{ReasonQueuedExpired, "queued_expired"},{ReasonRuntimeOffline, "runtime_offline"},+ {ReasonRuntimeReconnectTimeout, "runtime_reconnect_timeout"},{ReasonRuntimeRecovery, "runtime_recovery"},{ReasonTimeout, "timeout"},{ReasonIterationLimit, "iteration_limit"},@@ -44,7 +45,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonAgentUnknown, "agent_error.unknown"},}- if got, want := len(cases), 22; got != want {+ if got, want := len(cases), 23; got != want {t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)}@@ -66,6 +67,7 @@ func TestIsAgentError(t *testing.T) {platformSide := []Reason{ReasonQueuedExpired,ReasonRuntimeOffline,+ ReasonRuntimeReconnectTimeout,ReasonRuntimeRecovery,ReasonTimeout,ReasonIterationLimit,@@ -112,8 +114,8 @@ func TestAllReasonsContents(t *testing.T) {t.Parallel()got := AllReasons()- if len(got) != 22 {- t.Fatalf("AllReasons() returned %d entries, want 22", len(got))+ if len(got) != 23 {+ t.Fatalf("AllReasons() returned %d entries, want 23", len(got))}seen := make(map[Reason]bool, len(got))@@ -130,8 +132,8 @@ func TestAllReasonsContents(t *testing.T) {}}- if platformCount != 8 {- t.Errorf("AllReasons(): platform-side count = %d, want 8", platformCount)+ if platformCount != 9 {+ t.Errorf("AllReasons(): platform-side count = %d, want 9", platformCount)}if agentCount != 14 {t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)@@ -142,7 +144,8 @@ func TestAllReasonsContents(t *testing.T) {// someone adds a constant but forgets to register it in the// allReasons slice.required := []Reason{- ReasonQueuedExpired, ReasonRuntimeOffline, ReasonRuntimeRecovery,+ ReasonQueuedExpired, ReasonRuntimeOffline, ReasonRuntimeReconnectTimeout,+ ReasonRuntimeRecovery,ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,