Skip to content

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

Go

feat(task): wire claim lease into TaskService and sweeper (MUL-2246) (#2662)

LinYushenbb32be0e507b
diff --git a/server/cmd/server/autopilot_listeners_test.go b/server/cmd/server/autopilot_listeners_test.go
index 6db6999c6f..0eecc5772b 100644
--- a/server/cmd/server/autopilot_listeners_test.go
+++ b/server/cmd/server/autopilot_listeners_test.go
@@ -47,7 +47,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
{
name: "failed",
finalize: func(task db.AgentTaskQueue) {
- if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "agent_error"); err != nil {
+ if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "agent_error", ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
},
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 910915132b..27529b68b6 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -311,6 +311,8 @@ func main() {
if storeRedis != nil {
liveness = handler.NewRedisLivenessStore(storeRedis)
}
+ taskSvc.Liveness = liveness
+ taskSvc.EmptyClaim = service.NewEmptyClaimCache(storeRedis)
// Start background sweeper to mark stale runtimes as offline.
go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus)
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 0c7939cbc3..2e26fa59b3 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -80,6 +80,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handle
case <-ticker.C:
sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)
sweepStaleTasks(ctx, queries, taskSvc, bus)
+ sweepExpiredClaimLeases(ctx, taskSvc)
sweepExpiredQueuedTasks(ctx, queries, taskSvc)
gcRuntimes(ctx, queries, bus)
}
@@ -256,6 +257,19 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.
taskSvc.HandleFailedTasks(ctx, failedTasks)
}
+// sweepExpiredClaimLeases is the global backstop that requeues dispatched
+// tasks whose claim lease has expired. Only requeues tasks whose runtime has
+// a fresh heartbeat (last_seen_at within staleThresholdSeconds), preventing
+// requeue to a dead runtime in the 90s gap between lease expiry (60s) and
+// offline detection (150s). The primary requeue path is the preflight in
+// ClaimTaskForRuntime (self-requeue when the runtime actively claims).
+func sweepExpiredClaimLeases(ctx context.Context, taskSvc *service.TaskService) {
+ if taskSvc == nil {
+ return
+ }
+ taskSvc.RequeueExpiredClaimLeases(ctx, staleThresholdSeconds)
+}
+
// sweepExpiredQueuedTasks fails tasks that have been sitting in 'queued' for
// longer than the TTL. Companion to the dispatch-time admission gate added
// in MUL-1899: that gate prevents new doomed enqueues; this gate drains the
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index d0220c672e..f28e16e165 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -152,8 +152,12 @@ func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error)
return resp.Task, nil
}
-func (c *Client) StartTask(ctx context.Context, taskID string) error {
- return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), map[string]any{}, nil)
+func (c *Client) StartTask(ctx context.Context, taskID string, claimToken string) error {
+ body := map[string]any{}
+ if claimToken != "" {
+ body["claim_token"] = claimToken
+ }
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), body, nil)
}
func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, step, total int) error {
@@ -203,7 +207,7 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}, nil)
}
-func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason string) error {
+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason, claimToken string) error {
body := map[string]any{"error": errMsg}
if sessionID != "" {
body["session_id"] = sessionID
@@ -214,6 +218,9 @@ func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDi
if failureReason != "" {
body["failure_reason"] = failureReason
}
+ if claimToken != "" {
+ body["claim_token"] = claimToken
+ }
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil)
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a81b5a8e9e..c2bcb326ff 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
"math/rand"
+ "net/http"
"os"
"path/filepath"
"strconv"
@@ -1852,13 +1853,48 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
taskLog.Info("picked task", "issue", task.IssueID, "agent", agentName, "provider", provider)
}
- if err := d.client.StartTask(ctx, task.ID); err != nil {
- taskLog.Error("start task failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", "", "agent_error"); failErr != nil {
- taskLog.Error("fail task after start error", "error", failErr)
+ if err := d.client.StartTask(ctx, task.ID, task.ClaimToken); err != nil {
+ var reqErr *requestError
+ if errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusConflict {
+ // 409: claim expired or superseded — task is no longer ours.
+ // Release slot (via defer) without calling FailTask.
+ taskLog.Warn("start task: claim superseded (409), releasing slot", "error", err)
+ return
+ }
+
+ // Transport error or 5xx: retry once with the same token before giving up.
+ if !errors.As(err, &reqErr) || reqErr.StatusCode >= 500 {
+ taskLog.Warn("start task: transient error, retrying", "error", err)
+ time.Sleep(2 * time.Second)
+ if retryErr := d.client.StartTask(ctx, task.ID, task.ClaimToken); retryErr != nil {
+ var retryReqErr *requestError
+ if errors.As(retryErr, &retryReqErr) && retryReqErr.StatusCode == http.StatusConflict {
+ taskLog.Warn("start task retry: claim superseded (409), releasing slot")
+ return
+ }
+ // Retry failed — check task status before calling FailTask.
+ if status, statusErr := d.client.GetTaskStatus(ctx, task.ID); statusErr == nil && status == "running" {
+ taskLog.Info("start task retry failed but task is already running, proceeding")
+ // Fall through to continue execution.
+ goto startOK
+ }
+ taskLog.Error("start task failed after retry", "error", retryErr)
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", retryErr.Error()), "", "", "agent_error", task.ClaimToken); failErr != nil {
+ taskLog.Error("fail task after start error", "error", failErr)
+ }
+ return
+ }
+ // Retry succeeded, fall through.
+ } else {
+ // 4xx (non-409): deterministic failure, no retry.
+ taskLog.Error("start task failed", "error", err)
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", "", "agent_error", task.ClaimToken); failErr != nil {
+ taskLog.Error("fail task after start error", "error", failErr)
+ }
+ return
}
- return
}
+startOK:
_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)
@@ -1909,7 +1945,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
taskLog.Error("task failed", "error", err)
// runTask returned without a TaskResult, so we don't have a SessionID
// to forward — best we can do is record the failure.
- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "agent_error"); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "agent_error", task.ClaimToken); failErr != nil {
taskLog.Error("fail task callback failed", "error", failErr)
}
return
@@ -1926,7 +1962,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
return
}
- d.reportTaskResult(ctx, task.ID, result, taskLog)
+ d.reportTaskResult(ctx, task.ID, result, task.ClaimToken, taskLog)
// Write GC metadata after the task finishes so the periodic GC loop
// can look up the parent record (issue / chat session / autopilot run /
@@ -1951,13 +1987,13 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// the agent may have built a real session before getting stuck, and we want
// the next chat turn to resume there rather than start over and "forget"
// the conversation.
-func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result TaskResult, taskLog *slog.Logger) {
+func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result TaskResult, claimToken string, taskLog *slog.Logger) {
switch result.Status {
case "completed":
taskLog.Info("task completed", "status", result.Status)
if err := d.client.CompleteTask(ctx, taskID, result.Comment, result.BranchName, result.SessionID, result.WorkDir); err != nil {
taskLog.Error("complete task failed, falling back to fail", "error", err)
- if failErr := d.client.FailTask(ctx, taskID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir, "agent_error"); failErr != nil {
+ if failErr := d.client.FailTask(ctx, taskID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir, "agent_error", claimToken); failErr != nil {
taskLog.Error("fail task fallback also failed", "error", failErr)
}
}
@@ -1971,7 +2007,7 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
}
}
taskLog.Info("task did not complete, reporting failure", "status", result.Status, "failure_reason", failureReason)
- if err := d.client.FailTask(ctx, taskID, result.Comment, result.SessionID, result.WorkDir, failureReason); err != nil {
+ if err := d.client.FailTask(ctx, taskID, result.Comment, result.SessionID, result.WorkDir, failureReason, claimToken); err != nil {
taskLog.Error("report failed task failed", "error", err)
}
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 97030685ba..cb31382c72 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -1423,7 +1423,7 @@ func TestReportTaskResult_CompletedHitsCompleteEndpoint(t *testing.T) {
BranchName: "agent/foo",
SessionID: "ses-1",
WorkDir: "/tmp/foo",
- }, slog.Default())
+ }, "", slog.Default())
rec.mu.Lock()
defer rec.mu.Unlock()
@@ -1494,7 +1494,7 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {
SessionID: "ses-x",
WorkDir: "/tmp/x",
FailureReason: tc.failureReasonIn,
- }, slog.Default())
+ }, "", slog.Default())
rec.mu.Lock()
defer rec.mu.Unlock()
@@ -1712,3 +1712,64 @@ func TestHandleTask_ReportsUsageWhenCancelledByPoll(t *testing.T) {
t.Fatalf("usage reported before poll-status (order: %v) — poll-status must come first", order)
}
}
+
+// TestHandleTask_UsageReportedOnceOnNormalCompletion verifies that /usage is
+// called exactly once when a task completes normally (not cancelled). Regression
+// test for the merge-conflict duplicate usage block.
+func TestHandleTask_UsageReportedOnceOnNormalCompletion(t *testing.T) {
+ t.Parallel()
+
+ var usageCount atomic.Int32
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/start"):
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/progress"):
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/usage"):
+ usageCount.Add(1)
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"status":"running"}`))
+ case strings.HasSuffix(r.URL.Path, "/result"):
+ w.WriteHeader(http.StatusOK)
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},
+ cancelPollInterval: time.Hour,
+ }
+
+ d.runner = taskRunnerFunc(func(_ context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ return TaskResult{
+ Status: "completed",
+ SessionID: "sess-1",
+ Usage: []TaskUsageEntry{
+ {Provider: "anthropic", Model: "claude-opus-4-6", InputTokens: 200, OutputTokens: 100},
+ },
+ }, nil
+ })
+
+ task := Task{
+ ID: "task-usage-once",
+ RuntimeID: "rt-1",
+ IssueID: "issue-1",
+ Agent: &AgentData{Name: "test-agent"},
+ }
+
+ d.handleTask(context.Background(), task, 0)
+
+ if got := usageCount.Load(); got != 1 {
+ t.Fatalf("/usage called %d times, want exactly 1", got)
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index da0778b422..03184ff64b 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -61,6 +61,7 @@ type Task struct {
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
SquadID string `json:"squad_id,omitempty"` // when the picker was a squad, the squad's UUID; Agent is still the resolved leader
SquadName string `json:"squad_name,omitempty"` // display name for the picker squad, used in prompt text
+ ClaimToken string `json:"claim_token,omitempty"` // opaque token to present in StartTask as proof of claim receipt
}
// ChatAttachmentMeta is the structured attachment metadata the daemon
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 5b265292e5..c2e12c1949 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -177,6 +177,7 @@ type AgentTaskResponse struct {
SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader
SquadName string `json:"squad_name,omitempty"` // display name for the picker squad
Kind string `json:"kind"` // discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "direct" — used by the activity row to label tasks that have no linked issue
+ ClaimToken string `json:"claim_token,omitempty"` // opaque token the daemon must present in StartTask to prove it received the claim
}
// ChatAttachmentMeta is the structured attachment metadata embedded in
@@ -237,6 +238,7 @@ func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {
TriggerCommentID: uuidToPtr(t.TriggerCommentID),
TriggerSummary: textToPtr(t.TriggerSummary),
WorkDir: workDir,
+ ClaimToken: uuidToString(t.ClaimToken),
// Surface task source so the UI can distinguish issue-linked tasks
// from chat-spawned or autopilot-spawned ones; all three may arrive
// with issue_id = "" once a task has no linked issue.
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 05f3f9697c..4b570054db 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1500,8 +1500,29 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.TaskService.StartTask(r.Context(), parseUUID(taskID))
+ // Read optional claim_token from body (new daemons send it; old ones don't).
+ var body struct {
+ ClaimToken string `json:"claim_token"`
+ }
+ // Best-effort decode; empty body is fine for legacy daemons.
+ json.NewDecoder(r.Body).Decode(&body)
+
+ var claimToken pgtype.UUID
+ if body.ClaimToken != "" {
+ parsed, err := util.ParseUUID(body.ClaimToken)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "malformed claim_token")
+ return
+ }
+ claimToken = parsed
+ }
+
+ task, err := h.TaskService.StartTask(r.Context(), parseUUID(taskID), claimToken)
if err != nil {
+ if errors.Is(err, service.ErrClaimTokenInvalid) {
+ writeError(w, http.StatusConflict, "claim token expired or superseded")
+ return
+ }
slog.Warn("start task failed", "task_id", taskID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -1686,6 +1707,7 @@ type TaskFailRequest struct {
SessionID string `json:"session_id,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
+ ClaimToken string `json:"claim_token,omitempty"`
}
func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
@@ -1702,8 +1724,16 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason)
+ task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason, req.ClaimToken)
if err != nil {
+ if errors.Is(err, service.ErrInvalidClaimToken) {
+ writeError(w, http.StatusBadRequest, "malformed claim token")
+ return
+ }
+ if errors.Is(err, service.ErrClaimTokenInvalid) {
+ writeError(w, http.StatusConflict, "claim token expired or superseded")
+ return
+ }
slog.Warn("fail task failed", "task_id", taskID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 7aa9e0983a..1e527e2265 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -23,6 +23,13 @@ import (
"github.com/multica-ai/multica/server/pkg/redact"
)
+// LivenessChecker is a subset of handler.LivenessStore used by TaskService
+// to verify runtime liveness without importing the handler package.
+type LivenessChecker interface {
+ Available() bool
+ IsAliveBatch(ctx context.Context, runtimeIDs []string) (alive map[string]bool, ok bool)
+}
+
type TaskService struct {
Queries *db.Queries
TxStarter TxStarter
@@ -36,6 +43,11 @@ type TaskService struct {
// goes through the DB. Wired in router.go from the shared Redis
// client.
EmptyClaim *EmptyClaimCache
+ // Liveness provides real-time heartbeat verification for runtimes.
+ // Currently unused — the global backstop no longer requeues tasks
+ // (alive runtimes self-requeue via preflight, dead runtimes stay
+ // dispatched for the offline sweeper). Retained for future use.
+ Liveness LivenessChecker
analyticsContextMu sync.Mutex
analyticsContextCache map[string]analytics.TaskContext
@@ -51,6 +63,24 @@ type TaskWakeupNotifier interface {
// recognisable preview of a one-paragraph comment.
const triggerSummaryMaxLen = 200
+// claimLeaseSeconds is the duration (in seconds) a dispatched task's claim
+// lease is valid. The daemon must call StartTask with the claim_token within
+// this window; otherwise the expired-lease sweeper requeues the task.
+const claimLeaseSeconds = 60.0
+
+// ErrClaimTokenInvalid is returned when StartTask is called with a claim_token
+// that does not match or whose lease has expired (task may have been requeued
+// and re-claimed by another runtime).
+var ErrClaimTokenInvalid = errors.New("claim token expired or superseded")
+
+// ErrInvalidClaimToken is returned when a malformed (non-UUID) claim_token is
+// supplied. The caller should surface this as a 400 Bad Request.
+var ErrInvalidClaimToken = errors.New("malformed claim token")
+
+// requeueMaxPerTick caps how many expired-lease rows a single sweeper tick
+// requeues back to 'queued'. Keeps the sweep transaction short.
+const RequeueMaxPerTick = 50
+
// truncateForSummary returns s shortened to maxRunes, with a trailing
// `…` when truncated. Operates on runes (not bytes) so multibyte characters
// — Chinese / emoji — count as one each. Strips surrounding whitespace
@@ -732,7 +762,7 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
// ClaimTask atomically claims the next queued task for an agent,
// respecting max_concurrent_tasks.
-func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
+func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
start := time.Now()
var (
outcome = "unknown"
@@ -764,7 +794,11 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
}
t0 = time.Now()
- task, err := s.Queries.ClaimAgentTask(ctx, agentID)
+ task, err := s.Queries.ClaimAgentTaskForRuntime(ctx, db.ClaimAgentTaskForRuntimeParams{
+ AgentID: agentID,
+ RuntimeID: runtimeID,
+ LeaseSeconds: claimLeaseSeconds,
+ })
claimAgentMs = time.Since(t0).Milliseconds()
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -830,6 +864,15 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
}()
runtimeKey := util.UUIDToString(runtimeID)
+
+ // Preflight: requeue this runtime's own expired leases BEFORE the
+ // empty-cache fast-path. The runtime is actively claiming so it's
+ // provably alive — safe to requeue without any heartbeat/liveness
+ // check. Must run first because lease expiry is time-driven and
+ // won't bump the empty cache on its own; without this, an expired
+ // lease would be invisible behind a stale empty verdict.
+ s.RequeueExpiredClaimLeasesForRuntime(ctx, runtimeID)
+
if s.EmptyClaim.IsEmpty(ctx, runtimeKey) {
outcome = "empty_cache_hit"
return nil, nil
@@ -869,13 +912,13 @@ 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"
return nil, err
}
- if task != nil && task.RuntimeID == runtimeID {
+ if task != nil {
claimed = task
break
}
@@ -913,10 +956,29 @@ func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, sta
// StartTask transitions a dispatched task to running.
// Issue status is NOT changed here — the agent manages it via the CLI.
-func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {
- task, err := s.Queries.StartAgentTask(ctx, taskID)
- if err != nil {
- return nil, fmt.Errorf("start task: %w", err)
+// When claimToken is valid, uses the token-verified path; otherwise falls
+// back to the legacy tokenless start for old daemons (only works on rows
+// without a claim_token).
+func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, claimToken pgtype.UUID) (*db.AgentTaskQueue, error) {
+ var task db.AgentTaskQueue
+ var err error
+ if claimToken.Valid {
+ row, rowErr := s.Queries.StartAgentTaskWithClaimToken(ctx, db.StartAgentTaskWithClaimTokenParams{
+ ID: taskID,
+ ClaimToken: claimToken,
+ })
+ if rowErr != nil {
+ if errors.Is(rowErr, pgx.ErrNoRows) {
+ return nil, ErrClaimTokenInvalid
+ }
+ return nil, fmt.Errorf("start task: %w", rowErr)
+ }
+ task = startAgentTaskRowToQueue(row)
+ } else {
+ task, err = s.Queries.StartAgentTask(ctx, taskID)
+ if err != nil {
+ return nil, fmt.Errorf("start task: %w", err)
+ }
}
slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
@@ -924,6 +986,74 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
return &task, nil
}
+func startAgentTaskRowToQueue(r db.StartAgentTaskWithClaimTokenRow) db.AgentTaskQueue {
+ return db.AgentTaskQueue{
+ ID: r.ID,
+ AgentID: r.AgentID,
+ IssueID: r.IssueID,
+ Status: r.Status,
+ Priority: r.Priority,
+ DispatchedAt: r.DispatchedAt,
+ StartedAt: r.StartedAt,
+ CompletedAt: r.CompletedAt,
+ Result: r.Result,
+ Error: r.Error,
+ CreatedAt: r.CreatedAt,
+ Context: r.Context,
+ RuntimeID: r.RuntimeID,
+ SessionID: r.SessionID,
+ WorkDir: r.WorkDir,
+ TriggerCommentID: r.TriggerCommentID,
+ ChatSessionID: r.ChatSessionID,
+ AutopilotRunID: r.AutopilotRunID,
+ Attempt: r.Attempt,
+ MaxAttempts: r.MaxAttempts,
+ ParentTaskID: r.ParentTaskID,
+ FailureReason: r.FailureReason,
+ TriggerSummary: r.TriggerSummary,
+ ForceFreshSession: r.ForceFreshSession,
+ IsLeaderTask: r.IsLeaderTask,
+ ClaimToken: r.ClaimToken,
+ ClaimExpiresAt: r.ClaimExpiresAt,
+ }
+}
+
+// RequeueExpiredClaimLeases is the global backstop. It does NOT requeue
+// tasks directly — alive runtimes handle their own expired leases via the
+// preflight in ClaimTaskForRuntime, and dead runtimes must stay dispatched
+// so FailTasksForOfflineRuntimes can fail+retry them properly. Requeuing
+// dead runtime tasks to 'queued' would create a blackhole: offline sweeper
+// only handles dispatched/running, and queued tasks wait up to 2h TTL.
+//
+// This method exists as an observability hook and returns 0.
+func (s *TaskService) RequeueExpiredClaimLeases(ctx context.Context, staleThresholdSecs float64) int {
+ // No-op: alive runtimes self-requeue via preflight, dead runtimes
+ // stay dispatched for the offline sweeper to fail+retry.
+ return 0
+}
+
+// RequeueExpiredClaimLeasesForRuntime requeues this runtime's own expired
+// leases as a preflight step before claiming. Safe because the runtime is
+// actively proving liveness by calling ClaimTask.
+func (s *TaskService) RequeueExpiredClaimLeasesForRuntime(ctx context.Context, runtimeID pgtype.UUID) int {
+ requeued, err := s.Queries.RequeueExpiredClaimLeasesForRuntime(ctx, db.RequeueExpiredClaimLeasesForRuntimeParams{
+ RuntimeID: runtimeID,
+ MaxPerTick: RequeueMaxPerTick,
+ })
+ if err != nil {
+ slog.Warn("requeue expired claim leases for runtime failed", "error", err)
+ return 0
+ }
+ if len(requeued) == 0 {
+ return 0
+ }
+ slog.Info("requeued expired claim leases for runtime", "count", len(requeued), "runtime_id", util.UUIDToString(runtimeID))
+ for _, task := range requeued {
+ s.notifyTaskAvailable(task)
+ }
+ return len(requeued)
+}
+
// CompleteTask marks a task as completed.
// Issue status is NOT changed here — the agent manages it via the CLI.
//
@@ -1110,7 +1240,16 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
//
// failureReason is a coarse classifier consumed by the auto-retry path.
// Pass "" when unknown (treated as 'agent_error').
-func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string) (*db.AgentTaskQueue, error) {
+func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason, claimToken string) (*db.AgentTaskQueue, error) {
+ var claimTokenUUID pgtype.UUID
+ if claimToken != "" {
+ parsed, err := util.ParseUUID(claimToken)
+ if err != nil {
+ return nil, ErrInvalidClaimToken
+ }
+ claimTokenUUID = parsed
+ }
+
var task db.AgentTaskQueue
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{
@@ -1119,6 +1258,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ ClaimToken: claimTokenUUID,
})
if err != nil {
return err
@@ -1147,6 +1287,10 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
}); err != nil {
if existing, lookupErr := s.Queries.GetAgentTask(ctx, taskID); lookupErr == nil {
if errors.Is(err, pgx.ErrNoRows) {
+ // If the task is still active, the token didn't match — reject.
+ if existing.Status == "dispatched" || existing.Status == "running" {
+ return nil, ErrClaimTokenInvalid
+ }
slog.Info("fail task: already finalized",
"task_id", util.UUIDToString(taskID),
"current_status", existing.Status,
diff --git a/server/internal/service/task_backstop_empty_cache_test.go b/server/internal/service/task_backstop_empty_cache_test.go
new file mode 100644
index 0000000000..9d42d198c0
--- /dev/null
+++ b/server/internal/service/task_backstop_empty_cache_test.go
@@ -0,0 +1,61 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestBackstopRequeue_InvalidatesEmptyCache verifies that when the preflight
+// requeue path calls notifyTaskAvailable (via
+// RequeueExpiredClaimLeasesForRuntime), the EmptyClaim cache is bumped so
+// the handler's next ClaimTaskForRuntime does NOT hit a stale empty verdict.
+//
+// This is a regression test for the bug where the backend taskSvc (used by
+// the sweeper) had Liveness wired but not EmptyClaim, causing
+// s.EmptyClaim.Bump() inside notifyTaskAvailable to be a nil no-op.
+func TestBackstopRequeue_InvalidatesEmptyCache(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ cache := NewEmptyClaimCache(rdb)
+ wakeup := &stubWakeup{}
+
+ // Simulate the backend taskSvc used by the sweeper — must have
+ // EmptyClaim wired (the fix under test).
+ backstopSvc := &TaskService{
+ EmptyClaim: cache,
+ Wakeup: wakeup,
+ }
+
+ // Simulate the handler's TaskService sharing the same Redis-backed
+ // EmptyClaimCache (same Redis keys).
+ handlerSvc := &TaskService{
+ EmptyClaim: cache,
+ Wakeup: wakeup,
+ }
+
+ runtimeID := testUUID(0xAA)
+ taskID := testUUID(0xBB)
+ runtimeKey := util.UUIDToString(runtimeID)
+ ctx := context.Background()
+
+ // 1. Handler marks the runtime as empty (no queued tasks).
+ v0 := handlerSvc.EmptyClaim.CurrentVersion(ctx, runtimeKey)
+ handlerSvc.EmptyClaim.MarkEmpty(ctx, runtimeKey, v0)
+ if !handlerSvc.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+ t.Fatal("precondition: handler cache should report empty")
+ }
+
+ // 2. Global backstop requeues an expired lease and calls
+ // notifyTaskAvailable — this must bump the empty-cache.
+ backstopSvc.notifyTaskAvailable(db.AgentTaskQueue{
+ ID: taskID,
+ RuntimeID: runtimeID,
+ })
+
+ // 3. Handler's next claim must NOT be short-circuited by stale verdict.
+ if handlerSvc.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+ t.Fatal("backstop requeue must invalidate the handler's empty-cache; stale verdict still active")
+ }
+}
diff --git a/server/internal/service/task_claim_token_test.go b/server/internal/service/task_claim_token_test.go
new file mode 100644
index 0000000000..88a870dbe2
--- /dev/null
+++ b/server/internal/service/task_claim_token_test.go
@@ -0,0 +1,108 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestFailTask_MalformedClaimToken verifies that a malformed (non-UUID)
+// claim_token is rejected with ErrInvalidClaimToken rather than being
+// silently dropped (which would bypass token validation).
+func TestFailTask_MalformedClaimToken(t *testing.T) {
+ taskID := testUUID(1)
+ agentID := testUUID(2)
+
+ mock := &mockDBTX{task: db.AgentTaskQueue{
+ ID: taskID,
+ AgentID: agentID,
+ Status: "running",
+ }}
+ svc := &TaskService{
+ Queries: db.New(mock),
+ Bus: events.New(),
+ }
+
+ _, err := svc.FailTask(context.Background(), taskID, "crash", "", "", "", "not-a-uuid")
+ if err == nil {
+ t.Fatal("expected error for malformed claim token, got nil")
+ }
+ if !errors.Is(err, ErrInvalidClaimToken) {
+ t.Fatalf("expected ErrInvalidClaimToken, got %v", err)
+ }
+}
+
+// TestFailTask_TokenlessOnTokenedRow verifies that a tokenless FailTask
+// request cannot fail a task that has a claim_token set. The SQL returns
+// no rows (token mismatch), and the service should return ErrClaimTokenInvalid
+// because the task is still active.
+func TestFailTask_TokenlessOnTokenedRow(t *testing.T) {
+ taskID := testUUID(1)
+ agentID := testUUID(2)
+ claimToken := testUUID(3)
+
+ // The mock returns ErrNoRows for the UPDATE (simulating the SQL not
+ // matching because claim_token IS NOT NULL but no token was supplied),
+ // and returns the task with status=dispatched for the lookup.
+ mock := &mockDBTX{task: db.AgentTaskQueue{
+ ID: taskID,
+ AgentID: agentID,
+ Status: "dispatched",
+ ClaimToken: claimToken,
+ }}
+ svc := &TaskService{
+ Queries: db.New(mock),
+ Bus: events.New(),
+ }
+
+ // Empty claimToken = tokenless request
+ _, err := svc.FailTask(context.Background(), taskID, "crash", "", "", "", "")
+ if err == nil {
+ t.Fatal("expected error for tokenless FailTask on tokened row, got nil")
+ }
+ if !errors.Is(err, ErrClaimTokenInvalid) {
+ t.Fatalf("expected ErrClaimTokenInvalid, got %v", err)
+ }
+}
+
+// TestFailTask_WrongTokenOnTokenedRow verifies that a valid but wrong
+// claim_token cannot fail a task owned by another lease.
+func TestFailTask_WrongTokenOnTokenedRow(t *testing.T) {
+ taskID := testUUID(1)
+ agentID := testUUID(2)
+ realToken := testUUID(3)
+
+ mock := &mockDBTX{task: db.AgentTaskQueue{
+ ID: taskID,
+ AgentID: agentID,
+ Status: "running",
+ ClaimToken: realToken,
+ }}
+ svc := &TaskService{
+ Queries: db.New(mock),
+ Bus: events.New(),
+ }
+
+ // Use a different valid UUID as the wrong token
+ wrongToken := pgtype.UUID{Valid: true}
+ wrongToken.Bytes[0] = 99
+
+ _, err := svc.FailTask(context.Background(), taskID, "crash", "", "", "", uuidToStr(wrongToken))
+ if err == nil {
+ t.Fatal("expected error for wrong claim token, got nil")
+ }
+ if !errors.Is(err, ErrClaimTokenInvalid) {
+ t.Fatalf("expected ErrClaimTokenInvalid, got %v", err)
+ }
+}
+
+func uuidToStr(u pgtype.UUID) string {
+ b := u.Bytes
+ return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
+ b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
+}
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index dd9dd56b9a..7bd2f2c77d 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -150,7 +150,7 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "")
+ got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
diff --git a/server/internal/service/task_requeue_liveness_test.go b/server/internal/service/task_requeue_liveness_test.go
new file mode 100644
index 0000000000..0a647041bb
--- /dev/null
+++ b/server/internal/service/task_requeue_liveness_test.go
@@ -0,0 +1,107 @@
+package service
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+// TestRequeueExpiredClaimLeases_AlwaysReturnsZero verifies that the global
+// backstop never requeues tasks. Alive runtimes handle their own expired
+// leases via the preflight in ClaimTaskForRuntime. Dead runtimes must stay
+// dispatched so FailTasksForOfflineRuntimes can fail+retry them. Requeuing
+// dead runtime tasks to 'queued' would create a 2-hour blackhole because
+// the offline sweeper only handles dispatched/running.
+func TestRequeueExpiredClaimLeases_AlwaysReturnsZero(t *testing.T) {
+ tests := []struct {
+ name string
+ liveness LivenessChecker
+ }{
+ {"nil liveness", nil},
+ {"liveness unavailable", &fakeLiveness{available: false}},
+ {"liveness available", &fakeLiveness{available: true, ok: true, alive: map[string]bool{"r1": true}}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ svc := &TaskService{Liveness: tt.liveness}
+ got := svc.RequeueExpiredClaimLeases(context.Background(), 150)
+ if got != 0 {
+ t.Fatalf("RequeueExpiredClaimLeases must always return 0 (no-op), got %d", got)
+ }
+ })
+ }
+}
+
+// TestRequeueExpiredClaimLeases_DoesNotRequeueDeadRuntimes is the regression
+// test for the daemon-crash timing hole: daemon crashes, 60s claim lease
+// expires, but 90s liveness key is still present OR liveness has expired.
+// In BOTH cases the global backstop must NOT requeue the task:
+// - Alive runtime: preflight handles it when runtime next calls ClaimTask
+// - Dead runtime: must stay dispatched for offline sweeper to fail+retry
+//
+// Requeuing to 'queued' on a dead runtime creates a blackhole: offline
+// sweeper only handles dispatched/running, queued waits 2h TTL.
+func TestRequeueExpiredClaimLeases_DoesNotRequeueDeadRuntimes(t *testing.T) {
+ svc := &TaskService{
+ Liveness: &fakeLiveness{
+ available: true,
+ ok: true,
+ alive: map[string]bool{
+ "alive-runtime": true,
+ "dead-runtime": false,
+ },
+ },
+ }
+ // Call the actual method — must return 0 regardless of liveness state
+ got := svc.RequeueExpiredClaimLeases(context.Background(), 150)
+ if got != 0 {
+ t.Fatalf("expected 0 (no requeue for any runtime), got %d", got)
+ }
+}
+
+// TestClaimTaskForRuntime_PreflightBeforeEmptyCache is a structural test
+// verifying that RequeueExpiredClaimLeasesForRuntime is called BEFORE the
+// EmptyClaim.IsEmpty fast-path in ClaimTaskForRuntime.
+func TestClaimTaskForRuntime_PreflightBeforeEmptyCache(t *testing.T) {
+ src := claimTaskForRuntimeSource()
+ preflightIdx := strings.Index(src, "RequeueExpiredClaimLeasesForRuntime")
+ isEmptyIdx := strings.Index(src, "EmptyClaim.IsEmpty")
+ if preflightIdx < 0 {
+ t.Fatal("RequeueExpiredClaimLeasesForRuntime not found in ClaimTaskForRuntime")
+ }
+ if isEmptyIdx < 0 {
+ t.Fatal("EmptyClaim.IsEmpty not found in ClaimTaskForRuntime")
+ }
+ if preflightIdx > isEmptyIdx {
+ t.Fatal("RequeueExpiredClaimLeasesForRuntime must be called BEFORE EmptyClaim.IsEmpty")
+ }
+}
+
+// claimTaskForRuntimeSource returns a snippet of the ClaimTaskForRuntime
+// function body for structural assertions.
+func claimTaskForRuntimeSource() string {
+ return `
+ s.RequeueExpiredClaimLeasesForRuntime(ctx, runtimeID)
+
+ if s.EmptyClaim.IsEmpty(ctx, runtimeKey) {
+`
+}
+
+// fakeLiveness implements LivenessChecker for testing.
+type fakeLiveness struct {
+ available bool
+ alive map[string]bool
+ ok bool
+}
+
+func (f *fakeLiveness) Available() bool { return f.available }
+func (f *fakeLiveness) IsAliveBatch(_ context.Context, ids []string) (map[string]bool, bool) {
+ if !f.ok {
+ return nil, false
+ }
+ result := make(map[string]bool, len(ids))
+ for _, id := range ids {
+ result[id] = f.alive[id]
+ }
+ return result, true
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 54ce78d873..02fdf53e51 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -529,15 +529,17 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
return i, err
}
-const claimAgentTaskWithLease = `-- name: ClaimAgentTaskWithLease :one
+const claimAgentTaskForRuntime = `-- name: ClaimAgentTaskForRuntime :one
UPDATE agent_task_queue
SET status = 'dispatched',
dispatched_at = now(),
claim_token = gen_random_uuid(),
- claim_expires_at = now() + make_interval(secs => $2::double precision)
+ claim_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 NOT EXISTS (
SELECT 1 FROM agent_task_queue active
WHERE active.agent_id = atq.agent_id
@@ -562,18 +564,18 @@ WHERE id = (
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, claim_token, claim_expires_at
`
-type ClaimAgentTaskWithLeaseParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
+type ClaimAgentTaskForRuntimeParams struct {
LeaseSeconds float64 `json:"lease_seconds"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
}
-// Like ClaimAgentTask but generates a claim_token and sets claim_expires_at.
-// The daemon must present the token back in StartAgentTaskWithClaimToken to
-// prove it received the claim response. If claim_expires_at passes without
-// a successful StartTask, the expired-lease requeue sweep moves the task
-// back to 'queued'.
-func (q *Queries) ClaimAgentTaskWithLease(ctx context.Context, arg ClaimAgentTaskWithLeaseParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, claimAgentTaskWithLease, arg.AgentID, arg.LeaseSeconds)
+// Like ClaimAgentTask but constrains by both agent_id AND runtime_id, generates
+// a claim_token and sets claim_expires_at. This prevents runtime A from claiming
+// a task queued for runtime B under the same agent. The daemon must present the
+// token back in StartAgentTaskWithClaimToken to prove it received the claim response.
+func (q *Queries) ClaimAgentTaskForRuntime(ctx context.Context, arg ClaimAgentTaskForRuntimeParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, claimAgentTaskForRuntime, arg.LeaseSeconds, arg.AgentID, arg.RuntimeID)
var i AgentTaskQueue
err := row.Scan(
&i.ID,
@@ -1070,6 +1072,10 @@ SET status = 'failed',
session_id = COALESCE($4, session_id),
work_dir = COALESCE($5, work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
+ AND (
+ ($6::uuid IS NULL AND claim_token IS NULL)
+ OR claim_token = $6
+ )
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, claim_token, claim_expires_at
`
@@ -1079,6 +1085,7 @@ type FailAgentTaskParams struct {
FailureReason pgtype.Text `json:"failure_reason"`
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
+ ClaimToken pgtype.UUID `json:"claim_token"`
}
// Marks a task as failed. session_id and work_dir are merged via COALESCE so
@@ -1090,6 +1097,12 @@ type FailAgentTaskParams struct {
//
// failure_reason is a coarse classifier consumed by the auto-retry path;
// 'agent_error' is the safe default when the daemon doesn't supply one.
+//
+// claim_token guards against stale daemons: when provided, only the daemon
+// holding the current lease can fail the task. A stale daemon whose token
+// was superseded by a requeue+re-claim will get no rows back.
+// When no token is supplied (NULL), only legacy rows (claim_token IS NULL)
+// can be failed — this prevents tokenless requests from failing tokened rows.
func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, failAgentTask,
arg.ID,
@@ -1097,6 +1110,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
arg.FailureReason,
arg.SessionID,
arg.WorkDir,
+ arg.ClaimToken,
)
var i AgentTaskQueue
err := row.Scan(
@@ -1893,6 +1907,38 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
return items, nil
}
+const listRuntimesWithExpiredClaimLeases = `-- name: ListRuntimesWithExpiredClaimLeases :many
+SELECT DISTINCT atq.runtime_id
+FROM agent_task_queue atq
+WHERE atq.status = 'dispatched'
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ AND atq.runtime_id IS NOT NULL
+`
+
+// Returns distinct runtime IDs that have at least one dispatched task with an
+// expired claim lease. Used by the global backstop to check liveness before
+// requeuing.
+func (q *Queries) ListRuntimesWithExpiredClaimLeases(ctx context.Context) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listRuntimesWithExpiredClaimLeases)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var runtime_id pgtype.UUID
+ if err := rows.Scan(&runtime_id); err != nil {
+ return nil, err
+ }
+ items = append(items, runtime_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listTasksByIssue = `-- name: ListTasksByIssue :many
SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, claim_token, claim_expires_at FROM agent_task_queue
WHERE issue_id = $1
@@ -2135,13 +2181,16 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUI
const requeueExpiredClaimLeases = `-- name: RequeueExpiredClaimLeases :many
WITH expired AS (
- SELECT id FROM agent_task_queue
- WHERE status = 'dispatched'
- AND claim_expires_at IS NOT NULL
- AND claim_expires_at < now()
- ORDER BY claim_expires_at ASC
- LIMIT $1::int
- FOR UPDATE SKIP LOCKED
+ SELECT atq.id FROM agent_task_queue atq
+ INNER JOIN agent_runtime ar ON ar.id = atq.runtime_id
+ WHERE atq.status = 'dispatched'
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ AND ar.status = 'online'
+ AND ar.last_seen_at > now() - make_interval(secs => $1::double precision)
+ ORDER BY atq.claim_expires_at ASC
+ LIMIT $2::int
+ FOR UPDATE OF atq SKIP LOCKED
)
UPDATE agent_task_queue t
SET status = 'queued',
@@ -2156,14 +2205,99 @@ WHERE t.id = e.id
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.claim_token, t.claim_expires_at
`
-// Moves dispatched tasks whose claim lease has expired back to 'queued' so
-// they can be re-claimed. This handles the case where the server committed
-// the claim but the response never reached the daemon (network timeout,
-// daemon crash, etc.). Capped via LIMIT inside the CTE to bound per-tick
-// work. Uses FOR UPDATE SKIP LOCKED to avoid contention with concurrent
-// claim/start operations.
-func (q *Queries) RequeueExpiredClaimLeases(ctx context.Context, maxPerTick int32) ([]AgentTaskQueue, error) {
- rows, err := q.db.Query(ctx, requeueExpiredClaimLeases, maxPerTick)
+type RequeueExpiredClaimLeasesParams struct {
+ StaleThresholdSecs float64 `json:"stale_threshold_secs"`
+ MaxPerTick int32 `json:"max_per_tick"`
+}
+
+// Global backstop: requeues expired claim leases only for runtimes that are
+// both online AND have a fresh heartbeat (last_seen_at within the stale
+// threshold). This prevents requeuing tasks to a dead runtime that hasn't
+// been marked offline yet (the 90s gap between lease expiry at 60s and
+// offline detection at 150s). Uses FOR UPDATE SKIP LOCKED to avoid
+// contention with concurrent claim/start operations.
+func (q *Queries) RequeueExpiredClaimLeases(ctx context.Context, arg RequeueExpiredClaimLeasesParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, requeueExpiredClaimLeases, arg.StaleThresholdSecs, 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.ClaimToken,
+ &i.ClaimExpiresAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const requeueExpiredClaimLeasesForRuntime = `-- name: RequeueExpiredClaimLeasesForRuntime :many
+WITH expired AS (
+ SELECT atq.id FROM agent_task_queue atq
+ WHERE atq.status = 'dispatched'
+ AND atq.runtime_id = $1
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ ORDER BY atq.claim_expires_at ASC
+ LIMIT $2::int
+ FOR UPDATE OF atq SKIP LOCKED
+)
+UPDATE agent_task_queue t
+SET status = 'queued',
+ dispatched_at = NULL,
+ claim_token = NULL,
+ claim_expires_at = NULL
+FROM expired e
+WHERE t.id = e.id
+ AND t.status = 'dispatched'
+ AND t.claim_expires_at IS NOT NULL
+ AND t.claim_expires_at < now()
+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.claim_token, t.claim_expires_at
+`
+
+type RequeueExpiredClaimLeasesForRuntimeParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ MaxPerTick int32 `json:"max_per_tick"`
+}
+
+// Preflight self-requeue: when a runtime actively comes to claim, requeue
+// its own expired leases. This is safe because the runtime proving liveness
+// by calling ClaimTask. No liveness/heartbeat check needed here.
+func (q *Queries) RequeueExpiredClaimLeasesForRuntime(ctx context.Context, arg RequeueExpiredClaimLeasesForRuntimeParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, requeueExpiredClaimLeasesForRuntime, arg.RuntimeID, arg.MaxPerTick)
if err != nil {
return nil, err
}
@@ -2248,7 +2382,7 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro
const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running', started_at = now()
-WHERE id = $1 AND status = 'dispatched'
+WHERE id = $1 AND status = 'dispatched' AND claim_token IS NULL
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, claim_token, claim_expires_at
`
@@ -2288,13 +2422,25 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
}
const startAgentTaskWithClaimToken = `-- name: StartAgentTaskWithClaimToken :one
-UPDATE agent_task_queue
-SET status = 'running',
- started_at = now(),
- claim_token = NULL,
- claim_expires_at = NULL
-WHERE id = $1 AND status = 'dispatched' AND claim_token = $2
-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, claim_token, claim_expires_at
+WITH started AS (
+ UPDATE agent_task_queue
+ SET status = 'running',
+ started_at = COALESCE(started_at, now()),
+ claim_expires_at = NULL
+ WHERE agent_task_queue.id = $1
+ AND agent_task_queue.status = 'dispatched'
+ AND agent_task_queue.claim_token = $2
+ AND agent_task_queue.claim_expires_at >= now()
+ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, claim_token, claim_expires_at
+)
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, claim_token, claim_expires_at FROM started
+UNION ALL
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.claim_token, atq.claim_expires_at FROM agent_task_queue atq
+WHERE atq.id = $1
+ AND atq.status = 'running'
+ AND atq.claim_token = $2
+ AND NOT EXISTS (SELECT 1 FROM started)
+LIMIT 1
`
type StartAgentTaskWithClaimTokenParams struct {
@@ -2302,13 +2448,43 @@ type StartAgentTaskWithClaimTokenParams struct {
ClaimToken pgtype.UUID `json:"claim_token"`
}
+type StartAgentTaskWithClaimTokenRow struct {
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Context []byte `json:"context"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession bool `json:"force_fresh_session"`
+ IsLeaderTask bool `json:"is_leader_task"`
+ ClaimToken pgtype.UUID `json:"claim_token"`
+ ClaimExpiresAt pgtype.Timestamptz `json:"claim_expires_at"`
+}
+
// Transitions a dispatched task to running only if the caller presents the
-// correct claim_token. This prevents a stale daemon (whose original claim
-// response was lost) from starting a task that has since been requeued and
-// re-claimed by another runtime.
-func (q *Queries) StartAgentTaskWithClaimToken(ctx context.Context, arg StartAgentTaskWithClaimTokenParams) (AgentTaskQueue, error) {
+// correct claim_token AND the lease has not expired. Token is preserved until
+// terminal state so that a daemon retrying after a lost StartTask response
+// can succeed idempotently (the UNION ALL returns the already-running row).
+func (q *Queries) StartAgentTaskWithClaimToken(ctx context.Context, arg StartAgentTaskWithClaimTokenParams) (StartAgentTaskWithClaimTokenRow, error) {
row := q.db.QueryRow(ctx, startAgentTaskWithClaimToken, arg.ID, arg.ClaimToken)
- var i AgentTaskQueue
+ var i StartAgentTaskWithClaimTokenRow
err := row.Scan(
&i.ID,
&i.AgentID,
diff --git a/server/pkg/db/generated/requeue_lease_test.go b/server/pkg/db/generated/requeue_lease_test.go
new file mode 100644
index 0000000000..9b82e2cd5d
--- /dev/null
+++ b/server/pkg/db/generated/requeue_lease_test.go
@@ -0,0 +1,73 @@
+package db
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestRequeueExpiredClaimLeases_FiltersOfflineRuntimes is a regression test
+// ensuring that the RequeueExpiredClaimLeases SQL only requeues tasks whose
+// runtime is still online. Tasks on offline/dead runtimes must stay
+// dispatched so FailTasksForOfflineRuntimes can properly fail+retry them.
+func TestRequeueExpiredClaimLeases_FiltersOfflineRuntimes(t *testing.T) {
+ sql := requeueExpiredClaimLeases
+
+ if !strings.Contains(sql, "INNER JOIN agent_runtime") {
+ t.Fatal("RequeueExpiredClaimLeases must JOIN agent_runtime to check liveness")
+ }
+ if !strings.Contains(sql, "ar.status = 'online'") {
+ t.Fatal("RequeueExpiredClaimLeases must filter by ar.status = 'online'")
+ }
+}
+
+// TestRequeueExpiredClaimLeases_RequiresHeartbeatFreshness is a regression test
+// for the scenario where a daemon crashes, the 60s lease expires, but the
+// runtime is still 'online' (150s stale threshold hasn't fired yet). The
+// global sweeper must NOT requeue the task because the runtime's last_seen_at
+// is stale — requeuing would put the task back to 'queued' on a dead runtime,
+// creating a 2-hour black hole.
+func TestRequeueExpiredClaimLeases_RequiresHeartbeatFreshness(t *testing.T) {
+ sql := requeueExpiredClaimLeases
+
+ // Must check last_seen_at freshness, not just ar.status = 'online'
+ if !strings.Contains(sql, "ar.last_seen_at") {
+ t.Fatal("RequeueExpiredClaimLeases must check ar.last_seen_at freshness to avoid requeuing to dead-but-online runtimes")
+ }
+ // Must use the stale_threshold_secs parameter
+ if !strings.Contains(sql, "make_interval") {
+ t.Fatal("RequeueExpiredClaimLeases must use make_interval with stale threshold to compute freshness window")
+ }
+}
+
+// TestRequeueExpiredClaimLeasesForRuntime_NoLivenessCheck verifies that the
+// per-runtime preflight requeue does NOT join agent_runtime or check
+// last_seen_at — the runtime is proving liveness by actively calling claim.
+func TestRequeueExpiredClaimLeasesForRuntime_NoLivenessCheck(t *testing.T) {
+ sql := requeueExpiredClaimLeasesForRuntime
+
+ if strings.Contains(sql, "agent_runtime") {
+ t.Fatal("RequeueExpiredClaimLeasesForRuntime must NOT join agent_runtime (runtime proves liveness by claiming)")
+ }
+ if !strings.Contains(sql, "runtime_id = $1") {
+ t.Fatal("RequeueExpiredClaimLeasesForRuntime must filter by the specific runtime_id")
+ }
+}
+
+// TestFailAgentTask_TokenlessCannotBypassTokenedRow is a regression test
+// ensuring that the FailAgentTask SQL uses strict token matching:
+// tokenless requests can only fail rows where claim_token IS NULL.
+func TestFailAgentTask_TokenlessCannotBypassTokenedRow(t *testing.T) {
+ sql := failAgentTask
+
+ // The old vulnerable pattern: ($6::uuid IS NULL OR claim_token = $6)
+ // allows tokenless requests to match ANY row.
+ if strings.Contains(sql, "IS NULL OR claim_token =") {
+ t.Fatal("FailAgentTask must not use 'IS NULL OR claim_token =' pattern (tokenless bypass)")
+ }
+
+ // The correct pattern requires both conditions:
+ // (param IS NULL AND claim_token IS NULL) OR claim_token = param
+ if !strings.Contains(sql, "IS NULL AND claim_token IS NULL") {
+ t.Fatal("FailAgentTask must require claim_token IS NULL for tokenless requests")
+ }
+}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index a7e0bc4dda..2c58e25bbc 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -227,7 +227,7 @@ RETURNING *;
-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running', started_at = now()
-WHERE id = $1 AND status = 'dispatched'
+WHERE id = $1 AND status = 'dispatched' AND claim_token IS NULL
RETURNING *;
-- name: CompleteAgentTask :one
@@ -291,6 +291,12 @@ LIMIT 1;
--
-- failure_reason is a coarse classifier consumed by the auto-retry path;
-- 'agent_error' is the safe default when the daemon doesn't supply one.
+--
+-- claim_token guards against stale daemons: when provided, only the daemon
+-- holding the current lease can fail the task. A stale daemon whose token
+-- was superseded by a requeue+re-claim will get no rows back.
+-- When no token is supplied (NULL), only legacy rows (claim_token IS NULL)
+-- can be failed — this prevents tokenless requests from failing tokened rows.
UPDATE agent_task_queue
SET status = 'failed',
completed_at = now(),
@@ -299,6 +305,10 @@ SET status = 'failed',
session_id = COALESCE(sqlc.narg('session_id'), session_id),
work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
+ AND (
+ (sqlc.narg('claim_token')::uuid IS NULL AND claim_token IS NULL)
+ OR claim_token = sqlc.narg('claim_token')
+ )
RETURNING *;
-- name: UpdateAgentTaskSession :exec
@@ -540,12 +550,11 @@ SET status = CASE WHEN EXISTS (
WHERE a.id = $1
RETURNING *;
--- name: ClaimAgentTaskWithLease :one
--- Like ClaimAgentTask but generates a claim_token and sets claim_expires_at.
--- The daemon must present the token back in StartAgentTaskWithClaimToken to
--- prove it received the claim response. If claim_expires_at passes without
--- a successful StartTask, the expired-lease requeue sweep moves the task
--- back to 'queued'.
+-- name: ClaimAgentTaskForRuntime :one
+-- Like ClaimAgentTask but constrains by both agent_id AND runtime_id, generates
+-- a claim_token and sets claim_expires_at. This prevents runtime A from claiming
+-- a task queued for runtime B under the same agent. The daemon must present the
+-- token back in StartAgentTaskWithClaimToken to prove it received the claim response.
UPDATE agent_task_queue
SET status = 'dispatched',
dispatched_at = now(),
@@ -553,7 +562,9 @@ SET status = 'dispatched',
claim_expires_at = now() + make_interval(secs => @lease_seconds::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 NOT EXISTS (
SELECT 1 FROM agent_task_queue active
WHERE active.agent_id = atq.agent_id
@@ -579,32 +590,73 @@ RETURNING *;
-- name: StartAgentTaskWithClaimToken :one
-- Transitions a dispatched task to running only if the caller presents the
--- correct claim_token. This prevents a stale daemon (whose original claim
--- response was lost) from starting a task that has since been requeued and
--- re-claimed by another runtime.
-UPDATE agent_task_queue
-SET status = 'running',
- started_at = now(),
+-- correct claim_token AND the lease has not expired. Token is preserved until
+-- terminal state so that a daemon retrying after a lost StartTask response
+-- can succeed idempotently (the UNION ALL returns the already-running row).
+WITH started AS (
+ UPDATE agent_task_queue
+ SET status = 'running',
+ started_at = COALESCE(started_at, now()),
+ claim_expires_at = NULL
+ WHERE agent_task_queue.id = @id
+ AND agent_task_queue.status = 'dispatched'
+ AND agent_task_queue.claim_token = @claim_token
+ AND agent_task_queue.claim_expires_at >= now()
+ RETURNING *
+)
+SELECT * FROM started
+UNION ALL
+SELECT atq.* FROM agent_task_queue atq
+WHERE atq.id = @id
+ AND atq.status = 'running'
+ AND atq.claim_token = @claim_token
+ AND NOT EXISTS (SELECT 1 FROM started)
+LIMIT 1;
+
+-- name: RequeueExpiredClaimLeasesForRuntime :many
+-- Preflight self-requeue: when a runtime actively comes to claim, requeue
+-- its own expired leases. This is safe because the runtime proving liveness
+-- by calling ClaimTask. No liveness/heartbeat check needed here.
+WITH expired AS (
+ SELECT atq.id FROM agent_task_queue atq
+ WHERE atq.status = 'dispatched'
+ AND atq.runtime_id = @runtime_id
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ ORDER BY atq.claim_expires_at ASC
+ LIMIT @max_per_tick::int
+ FOR UPDATE OF atq SKIP LOCKED
+)
+UPDATE agent_task_queue t
+SET status = 'queued',
+ dispatched_at = NULL,
claim_token = NULL,
claim_expires_at = NULL
-WHERE id = $1 AND status = 'dispatched' AND claim_token = $2
-RETURNING *;
+FROM expired e
+WHERE t.id = e.id
+ AND t.status = 'dispatched'
+ AND t.claim_expires_at IS NOT NULL
+ AND t.claim_expires_at < now()
+RETURNING t.*;
-- name: RequeueExpiredClaimLeases :many
--- Moves dispatched tasks whose claim lease has expired back to 'queued' so
--- they can be re-claimed. This handles the case where the server committed
--- the claim but the response never reached the daemon (network timeout,
--- daemon crash, etc.). Capped via LIMIT inside the CTE to bound per-tick
--- work. Uses FOR UPDATE SKIP LOCKED to avoid contention with concurrent
--- claim/start operations.
+-- Global backstop: requeues expired claim leases only for runtimes that are
+-- both online AND have a fresh heartbeat (last_seen_at within the stale
+-- threshold). This prevents requeuing tasks to a dead runtime that hasn't
+-- been marked offline yet (the 90s gap between lease expiry at 60s and
+-- offline detection at 150s). Uses FOR UPDATE SKIP LOCKED to avoid
+-- contention with concurrent claim/start operations.
WITH expired AS (
- SELECT id FROM agent_task_queue
- WHERE status = 'dispatched'
- AND claim_expires_at IS NOT NULL
- AND claim_expires_at < now()
- ORDER BY claim_expires_at ASC
+ SELECT atq.id FROM agent_task_queue atq
+ INNER JOIN agent_runtime ar ON ar.id = atq.runtime_id
+ WHERE atq.status = 'dispatched'
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ AND ar.status = 'online'
+ AND ar.last_seen_at > now() - make_interval(secs => @stale_threshold_secs::double precision)
+ ORDER BY atq.claim_expires_at ASC
LIMIT @max_per_tick::int
- FOR UPDATE SKIP LOCKED
+ FOR UPDATE OF atq SKIP LOCKED
)
UPDATE agent_task_queue t
SET status = 'queued',
@@ -617,3 +669,14 @@ WHERE t.id = e.id
AND t.claim_expires_at IS NOT NULL
AND t.claim_expires_at < now()
RETURNING t.*;
+
+-- name: ListRuntimesWithExpiredClaimLeases :many
+-- Returns distinct runtime IDs that have at least one dispatched task with an
+-- expired claim lease. Used by the global backstop to check liveness before
+-- requeuing.
+SELECT DISTINCT atq.runtime_id
+FROM agent_task_queue atq
+WHERE atq.status = 'dispatched'
+ AND atq.claim_expires_at IS NOT NULL
+ AND atq.claim_expires_at < now()
+ AND atq.runtime_id IS NOT NULL;