Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): reclaim stale dispatched claims (MUL-2485) (#2872)
YOMXXX29c2a5d18f90
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 746faf003b..556a52f292 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -95,6 +95,218 @@ func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonIDreturn req.WithContext(ctx)}+func createClaimReclaimRuntime(t *testing.T, ctx context.Context, name string) string {+ t.Helper()++ var runtimeID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider,+ status, device_info, metadata, last_seen_at, visibility+ )+ VALUES ($1, NULL, $2, 'cloud', 'handler_test_runtime', 'online', 'claim reclaim fixture', '{}'::jsonb, now(), 'private')+ RETURNING id+ `, testWorkspaceID, name).Scan(&runtimeID); err != nil {+ t.Fatalf("setup: create runtime: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })++ return runtimeID+}++func createClaimReclaimAgentAndIssue(t *testing.T, ctx context.Context, runtimeID, name string) (string, string) {+ t.Helper()++ var agentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id+ )+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)+ RETURNING id+ `, testWorkspaceID, name, runtimeID, testUserID).Scan(&agentID); err != nil {+ t.Fatalf("setup: create agent: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES (+ $1, $2, 'in_progress', 'none', $3, 'member',+ (SELECT COALESCE(MAX(number), 82649) + 1 FROM issue WHERE workspace_id = $1),+ 0+ )+ RETURNING id+ `, testWorkspaceID, name+" issue", testUserID).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ return agentID, issueID+}++func createDispatchedClaimFixtureTask(t *testing.T, ctx context.Context, agentID, runtimeID, issueID, dispatchedAge string, started bool) string {+ t.Helper()++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, dispatched_at, started_at+ )+ VALUES ($1, $2, $3, 'dispatched', 0, now() - ($4::interval), CASE WHEN $5::boolean THEN now() ELSE NULL END)+ RETURNING id+ `, agentID, runtimeID, issueID, dispatchedAge, started).Scan(&taskID); err != nil {+ t.Fatalf("setup: create dispatched task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ return taskID+}++func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {+ ID string `json:"id"`+}, string) {+ t.Helper()++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,+ testWorkspaceID, "claim-reclaim-review")+ req = withURLParam(req, "runtimeId", runtimeID)++ testHandler.ClaimTaskByRuntime(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp struct {+ Task *struct {+ ID string `json:"id"`+ } `json:"task"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode claim response: %v", err)+ }+ return resp.Task, w.Body.String()+}++func TestClaimTaskByRuntime_ReclaimsStaleDispatchedTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Stale dispatch reclaim runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Stale dispatch reclaim agent")+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)++ task, body := claimTaskByRuntimeForTest(t, runtimeID)+ if task == nil {+ t.Fatalf("expected stale dispatched task %s to be reclaimed, got nil response: %s", taskID, body)+ }+ if task.ID != taskID {+ t.Fatalf("reclaimed task id = %s, want %s", task.ID, taskID)+ }++ var refreshed bool+ if err := testPool.QueryRow(ctx, `+ SELECT dispatched_at > now() - interval '15 seconds'+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&refreshed); err != nil {+ t.Fatalf("load refreshed dispatched_at: %v", err)+ }+ if !refreshed {+ t.Fatal("expected reclaimed task to refresh dispatched_at")+ }+}++func TestClaimTaskByRuntime_DoesNotReclaimFreshDispatchedTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Fresh dispatch reclaim runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Fresh dispatch reclaim agent")+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "75 seconds", false)++ task, body := claimTaskByRuntimeForTest(t, runtimeID)+ if task != nil {+ t.Fatalf("expected fresh dispatched task %s not to be reclaimed, got %s in %s", taskID, task.ID, body)+ }++ var stillFresh bool+ if err := testPool.QueryRow(ctx, `+ SELECT dispatched_at < now() - interval '70 seconds'+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&stillFresh); err != nil {+ t.Fatalf("load fresh dispatched task: %v", err)+ }+ if !stillFresh {+ t.Fatal("expected fresh dispatched task to keep its original dispatched_at")+ }+}++func TestClaimTaskByRuntime_DoesNotReclaimAlreadyStartedTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Started dispatch reclaim runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Started dispatch reclaim agent")+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", true)++ task, body := claimTaskByRuntimeForTest(t, runtimeID)+ if task != nil {+ t.Fatalf("expected started dispatched task %s not to be reclaimed, got %s in %s", taskID, task.ID, body)+ }++ var startedAtValid bool+ if err := testPool.QueryRow(ctx, `+ SELECT started_at IS NOT NULL+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&startedAtValid); err != nil {+ t.Fatalf("load started dispatched task: %v", err)+ }+ if !startedAtValid {+ t.Fatal("expected started dispatched task to keep started_at")+ }+}++func TestClaimTaskByRuntime_DoesNotReclaimDifferentRuntimeTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ claimingRuntimeID := createClaimReclaimRuntime(t, ctx, "Claiming dispatch reclaim runtime")+ owningRuntimeID := createClaimReclaimRuntime(t, ctx, "Owning dispatch reclaim runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, owningRuntimeID, "Different runtime reclaim agent")+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, owningRuntimeID, issueID, "120 seconds", false)++ task, body := claimTaskByRuntimeForTest(t, claimingRuntimeID)+ if task != nil {+ t.Fatalf("expected other-runtime task %s not to be reclaimed, got %s in %s", taskID, task.ID, body)+ }++ var runtimeID string+ if err := testPool.QueryRow(ctx, `+ SELECT runtime_id::text+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&runtimeID); err != nil {+ t.Fatalf("load other-runtime dispatched task: %v", err)+ }+ if runtimeID != owningRuntimeID {+ t.Fatalf("task runtime_id = %s, want %s", runtimeID, owningRuntimeID)+ }+}+func TestDaemonRegister_WithDaemonToken(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex f28d152f31..f703e4aa82 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -77,7 +77,13 @@ func truncateForSummary(s string, maxRunes int) string {return string(rs[:maxRunes]) + "…"}-const taskAnalyticsContextCacheMax = 4096+const (+ taskAnalyticsContextCacheMax = 4096+ // claimResponseRecoveryWindow must exceed daemon client.Timeout for+ // /tasks/claim (30s) plus /tasks/{id}/start (30s) plus scheduling slack, so+ // an in-flight StartTask cannot be reclaimed and double-dispatched.+ claimResponseRecoveryWindow = 90 * time.Second+)// buildCommentTriggerSummary fetches the comment content and truncates// it for storage on the task row. Returns an invalid pgtype.Text when@@ -831,6 +837,27 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.}()runtimeKey := util.UUIDToString(runtimeID)+ // Check this before EmptyClaim: a lost claim response moves the task out of+ // `queued`, so the empty-queued cache cannot represent recoverability.+ stale, err := s.Queries.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{+ RuntimeID: runtimeID,+ ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),+ })+ if err == nil {+ outcome = "reclaimed_dispatched"+ claimedFlag = true+ slog.Info("stale dispatched task reclaimed",+ "task_id", util.UUIDToString(stale.ID),+ "runtime_id", runtimeKey,+ "agent_id", util.UUIDToString(stale.AgentID),+ )+ return &stale, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ outcome = "error_reclaim_dispatched"+ return nil, fmt.Errorf("reclaim stale dispatched task: %w", err)+ }+if s.EmptyClaim.IsEmpty(ctx, runtimeKey) {outcome = "empty_cache_hit"return nil, nildiff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 63d75e537f..88f0289e98 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -517,6 +517,65 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agenreturn i, err}+const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :one+UPDATE agent_task_queue+SET dispatched_at = now()+WHERE id = (+ SELECT atq.id FROM agent_task_queue atq+ WHERE atq.runtime_id = $1+ AND atq.status = 'dispatched'+ AND atq.started_at IS NULL+ AND atq.dispatched_at < now() - make_interval(secs => $2::double precision)+ ORDER BY atq.priority DESC, atq.dispatched_at ASC+ LIMIT 1+ FOR UPDATE SKIP LOCKED+)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+`++type ReclaimStaleDispatchedTaskForRuntimeParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ ClaimRecoverySecs float64 `json:"claim_recovery_secs"`+}++// Re-delivers a task whose previous claim likely succeeded server-side but+// whose response never reached the daemon. The task is still in `dispatched`+// with no `started_at`, so the daemon has not acknowledged it via StartTask.+// 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.ClaimRecoverySecs)+ var i AgentTaskQueue+ err := row.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,+ )+ return i, err+}+const clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :oneUPDATE agent SET mcp_config = NULL, updated_at = now()WHERE id = $1diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 1b566a8535..81ee1fe79a 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -239,6 +239,26 @@ WHERE id = ()RETURNING *;+-- name: ReclaimStaleDispatchedTaskForRuntime :one+-- Re-delivers a task whose previous claim likely succeeded server-side but+-- whose response never reached the daemon. The task is still in `dispatched`+-- with no `started_at`, so the daemon has not acknowledged it via StartTask.+-- Refresh dispatched_at so the server-side dispatch timeout measures from the+-- recovered delivery attempt.+UPDATE agent_task_queue+SET dispatched_at = now()+WHERE id = (+ SELECT atq.id FROM agent_task_queue atq+ WHERE atq.runtime_id = $1+ AND atq.status = 'dispatched'+ AND atq.started_at IS NULL+ AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)+ ORDER BY atq.priority DESC, atq.dispatched_at ASC+ LIMIT 1+ FOR UPDATE SKIP LOCKED+)+RETURNING *;+-- name: StartAgentTask :oneUPDATE agent_task_queueSET status = 'running', started_at = now()