Skip to content

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

Go

MUL-7351: fix(daemon): fence and retry task start acknowledgements (LANX-3) (#8400)

hutiefang761879bc35e344
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 3e770fcef1..c339edb5d6 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -434,8 +434,38 @@ func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID s
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/prepare-lease", runtimeID, taskID), map[string]any{}, 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)
+// startTaskRetrySchedule allows two short reconnects without the terminal
+// callbacks' 124s backoff. The whole start has a 30s budget (not 3 x the HTTP
+// client's 30s timeout). Preparation keeps renewing its 45s lease every 15s
+// throughout requests and backoff; its own deadline can end this sooner.
+// runTask calls this once. Task-level retries are separate executions, with
+// fresh claims, and cannot reuse this acknowledgement.
+var startTaskRetrySchedule = []time.Duration{500 * time.Millisecond, 2 * time.Second}
+
+const startTaskTimeout = 30 * time.Second
+
+var errStartClaimRejected = errors.New("task start claim rejected")
+
+func (c *Client) StartTask(ctx context.Context, task Task) error {
+ path := fmt.Sprintf("/api/daemon/tasks/%s/start", task.ID)
+ if !task.StartClaimSupported {
+ // Old servers have no safe replay contract. Preserve one attempt.
+ return c.postJSON(ctx, path, map[string]any{}, nil)
+ }
+ if task.RuntimeID == "" || task.DispatchedAt == "" {
+ return fmt.Errorf("start task: claim is missing runtime_id or dispatched_at")
+ }
+ ctx, cancel := context.WithTimeout(ctx, startTaskTimeout)
+ defer cancel()
+ err := c.postJSONWithRetry(ctx, path, map[string]any{
+ "runtime_id": task.RuntimeID,
+ "dispatched_at": task.DispatchedAt,
+ }, nil, startTaskRetrySchedule)
+ var reqErr *requestError
+ if errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusConflict {
+ return fmt.Errorf("%w: %w", errStartClaimRejected, err)
+ }
+ return err
}
// MarkTaskWaitingLocalDirectory parks a freshly-dispatched task in the
diff --git a/server/internal/daemon/client_start_test.go b/server/internal/daemon/client_start_test.go
new file mode 100644
index 0000000000..66e147220c
--- /dev/null
+++ b/server/internal/daemon/client_start_test.go
@@ -0,0 +1,163 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type startTaskTransport func(*http.Request) (*http.Response, error)
+
+func (f startTaskTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestStartTaskRetries(t *testing.T) {
+ defer noSleepRetry(t)()
+ for _, tc := range []struct {
+ name string
+ failure error
+ status int
+ failures int
+ wantCalls int
+ wantError bool
+ }{
+ {name: "EOF", failure: io.EOF, failures: 1, wantCalls: 2},
+ {name: "unexpected EOF", failure: io.ErrUnexpectedEOF, failures: 2, wantCalls: 3},
+ {name: "gateway outage", status: http.StatusBadGateway, failures: 1, wantCalls: 2},
+ {name: "persistent outage", failure: io.ErrUnexpectedEOF, failures: 10, wantCalls: 3, wantError: true},
+ {name: "unauthorized", status: http.StatusUnauthorized, failures: 10, wantCalls: 1, wantError: true},
+ {name: "invalid task state", status: http.StatusBadRequest, failures: 10, wantCalls: 1, wantError: true},
+ {name: "stale claim", status: http.StatusConflict, failures: 10, wantCalls: 1, wantError: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ calls := 0
+ client := NewClient("https://daemon.test")
+ client.client.Transport = startTaskTransport(func(r *http.Request) (*http.Response, error) {
+ calls++
+ if r.Method != http.MethodPost || r.URL.Path != "/api/daemon/tasks/task-1/start" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
+ }
+ body, err := io.ReadAll(r.Body)
+ var claim map[string]string
+ if err != nil || json.Unmarshal(body, &claim) != nil || claim["runtime_id"] != "runtime-1" || claim["dispatched_at"] != "2026-09-17T09:00:00.123456Z" {
+ t.Fatalf("start body = %q, error = %v", body, err)
+ }
+ status := http.StatusOK
+ if calls <= tc.failures {
+ if tc.failure != nil {
+ return nil, tc.failure
+ }
+ status = tc.status
+ }
+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader("{}")), Header: make(http.Header)}, nil
+ })
+ err := client.StartTask(context.Background(), startTestClaim())
+ if tc.status == http.StatusConflict && !errors.Is(err, errStartClaimRejected) {
+ t.Fatalf("lost claim rejection: %v", err)
+ }
+ if (err != nil) != tc.wantError || calls != tc.wantCalls {
+ t.Fatalf("StartTask error = %v, calls = %d; want error = %v, calls = %d", err, calls, tc.wantError, tc.wantCalls)
+ }
+ })
+ }
+}
+
+func TestStartTaskCancellationStopsRetry(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ previous := retrySleep
+ t.Cleanup(func() { retrySleep = previous })
+ retrySleep = func(ctx context.Context, _ time.Duration) error {
+ cancel()
+ return ctx.Err()
+ }
+ calls := 0
+ client := NewClient("https://daemon.test")
+ client.client.Transport = startTaskTransport(func(*http.Request) (*http.Response, error) {
+ calls++
+ return nil, io.ErrUnexpectedEOF
+ })
+ err := client.StartTask(ctx, startTestClaim())
+ if err == nil || !errors.Is(ctx.Err(), context.Canceled) || calls != 1 {
+ t.Fatalf("error = %v, context = %v, calls = %d; want cancelled backoff and one attempt", err, ctx.Err(), calls)
+ }
+}
+
+func TestHandleTaskRejectedStartDoesNotFailNewOwner(t *testing.T) {
+ var callbacks atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/fail") || strings.HasSuffix(r.URL.Path, "/complete") || strings.HasSuffix(r.URL.Path, "/cancel-ack") {
+ callbacks.Add(1)
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer 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"}},
+ activeEnvRoots: make(map[string]int), cancelPollInterval: time.Hour,
+ cfg: Config{WorkspacesRoot: t.TempDir()},
+ }
+ var ran bool
+ d.runner = taskRunnerFunc(func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error) {
+ ran = true
+ return TaskResult{}, errStartClaimRejected
+ })
+ d.handleTask(context.Background(), Task{ID: "stale-task", WorkspaceID: "workspace", RuntimeID: "rt-1", Agent: &AgentData{Name: "test-agent"}}, 0)
+ if !ran || callbacks.Load() != 0 {
+ t.Fatalf("ran=%t terminal callbacks=%d", ran, callbacks.Load())
+ }
+}
+
+func startTestClaim() Task {
+ return Task{ID: "task-1", RuntimeID: "runtime-1", DispatchedAt: "2026-09-17T09:00:00.123456Z", StartClaimSupported: true}
+}
+
+func TestStartTaskLegacyServerDoesNotRetry(t *testing.T) {
+ calls := 0
+ client := NewClient("https://daemon.test")
+ client.client.Transport = startTaskTransport(func(r *http.Request) (*http.Response, error) {
+ calls++
+ body, _ := io.ReadAll(r.Body)
+ if string(body) != "{}" {
+ t.Fatalf("legacy body: %s", body)
+ }
+ return nil, io.ErrUnexpectedEOF
+ })
+ claim := startTestClaim()
+ claim.StartClaimSupported = false
+ if err := client.StartTask(context.Background(), claim); err == nil || calls != 1 {
+ t.Fatalf("legacy start: err=%v calls=%d", err, calls)
+ }
+}
+
+func TestStartTaskBudgetAndMissingClaim(t *testing.T) {
+ client := NewClient("https://daemon.test")
+ calls := 0
+ client.client.Transport = startTaskTransport(func(r *http.Request) (*http.Response, error) {
+ calls++
+ deadline, ok := r.Context().Deadline()
+ if !ok || time.Until(deadline) > startTaskTimeout {
+ t.Fatal("missing overall start budget")
+ }
+ <-r.Context().Done()
+ return nil, r.Context().Err()
+ })
+ claim := startTestClaim()
+ claim.DispatchedAt = ""
+ if err := client.StartTask(context.Background(), claim); err == nil || calls != 0 {
+ t.Fatalf("missing claim: %v, calls=%d", err, calls)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if err := client.StartTask(ctx, startTestClaim()); err == nil || calls != 1 {
+ t.Fatalf("deadline: %v, calls=%d", err, calls)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 30601888c3..afc31651e8 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5833,6 +5833,12 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
}()
result, err := d.runner.run(runCtx, task, provider, slot, taskLog)
+ if errors.Is(err, errStartClaimRejected) {
+ // The row belongs to another claim (or is terminal). A task-id-only
+ // failure callback from this stale delivery could kill its new owner.
+ taskLog.Info("discarding rejected start claim", "error", err)
+ return
+ }
// Report usage before any early return — the agent accumulates tokens
// whether the task completes, errors, or is cancelled mid-run by the poll
@@ -7662,7 +7668,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
prepareComplete := false
defer func() {
cancelPrepare()
- if prepareComplete || returnErr == nil || !errors.Is(context.Cause(prepareCtx), errTaskPrepareTimeout) {
+ if prepareComplete || returnErr == nil || errors.Is(returnErr, errStartClaimRejected) || !errors.Is(context.Cause(prepareCtx), errTaskPrepareTimeout) {
return
}
// Collapse every deadline shape (context deadline, HTTP cancellation,
@@ -8366,11 +8372,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// /multica_workspaces/{ws}/{short-id}/workdir hit FileNotFoundError in
// the microsecond window before os.MkdirAll ran.
//
- // On error we return early so handleTask's existing FailTask +
- // taskfailure.Classify path records the failure with the same
+ // On error we return early. A rejected claim is discarded by handleTask;
+ // other errors use its existing FailTask + taskfailure.Classify path with the same
// "start task failed: <…>" string and the same failure_reason
// taxonomy as before — see MUL-2946 for the classifier contract.
- if err := d.client.StartTask(prepareCtx, task.ID); err != nil {
+ if err := d.client.StartTask(prepareCtx, task); err != nil {
stopPrepareLease()
return TaskResult{}, fmt.Errorf("start task failed: %w", err)
}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 183a7c1895..7139ce386a 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -68,6 +68,9 @@ type IssueStatusData struct {
// Task represents a claimed task from the server.
// Agent data (name, skills) is populated by the claim endpoint.
type Task struct {
+ // StartClaimSupported gates retries when talking to older servers.
+ StartClaimSupported bool `json:"start_claim_supported,omitempty"`
+ DispatchedAt string `json:"dispatched_at,omitempty"`
ID string `json:"id"`
AgentID string `json:"agent_id"`
RuntimeID string `json:"runtime_id"`
diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.go
index a068d83c34..a9c3914686 100644
--- a/server/internal/daemon/workdir_race_test.go
+++ b/server/internal/daemon/workdir_race_test.go
@@ -580,6 +580,7 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
closeLeaseOnce sync.Once
)
leaseSeenDuringStart := make(chan struct{})
+ var startAttempts atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
@@ -590,11 +591,16 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
}
w.WriteHeader(http.StatusOK)
case strings.HasSuffix(r.URL.Path, "/start"):
+ attempt := startAttempts.Add(1)
startEntered.Store(true)
select {
case <-leaseSeenDuringStart:
case <-time.After(2 * time.Second):
}
+ if attempt == 1 {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusOK)
@@ -619,12 +625,14 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
}
task := Task{
- ID: taskID,
- WorkspaceID: workspaceID,
- RuntimeID: "rt-1",
- IssueID: "issue-runtask-start-lease",
- AgentID: "agent-runtask-start-lease",
- Agent: &AgentData{ID: "agent-runtask-start-lease", Name: "test-agent"},
+ ID: taskID,
+ WorkspaceID: workspaceID,
+ RuntimeID: "rt-1",
+ IssueID: "issue-runtask-start-lease",
+ StartClaimSupported: true,
+ DispatchedAt: "2026-09-17T09:00:00.123456Z",
+ AgentID: "agent-runtask-start-lease",
+ Agent: &AgentData{ID: "agent-runtask-start-lease", Name: "test-agent"},
}
taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
@@ -636,6 +644,9 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
if !leaseDuringStart.Load() {
t.Fatal("prepare lease was not extended while /start was still in flight")
}
+ if startAttempts.Load() != 2 {
+ t.Fatalf("start attempts = %d, want transient failure then success", startAttempts.Load())
+ }
}
// prepareRequestCountingTransport counts requests where the client starts
@@ -734,12 +745,14 @@ func prepareTimeoutStopsLeaseDuringBlockedStart(t *testing.T, budget time.Durati
}
task := Task{
- ID: "task-runtask-start-timeout",
- WorkspaceID: "ws-runtask-start-timeout",
- RuntimeID: "rt-1",
- IssueID: "issue-runtask-start-timeout",
- AgentID: "agent-runtask-start-timeout",
- Agent: &AgentData{ID: "agent-runtask-start-timeout", Name: "test-agent"},
+ ID: "task-runtask-start-timeout",
+ StartClaimSupported: true,
+ DispatchedAt: "2026-09-17T09:00:00.123456Z",
+ WorkspaceID: "ws-runtask-start-timeout",
+ RuntimeID: "rt-1",
+ IssueID: "issue-runtask-start-timeout",
+ AgentID: "agent-runtask-start-timeout",
+ Agent: &AgentData{ID: "agent-runtask-start-timeout", Name: "test-agent"},
}
taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
startedAt := time.Now()
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 661acda1ca..5bce765cda 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -357,6 +357,7 @@ type TaskCancellationActor struct {
}
type AgentTaskResponse struct {
+ StartClaimSupported bool `json:"start_claim_supported,omitempty"`
CancelledByCommentChange bool `json:"cancelled_by_comment_change,omitempty"`
CancelledBy *TaskCancellationActor `json:"cancelled_by,omitempty"`
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 7f06b43cce..1126a0e491 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2349,6 +2349,13 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
return resp, nil, nil, 0, 0, h.failClaimedTaskBeforeLaunch(r.Context(), task, "Wakeup is disabled or its authorization is no longer available.", taskfailure.ReasonInvalidTaskIdentity, "wakeup_unavailable", http.StatusConflict, "wakeup unavailable")
}
+ // Preserve PostgreSQL's microseconds: second-resolution display timestamps
+ // cannot distinguish stale claims reclaimed within the same second.
+ if task.DispatchedAt.Valid {
+ generation := task.DispatchedAt.Time.UTC().Format(time.RFC3339Nano)
+ resp.DispatchedAt = &generation
+ resp.StartClaimSupported = true
+ }
var issueNumber int32
// Claim-only capability: this server resolves the squad-leader role on the
// wire (is_leader_task / squad_id), so the daemon must not re-derive it
@@ -4077,10 +4084,49 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.TaskService.StartTask(r.Context(), parseUUID(taskID))
+ var req struct {
+ RuntimeID string `json:"runtime_id"`
+ DispatchedAt string `json:"dispatched_at"`
+ }
+ if r.ContentLength != 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ }
+ var task *db.AgentTaskQueue
+ var err error
+ legacy := req.RuntimeID == "" && req.DispatchedAt == ""
+ if legacy {
+ // Older daemons send {}. Keep their single-winner behavior; in
+ // particular, they cannot acknowledge an already-running task.
+ task, err = h.TaskService.StartTask(r.Context(), parseUUID(taskID))
+ } else {
+ runtimeID, ok := parseUUIDOrBadRequest(w, req.RuntimeID, "runtime_id")
+ if !ok {
+ return
+ }
+ generation, parseErr := time.Parse(time.RFC3339Nano, req.DispatchedAt)
+ if parseErr != nil || generation.Nanosecond()%1000 != 0 {
+ writeError(w, http.StatusBadRequest, "dispatched_at must be a PostgreSQL claim timestamp")
+ return
+ }
+ task, err = h.TaskService.StartTaskForClaim(r.Context(), db.LockAgentTaskStartClaimParams{
+ ID: parseUUID(taskID), RuntimeID: runtimeID,
+ DispatchedAt: pgtype.Timestamptz{Time: generation, Valid: true},
+ })
+ }
if err != nil {
slog.Warn("start task failed", "task_id", taskID, "error", err)
- writeError(w, http.StatusBadRequest, err.Error())
+ if errors.Is(err, pgx.ErrNoRows) {
+ status := http.StatusConflict
+ if legacy {
+ status = http.StatusBadRequest
+ }
+ writeError(w, status, "task claim is stale or task is no longer startable")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to start task")
+ }
return
}
diff --git a/server/internal/handler/daemon_start_claim_test.go b/server/internal/handler/daemon_start_claim_test.go
new file mode 100644
index 0000000000..4e31365ac1
--- /dev/null
+++ b/server/internal/handler/daemon_start_claim_test.go
@@ -0,0 +1,212 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func startClaimFixture(t *testing.T, status string) (string, string, time.Time) {
+ t.Helper()
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required for start claim tests")
+ }
+ var agentID string
+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id=$1 LIMIT 1`, testWorkspaceID).Scan(&agentID)
+ issueID := dbfx.Issue(t, "start claim ownership")
+ generation := time.Date(2026, 9, 17, 9, 0, 0, 123456000, time.UTC)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": testRuntimeID,
+ "status": status, "dispatched_at": generation,
+ })
+ return taskID, testRuntimeID, generation
+}
+
+func startClaimRequest(taskID, runtimeID string, generation time.Time) *http.Request {
+ return withURLParam(newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]string{
+ "runtime_id": runtimeID, "dispatched_at": generation.Format(time.RFC3339Nano),
+ }, testWorkspaceID, "start-claim-test"), "taskId", taskID)
+}
+
+func TestStartClaimLostResponseAndOwnership(t *testing.T) {
+ for _, state := range []string{"dispatched", "waiting_local_directory"} {
+ t.Run(state, func(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, state)
+ // A stale generation on the same runtime cannot win the FIRST start.
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation.Add(-time.Microsecond))).Want(http.StatusConflict)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, "00000000-0000-0000-0000-000000000001", generation)).Want(http.StatusConflict)
+ // Commit the first request, then discard its response (lost acknowledgement).
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusOK)
+ var before pgtype.Timestamptz
+ dbfx.QueryRow(t, `SELECT started_at FROM agent_task_queue WHERE id=$1`, id).Scan(&before)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusOK)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation.Add(-time.Microsecond))).Want(http.StatusConflict)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, "00000000-0000-0000-0000-000000000001", generation)).Want(http.StatusConflict)
+ var after pgtype.Timestamptz
+ dbfx.QueryRow(t, `SELECT started_at FROM agent_task_queue WHERE id=$1`, id).Scan(&after)
+ if !before.Valid || !before.Time.Equal(after.Time) {
+ t.Fatalf("replay changed started_at: %v -> %v", before, after)
+ }
+ })
+ }
+}
+
+func TestStartClaimReclaimedGeneration(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, "dispatched")
+ // Reclaim refreshes dispatched_at even if the runtime stays the same.
+ newGeneration := generation.Add(time.Microsecond)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET dispatched_at=$2 WHERE id=$1`, id, newGeneration)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusConflict)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, newGeneration)).Want(http.StatusOK)
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusConflict)
+}
+
+func TestStartClaimConcurrentReplay(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, "dispatched")
+ const workers = 12
+ results := make(chan *httptest.ResponseRecorder, workers)
+ var wg sync.WaitGroup
+ gate := make(chan struct{})
+ for range workers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-gate
+ w := httptest.NewRecorder()
+ testHandler.StartTask(w, startClaimRequest(id, runtimeID, generation))
+ results <- w
+ }()
+ }
+ close(gate)
+ wg.Wait()
+ close(results)
+ var started string
+ for w := range results {
+ if w.Code != http.StatusOK {
+ t.Fatalf("concurrent start: %d %s", w.Code, w.Body.String())
+ }
+ var task AgentTaskResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &task); err != nil {
+ t.Fatal(err)
+ }
+ if task.StartedAt == nil {
+ t.Fatal("missing started_at")
+ }
+ if started != "" && started != *task.StartedAt {
+ t.Fatal("multiple start timestamps")
+ }
+ started = *task.StartedAt
+ }
+}
+
+func TestStartClaimCancellationRace(t *testing.T) {
+ for _, replay := range []bool{false, true} {
+ t.Run(fmt.Sprintf("replay=%t", replay), func(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, "dispatched")
+ if replay {
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusOK)
+ }
+ ctx := context.Background()
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `UPDATE agent_task_queue SET status='cancelled' WHERE id=$1`, id); err != nil {
+ t.Fatal(err)
+ }
+ result := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ testHandler.StartTask(w, startClaimRequest(id, runtimeID, generation))
+ result <- w
+ }()
+ // Observe the actual PostgreSQL row-lock wait before committing cancellation.
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ var blocked bool
+ dbfx.QueryRow(t, `SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '-- name: LockAgentTaskStartClaim%')`).Scan(&blocked)
+ if blocked {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("start did not wait on cancellation lock")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case w := <-result:
+ if w.Code != http.StatusConflict {
+ t.Fatalf("cancelled start: %d %s", w.Code, w.Body.String())
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("start blocked after cancellation committed")
+ }
+ testutil.Call(t, testHandler.StartTask, startClaimRequest(id, runtimeID, generation)).Want(http.StatusConflict)
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, id).Scan(&status)
+ if status != "cancelled" {
+ t.Fatalf("cancellation overwritten: %s", status)
+ }
+ })
+ }
+}
+
+func TestStartClaimInvalidBodiesAndLegacy(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, "dispatched")
+ for _, body := range []any{
+ map[string]string{"runtime_id": runtimeID},
+ map[string]string{"dispatched_at": generation.Format(time.RFC3339Nano)},
+ map[string]string{"runtime_id": "invalid", "dispatched_at": generation.Format(time.RFC3339Nano)},
+ map[string]string{"runtime_id": runtimeID, "dispatched_at": generation.Add(time.Nanosecond).Format(time.RFC3339Nano)},
+ } {
+ req := withURLParam(newDaemonTokenRequest("POST", "/start", body, testWorkspaceID, "legacy-test"), "taskId", id)
+ testutil.Call(t, testHandler.StartTask, req).Want(http.StatusBadRequest)
+ }
+ for _, code := range []int{http.StatusOK, http.StatusBadRequest} {
+ req := withURLParam(newDaemonTokenRequest("POST", "/start", nil, testWorkspaceID, "legacy-test"), "taskId", id)
+ testutil.Call(t, testHandler.StartTask, req).Want(code)
+ }
+}
+
+func TestStartClaimWirePrecision(t *testing.T) {
+ id, runtimeID, generation := startClaimFixture(t, "dispatched")
+ task, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(id))
+ if err != nil {
+ t.Fatal(err)
+ }
+ runtime, err := testHandler.Queries.GetAgentRuntime(context.Background(), parseUUID(runtimeID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := newDaemonTokenRequest("POST", "/claim", nil, testWorkspaceID, "claim-wire-test")
+ // Exercise non-UTC database timestamp locations even on a UTC CI runner.
+ for _, zone := range []*time.Location{time.UTC, time.FixedZone("UTC+08", 8*60*60), time.FixedZone("UTC-07", -7*60*60)} {
+ t.Run(zone.String(), func(t *testing.T) {
+ claimed := task
+ claimed.DispatchedAt.Time = task.DispatchedAt.Time.In(zone)
+ resp, _, _, _, _, failure := testHandler.buildClaimedTaskResponse(req, &claimed, runtime, runtimeID, testWorkspaceID)
+ if failure != nil {
+ t.Fatalf("build claim: %+v", failure)
+ }
+ want := generation.UTC().Format(time.RFC3339Nano)
+ if !resp.StartClaimSupported || resp.DispatchedAt == nil {
+ t.Fatalf("missing claim timestamp or capability: supported=%t timestamp=%v", resp.StartClaimSupported, resp.DispatchedAt)
+ }
+ if *resp.DispatchedAt != want {
+ t.Fatalf("claim timestamp = %q, want canonical UTC with microseconds %q", *resp.DispatchedAt, want)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index f6c06263e5..eeb1afae36 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4170,6 +4170,44 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
if err != nil {
return nil, fmt.Errorf("start task: %w", err)
}
+ s.taskStarted(ctx, task)
+ return &task, nil
+}
+
+// StartTaskForClaim serializes the ownership check and transition with reclaim,
+// cancellation and other start requests. A replay linearizes at the locked read;
+// a cancellation that commits later can still cancel the acknowledged task.
+func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentTaskStartClaimParams) (*db.AgentTaskQueue, error) {
+ if !claim.ID.Valid || !claim.RuntimeID.Valid || !claim.DispatchedAt.Valid {
+ return nil, fmt.Errorf("start task: incomplete claim")
+ }
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin task start: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.Queries.WithTx(tx)
+ task, err := qtx.LockAgentTaskStartClaim(ctx, claim)
+ if err != nil {
+ return nil, fmt.Errorf("lock task start claim: %w", err)
+ }
+ replay := task.Status == "running"
+ if !replay {
+ task, err = qtx.StartAgentTask(ctx, task.ID)
+ if err != nil {
+ return nil, fmt.Errorf("start claimed task: %w", err)
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return nil, fmt.Errorf("commit task start: %w", err)
+ }
+ if !replay {
+ s.taskStarted(ctx, task)
+ }
+ return &task, nil
+}
+
+func (s *TaskService) taskStarted(ctx context.Context, task db.AgentTaskQueue) {
s.forgetTaskReclaim(task)
slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
@@ -4186,7 +4224,6 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
// the issue-card agent activity indicator) lags by up to half a minute
// on the transition users care about most.
s.broadcastTaskEvent(ctx, protocol.EventTaskRunning, task)
- return &task, nil
}
// ExtendTaskPrepareLease keeps a claimed-but-not-started task protected while
diff --git a/server/internal/service/task_start_test.go b/server/internal/service/task_start_test.go
new file mode 100644
index 0000000000..6c84f3393c
--- /dev/null
+++ b/server/internal/service/task_start_test.go
@@ -0,0 +1,32 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type startReplayDB struct {
+ mockDBTX
+ startErr error
+ calls int
+}
+
+func (m *startReplayDB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ m.calls++
+ return &mockRow{err: m.startErr}
+}
+
+func TestStartTaskLegacyDoesNotAcknowledgeReplayOrDatabaseFailure(t *testing.T) {
+ for _, want := range []error{pgx.ErrNoRows, errors.New("database unavailable")} {
+ store := &startReplayDB{startErr: want}
+ svc := &TaskService{Queries: db.New(store)}
+ got, err := svc.StartTask(context.Background(), testUUID(1))
+ if got != nil || !errors.Is(err, want) || store.calls != 1 {
+ t.Fatalf("legacy start: task=%v err=%v queries=%d", got, err, store.calls)
+ }
+ }
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 72fa310a97..0bfc2bdf6b 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -6748,6 +6748,88 @@ func (q *Queries) LockAgentForAutopilotAssignment(ctx context.Context, arg LockA
return i, err
}
+const lockAgentTaskStartClaim = `-- name: LockAgentTaskStartClaim :one
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queue
+WHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3
+ AND status IN ('dispatched', 'waiting_local_directory', 'running')
+FOR UPDATE
+`
+
+type LockAgentTaskStartClaimParams struct {
+ ID pgtype.UUID `json:"id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+}
+
+// Serialize start/replay with reclaim and cancellation. A stale delivery must
+// never start or acknowledge a newer claim, even on the same runtime.
+func (q *Queries) LockAgentTaskStartClaim(ctx context.Context, arg LockAgentTaskStartClaimParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, lockAgentTaskStartClaim, arg.ID, arg.RuntimeID, arg.DispatchedAt)
+ 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,
+ &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.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ )
+ return i, err
+}
+
const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDirectory :one
UPDATE agent_task_queue
SET status = 'waiting_local_directory',
@@ -8516,6 +8598,7 @@ WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot
`
+// Legacy single-winner transition; generation-aware callers lock the claim first.
// Transitions a task to running. Accepts either 'dispatched' (the normal
// claim → run flow) or 'waiting_local_directory' (the daemon held the row in
// a wait state while another task owned the local_directory path lock; once
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index cf33083e6c..97a33d5f5f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -968,6 +968,7 @@ WHERE id = $1
RETURNING *;
-- name: StartAgentTask :one
+-- Legacy single-winner transition; generation-aware callers lock the claim first.
-- Transitions a task to running. Accepts either 'dispatched' (the normal
-- claim → run flow) or 'waiting_local_directory' (the daemon held the row in
-- a wait state while another task owned the local_directory path lock; once
@@ -982,6 +983,14 @@ SET status = 'running',
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
RETURNING *;
+-- name: LockAgentTaskStartClaim :one
+-- Serialize start/replay with reclaim and cancellation. A stale delivery must
+-- never start or acknowledge a newer claim, even on the same runtime.
+SELECT * FROM agent_task_queue
+WHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3
+ AND status IN ('dispatched', 'waiting_local_directory', 'running')
+FOR UPDATE;
+
-- name: MarkAgentTaskWaitingLocalDirectory :one
-- Transitions a freshly-dispatched task into 'waiting_local_directory' while
-- the daemon waits for another in-flight task to release the path lock on a