Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6697: enforce runtime access on task claims (#7571)
Multica Evebbba9c5460d4
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 4374f30775..44f65a2072 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1707,8 +1707,8 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {resp, deliveredCommentIDs, _, _, failure := h.buildClaimedTaskResponse(r, &task, rt, uuidToString(task.RuntimeID), rtWorkspaceID)if failure != nil {// Builder rejected this task (workspace isolation / chat-input);- // it has already cancelled the task where the failure requires it.- // Skip it — non-cancelling failures leave the task dispatched for+ // it has already settled the task where the failure requires it.+ // Skip it — non-settling failures leave the task dispatched for// the reclaim path.continue}@@ -2072,6 +2072,43 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQumessage: "failed to load task agent",}}+ // The SQL claim narrows candidates and repeats the access predicate before+ // changing task state, but Agent mutations do not stay locked through HTTP+ // response assembly. Recheck the freshly loaded Agent here so a rebind or+ // owner change that committed after the claim cannot reach the daemon.+ if agent.RuntimeID != task.RuntimeID {+ slog.Warn("daemon claim: agent runtime changed before delivery; refusing dispatch",+ "task_id", uuidToString(task.ID),+ "agent_id", uuidToString(task.AgentID),+ "task_runtime_id", uuidToString(task.RuntimeID),+ "agent_runtime_id", uuidToString(agent.RuntimeID),+ )+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.failClaimedTaskBeforeLaunch(+ r.Context(), task,+ "The agent moved to another runtime before this task could start. Retry the task to run it on the agent's current runtime.",+ taskfailure.ReasonInvalidTaskIdentity,+ "error_agent_runtime_changed", http.StatusConflict, "agent runtime changed before task delivery",+ )+ }+ if runtime.Visibility == "private" && runtime.OwnerID.Valid &&+ (!agent.OwnerID.Valid || agent.OwnerID != runtime.OwnerID) {+ userMessage := "This private runtime cannot run the assigned agent because the agent and runtime have different owners."+ if !agent.OwnerID.Valid {+ userMessage = "This private runtime cannot run the assigned agent because the agent has no owner."+ }+ slog.Warn("daemon claim: private runtime no longer permits task agent; refusing dispatch",+ "task_id", uuidToString(task.ID),+ "agent_id", uuidToString(task.AgentID),+ "runtime_id", runtimeID,+ "agent_owner_valid", agent.OwnerID.Valid,+ )+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.failClaimedTaskBeforeLaunch(+ r.Context(), task,+ userMessage,+ taskfailure.ReasonInvalidTaskIdentity,+ "error_runtime_access_denied", http.StatusForbidden, "private runtime does not permit task agent",+ )+ }useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)var customEnv map[string]stringif agent.CustomEnv != nil {diff --git a/server/internal/handler/daemon_runtime_access_test.go b/server/internal/handler/daemon_runtime_access_test.gonew file mode 100644index 0000000000..125fbd26d5--- /dev/null+++ b/server/internal/handler/daemon_runtime_access_test.go@@ -0,0 +1,156 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/taskfailure"+)++func TestClaimTaskByRuntime_OwnerlessAgentOnPrivateRuntimeFailsExplicitly(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Ownerless agent private runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Ownerless private agent")+ dbfx.Exec(t, `UPDATE agent SET owner_id = NULL WHERE id = $1`, agentID)+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)++ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,+ testWorkspaceID, "ownerless-agent-claim")+ req = withURLParam(req, "runtimeId", runtimeID)+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusForbidden)+ if !strings.Contains(w.Body.String(), "private runtime does not permit task agent") {+ t.Fatalf("ClaimTaskByRuntime body = %q, want explicit private-runtime access error", w.Body.String())+ }++ var status, errorMessage, failureReason string+ dbfx.QueryRow(t, `+ SELECT status, error, failure_reason+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&status, &errorMessage, &failureReason)+ if status != "failed" {+ t.Fatalf("task status = %q, want failed", status)+ }+ if !strings.Contains(errorMessage, "agent has no owner") {+ t.Fatalf("task error = %q, want actionable missing-owner error", errorMessage)+ }+ if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)+ }+}++func TestBuildClaimedTaskResponseRejectsAgentOwnerChangedAfterClaim(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ newOwnerID := dbfx.User(t, "Claim owner mismatch", "claim-owner-mismatch-"+uuid.NewString()+"@example.com")+ dbfx.Member(t, testWorkspaceID, newOwnerID, "member")+ runtimeID := createClaimReclaimRuntime(t, ctx, "Claim then change owner runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Claim then change owner agent")+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)++ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(runtimeID))+ if err != nil {+ t.Fatalf("claim task: %v", err)+ }+ if task == nil || uuidToString(task.ID) != taskID {+ t.Fatalf("claimed task = %+v, want %s", task, taskID)+ }+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, newOwnerID, agentID)++ runtime, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{+ ID: parseUUID(runtimeID),+ WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,+ testWorkspaceID, "claim-then-owner-change")+ _, _, _, _, failure := testHandler.buildClaimedTaskResponse(+ req, task, runtime, runtimeID, testWorkspaceID,+ )+ if failure == nil || failure.status != http.StatusForbidden || failure.outcome != "error_runtime_access_denied" {+ t.Fatalf("failure = %+v, want runtime-access forbidden", failure)+ }++ var status, errorMessage, failureReason string+ dbfx.QueryRow(t, `+ SELECT status, error, failure_reason+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&status, &errorMessage, &failureReason)+ if status != "failed" {+ t.Fatalf("task status = %q, want failed", status)+ }+ if !strings.Contains(errorMessage, "agent and runtime have different owners") {+ t.Fatalf("task error = %q, want actionable owner-mismatch error", errorMessage)+ }+ if strings.Contains(errorMessage, "agent has no owner") {+ t.Fatalf("task error = %q, must not describe a non-null owner as missing", errorMessage)+ }+ if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)+ }+}++func TestBuildClaimedTaskResponseRejectsAgentReboundAfterClaim(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ oldRuntimeID := createClaimReclaimRuntime(t, ctx, "Claim then rebind old runtime")+ newRuntimeID := createClaimReclaimRuntime(t, ctx, "Claim then rebind new runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, oldRuntimeID, "Claim then rebind agent")+ taskID := seedQueuedIssueTask(t, ctx, agentID, oldRuntimeID, issueID)++ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(oldRuntimeID))+ if err != nil {+ t.Fatalf("claim task: %v", err)+ }+ if task == nil || uuidToString(task.ID) != taskID {+ t.Fatalf("claimed task = %+v, want %s", task, taskID)+ }+ dbfx.Exec(t, `UPDATE agent SET runtime_id = $1 WHERE id = $2`, newRuntimeID, agentID)++ runtime, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{+ ID: parseUUID(oldRuntimeID),+ WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("load old runtime: %v", err)+ }+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+oldRuntimeID+"/tasks/claim", nil,+ testWorkspaceID, "claim-then-rebind")+ _, _, _, _, failure := testHandler.buildClaimedTaskResponse(+ req, task, runtime, oldRuntimeID, testWorkspaceID,+ )+ if failure == nil || failure.status != http.StatusConflict || failure.outcome != "error_agent_runtime_changed" {+ t.Fatalf("failure = %+v, want runtime-changed conflict", failure)+ }++ var status, errorMessage, failureReason string+ dbfx.QueryRow(t, `+ SELECT status, error, failure_reason+ FROM agent_task_queue+ WHERE id = $1+ `, taskID).Scan(&status, &errorMessage, &failureReason)+ if status != "failed" {+ t.Fatalf("task status = %q, want failed", status)+ }+ if !strings.Contains(errorMessage, "moved to another runtime") {+ t.Fatalf("task error = %q, want actionable rebind error", errorMessage)+ }+ if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)+ }+}diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 2f211c1ce9..f9a5667fba 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -2723,11 +2723,11 @@ func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtimdbfx.QueryRow(t, `INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks+ runtime_id, visibility, max_concurrent_tasks, owner_id)- VALUES ($1, $2, 'local', '{}'::jsonb, $3, 'workspace', 3)+ VALUES ($1, $2, 'local', '{}'::jsonb, $3, 'workspace', 3, $4)RETURNING id- `, testWorkspaceID, "Runtime Guard Agent "+t.Name(), runtimeID).Scan(&agentID)+ `, testWorkspaceID, "Runtime Guard Agent "+t.Name(), runtimeID, testUserID).Scan(&agentID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })return agentID, runtimeID, daemonIDdiff --git a/server/internal/service/runtime_claim_access_test.go b/server/internal/service/runtime_claim_access_test.gonew file mode 100644index 0000000000..dcf587b070--- /dev/null+++ b/server/internal/service/runtime_claim_access_test.go@@ -0,0 +1,284 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type runtimeClaimAccessFixture struct {+ pool *pgxpool.Pool+ agentID pgtype.UUID+ runtimeID pgtype.UUID+ taskID string+}++func newRuntimeClaimAccessFixture(+ t *testing.T,+ visibility string,+ sameOwner bool,+ matchingBinding bool,+ taskStatus string,+) runtimeClaimAccessFixture {+ t.Helper()++ pool := newResolveOriginatorPool(t)+ bootstrap := testutil.New(pool, "", "")+ suffix := time.Now().UnixNano()+ runtimeOwnerID := bootstrap.User(t,+ fmt.Sprintf("runtime-owner-%d", suffix),+ fmt.Sprintf("runtime-owner-%[email protected]", suffix),+ )+ agentOwnerID := runtimeOwnerID+ if !sameOwner {+ agentOwnerID = bootstrap.User(t,+ fmt.Sprintf("agent-owner-%d", suffix),+ fmt.Sprintf("agent-owner-%[email protected]", suffix),+ )+ }+ workspaceID := bootstrap.Workspace(t,+ fmt.Sprintf("runtime-claim-access-%d", suffix),+ fmt.Sprintf("runtime-claim-access-%d", suffix),+ )++ fx := testutil.New(pool, workspaceID, runtimeOwnerID)+ fx.Member(t, workspaceID, runtimeOwnerID, "owner")+ if agentOwnerID != runtimeOwnerID {+ fx.Member(t, workspaceID, agentOwnerID, "member")+ }+ taskRuntimeID := fx.Runtime(t, "task-runtime", testutil.Cols{+ "visibility": visibility,+ "owner_id": runtimeOwnerID,+ })+ boundRuntimeID := taskRuntimeID+ if !matchingBinding {+ boundRuntimeID = fx.Runtime(t, "agent-runtime", testutil.Cols{+ "visibility": "public",+ "owner_id": runtimeOwnerID,+ })+ }+ agentID := fx.Agent(t, "claim-agent", boundRuntimeID, testutil.Cols{+ "owner_id": agentOwnerID,+ "max_concurrent_tasks": 5,+ })+ issueID := fx.Issue(t, "runtime claim access")+ taskCols := testutil.Cols{+ "runtime_id": taskRuntimeID,+ "issue_id": issueID,+ "status": taskStatus,+ }+ if taskStatus == "dispatched" {+ taskCols["dispatched_at"] = testutil.Raw("now() - interval '10 minutes'")+ taskCols["prepare_lease_expires_at"] = testutil.Raw("now() - interval '1 minute'")+ }+ taskID := fx.Task(t, agentID, taskCols)++ return runtimeClaimAccessFixture{+ pool: pool,+ agentID: util.MustParseUUID(agentID),+ runtimeID: util.MustParseUUID(taskRuntimeID),+ taskID: taskID,+ }+}++func TestRuntimeAccessGatesQueuedTaskClaims(t *testing.T) {+ ctx := context.Background()++ tests := []struct {+ name string+ visibility string+ sameOwner bool+ matchingBinding bool+ ownerlessAgent bool+ wantClaim bool+ }{+ {name: "private runtime rejects foreign agent", visibility: "private", wantClaim: false, matchingBinding: true},+ {name: "private runtime accepts owner agent", visibility: "private", sameOwner: true, matchingBinding: true, wantClaim: true},+ {name: "private runtime routes ownerless agent to handler", visibility: "private", sameOwner: true, matchingBinding: true, ownerlessAgent: true, wantClaim: true},+ {name: "public runtime accepts foreign agent", visibility: "public", wantClaim: true, matchingBinding: true},+ {name: "task runtime must match agent binding", visibility: "public", wantClaim: false, matchingBinding: false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ fixture := newRuntimeClaimAccessFixture(t, tt.visibility, tt.sameOwner, tt.matchingBinding, "queued")+ if tt.ownerlessAgent {+ if _, err := fixture.pool.Exec(ctx, `UPDATE agent SET owner_id = NULL WHERE id = $1`, fixture.agentID); err != nil {+ t.Fatalf("clear agent owner: %v", err)+ }+ }+ q := db.New(fixture.pool)++ candidates, err := q.ListQueuedClaimCandidatesByRuntime(ctx, fixture.runtimeID)+ if err != nil {+ t.Fatalf("list singular candidates: %v", err)+ }+ batchCandidates, err := q.ListQueuedClaimCandidatesByRuntimes(ctx, []pgtype.UUID{fixture.runtimeID})+ if err != nil {+ t.Fatalf("list batch candidates: %v", err)+ }+ wantCandidates := 0+ if tt.wantClaim {+ wantCandidates = 1+ }+ if len(candidates) != wantCandidates {+ t.Fatalf("singular candidates = %d, want %d", len(candidates), wantCandidates)+ }+ if len(batchCandidates) != wantCandidates {+ t.Fatalf("batch candidates = %d, want %d", len(batchCandidates), wantCandidates)+ }++ claimed, err := q.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{+ AgentID: fixture.agentID,+ RuntimeID: fixture.runtimeID,+ PrepareLeaseSecs: 60,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })+ if !tt.wantClaim {+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("claim error = %v, want no rows", err)+ }+ var status string+ if err := fixture.pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, fixture.taskID).Scan(&status); err != nil {+ t.Fatalf("read task status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("task status = %q, want queued", status)+ }+ return+ }+ if err != nil {+ t.Fatalf("claim: %v", err)+ }+ if util.UUIDToString(claimed.ID) != fixture.taskID {+ t.Fatalf("claimed task = %s, want %s", util.UUIDToString(claimed.ID), fixture.taskID)+ }+ })+ }+}++func TestRuntimeAccessGatesStaleDispatchReclaim(t *testing.T) {+ ctx := context.Background()++ tests := []struct {+ name string+ visibility string+ sameOwner bool+ matchingBinding bool+ ownerlessAgent bool+ wantReclaim bool+ }{+ {name: "private runtime rejects foreign agent", visibility: "private", wantReclaim: false, matchingBinding: true},+ {name: "private runtime accepts owner agent", visibility: "private", sameOwner: true, matchingBinding: true, wantReclaim: true},+ {name: "private runtime routes ownerless agent to handler", visibility: "private", sameOwner: true, matchingBinding: true, ownerlessAgent: true, wantReclaim: true},+ {name: "public runtime accepts foreign agent", visibility: "public", wantReclaim: true, matchingBinding: true},+ {name: "task runtime must match agent binding", visibility: "public", wantReclaim: false, matchingBinding: false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ fixture := newRuntimeClaimAccessFixture(t, tt.visibility, tt.sameOwner, tt.matchingBinding, "dispatched")+ if tt.ownerlessAgent {+ if _, err := fixture.pool.Exec(ctx, `UPDATE agent SET owner_id = NULL WHERE id = $1`, fixture.agentID); err != nil {+ t.Fatalf("clear agent owner: %v", err)+ }+ }+ q := db.New(fixture.pool)+ params := db.ReclaimStaleDispatchedTaskForRuntimeParams{+ RuntimeID: fixture.runtimeID,+ PrepareLeaseSecs: 60,+ ClaimRecoverySecs: 30,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ }+ reclaimed, err := q.ReclaimStaleDispatchedTaskForRuntime(ctx, params)+ if !tt.wantReclaim {+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("singular reclaim error = %v, want no rows", err)+ }+ } else {+ if err != nil {+ t.Fatalf("singular reclaim: %v", err)+ }+ if util.UUIDToString(reclaimed.ID) != fixture.taskID {+ t.Fatalf("singular reclaimed task = %s, want %s", util.UUIDToString(reclaimed.ID), fixture.taskID)+ }+ }++ // Restore the stale generation so the batch path evaluates the same gate.+ if _, err := fixture.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET dispatched_at = now() - interval '10 minutes',+ prepare_lease_expires_at = now() - interval '1 minute'+ WHERE id = $1+ `, fixture.taskID); err != nil {+ t.Fatalf("reset stale dispatch: %v", err)+ }+ batch, err := q.ReclaimStaleDispatchedTasksForRuntimes(ctx, db.ReclaimStaleDispatchedTasksForRuntimesParams{+ RuntimeIds: []pgtype.UUID{fixture.runtimeID},+ PrepareLeaseSecs: 60,+ ClaimRecoverySecs: 30,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ MaxTasks: 10,+ })+ if err != nil {+ t.Fatalf("batch reclaim: %v", err)+ }+ wantBatch := 0+ if tt.wantReclaim {+ wantBatch = 1+ }+ if len(batch) != wantBatch {+ t.Fatalf("batch reclaimed %d tasks, want %d", len(batch), wantBatch)+ }+ })+ }+}++func TestClaimTaskRejectsMismatchedAgentRuntime(t *testing.T) {+ ctx := context.Background()+ fixture := newRuntimeClaimAccessFixture(t, "public", false, false, "queued")+ svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())++ claimed, err := svc.claimTask(ctx, fixture.agentID, fixture.runtimeID)+ if err != nil {+ t.Fatalf("claim task: %v", err)+ }+ if claimed != nil {+ t.Fatalf("claimed mismatched task %s", util.UUIDToString(claimed.ID))+ }++ var status string+ if err := fixture.pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, fixture.taskID).Scan(&status); err != nil {+ t.Fatalf("read task status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("task status = %q, want queued", status)+ }+}++func TestClaimTaskUsesCurrentAgentRuntimeWhenRuntimeIDIsOmitted(t *testing.T) {+ ctx := context.Background()+ fixture := newRuntimeClaimAccessFixture(t, "public", true, true, "queued")+ svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())++ claimed, err := svc.ClaimTask(ctx, fixture.agentID)+ if err != nil {+ t.Fatalf("claim task: %v", err)+ }+ if claimed == nil {+ t.Fatal("ClaimTask returned nil, want task from the agent's current runtime")+ }+ if util.UUIDToString(claimed.ID) != fixture.taskID {+ t.Fatalf("claimed task = %s, want %s", util.UUIDToString(claimed.ID), fixture.taskID)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex c451b134e9..a8e0513d6b 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3374,6 +3374,15 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.Uoutcome = "no_runtime"return nil}+ // A daemon may still hold a stale candidate after the agent is rebound.+ // Reject it before doing capacity work. ClaimAgentTask repeats the fence+ // before its state transition; the claim handler then rechecks the freshly+ // loaded Agent before returning any payload. Runtime mutation teardown is+ // responsible for serializing and settling the remaining queued rows.+ if runtimeID.Valid && agent.RuntimeID != runtimeID {+ outcome = "runtime_mismatch"+ return nil+ }t0 = time.Now()running, err := qtx.CountRunningTasks(ctx, agentID)diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 8211697dde..bd3d72a194 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1577,8 +1577,28 @@ WHERE id = (AND atq.runtime_id = $3AND atq.status = 'queued'AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ -- A task's persisted runtime is not authority after an agent rebind.+ AND a.runtime_id = atq.runtime_id+ -- Private runtimes only execute their owner's agents. Ownerless+ -- runtime/agent rows remain claimable only so the handler can+ -- settle them explicitly before daemon delivery; filtering them+ -- here would leave every task silently queued until the TTL.+ -- Public runtimes remain shareable across agent owners.+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => $4::double precision)@@ -5790,12 +5810,32 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :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, 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 FROM agent_task_queue-WHERE runtime_id = $1 AND status = 'queued'-ORDER BY priority DESC, created_at ASC+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.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq+WHERE atq.runtime_id = $1+ AND atq.status = 'queued'+ AND EXISTS (+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )+ )+ORDER BY atq.priority DESC, atq.created_at ASC`-// Returns rows the runtime can attempt to claim. Status is restricted to+// Returns rows the runtime is authorized to attempt to claim. Status is restricted to// 'queued' (in contrast to ListPendingTasksByRuntime which also includes// 'dispatched') because dispatched rows are by definition already owned// and cannot be re-claimed — including them in the candidate list pads@@ -5879,9 +5919,29 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim}const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :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, 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 FROM agent_task_queue-WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'-ORDER BY priority DESC, created_at ASC+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.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq+WHERE atq.runtime_id = ANY($1::uuid[])+ AND atq.status = 'queued'+ AND EXISTS (+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )+ )+ORDER BY atq.priority DESC, atq.created_at ASC`// Batch variant of ListQueuedClaimCandidatesByRuntime (MUL-4257): returns@@ -7269,8 +7329,23 @@ WHERE id = (AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => $4::double precision)@@ -7373,8 +7448,23 @@ WHERE id IN (AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => $4::double precision)diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 1df629400b..b763d5f93d 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -788,8 +788,28 @@ WHERE id = (AND atq.runtime_id = @runtime_idAND atq.status = 'queued'AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ -- A task's persisted runtime is not authority after an agent rebind.+ AND a.runtime_id = atq.runtime_id+ -- Private runtimes only execute their owner's agents. Ownerless+ -- runtime/agent rows remain claimable only so the handler can+ -- settle them explicitly before daemon delivery; filtering them+ -- here would leave every task silently queued until the TTL.+ -- Public runtimes remain shareable across agent owners.+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => @runtime_stale_secs::double precision)@@ -877,8 +897,23 @@ WHERE id = (AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => @runtime_stale_secs::double precision)@@ -908,8 +943,23 @@ WHERE id IN (AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())AND EXISTS (- SELECT 1 FROM agent_runtime r- WHERE r.id = atq.runtime_id+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )AND r.status = 'online'AND COALESCE(r.last_seen_at, r.updated_at) >=now() - make_interval(secs => @runtime_stale_secs::double precision)@@ -2023,7 +2073,7 @@ WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC;-- name: ListQueuedClaimCandidatesByRuntime :many--- Returns rows the runtime can attempt to claim. Status is restricted to+-- Returns rows the runtime is authorized to attempt to claim. Status is restricted to-- 'queued' (in contrast to ListPendingTasksByRuntime which also includes-- 'dispatched') because dispatched rows are by definition already owned-- and cannot be re-claimed — including them in the candidate list pads@@ -2031,9 +2081,29 @@ ORDER BY priority DESC, created_at ASC;-- ClaimAgentTask, wasting CPU and a SELECT every poll cycle when the-- runtime is busy on a long-running task. Backed by the partial index-- idx_agent_task_queue_claim_candidates so the warm path is cheap.-SELECT * FROM agent_task_queue-WHERE runtime_id = $1 AND status = 'queued'-ORDER BY priority DESC, created_at ASC;+SELECT atq.* FROM agent_task_queue atq+WHERE atq.runtime_id = $1+ AND atq.status = 'queued'+ AND EXISTS (+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )+ )+ORDER BY atq.priority DESC, atq.created_at ASC;-- name: CancelSupersededDeferredRetriesForRuntimes :many-- Cancels deferred auto-retry rows that a newer active task has already@@ -2138,9 +2208,29 @@ RETURNING *;-- a sort step (each runtime's slice is index-ordered, but merging several-- runtimes' rows into one priority/FIFO order is not). The per-machine-- candidate set is small, so this is cheap in practice.-SELECT * FROM agent_task_queue-WHERE runtime_id = ANY(@runtime_ids::uuid[]) AND status = 'queued'-ORDER BY priority DESC, created_at ASC;+SELECT atq.* FROM agent_task_queue atq+WHERE atq.runtime_id = ANY(@runtime_ids::uuid[])+ AND atq.status = 'queued'+ AND EXISTS (+ -- Keep this authorization fence in sync with ClaimAgentTask.+ SELECT 1+ FROM agent a+ JOIN agent_runtime r ON r.id = atq.runtime_id+ WHERE a.id = atq.agent_id+ AND a.runtime_id = atq.runtime_id+ AND (+ r.visibility = 'public'+ OR (+ r.visibility = 'private'+ AND (+ r.owner_id IS NULL+ OR a.owner_id IS NULL+ OR r.owner_id = a.owner_id+ )+ )+ )+ )+ORDER BY atq.priority DESC, atq.created_at ASC;-- name: PromoteDueDeferredTasksForRuntimes :many-- Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all