Skip to content

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

Go

fix(agents): move pending tasks along when an agent switches runtime (#9960)

Jean Woodf88fdd08ec96
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 3cc07663f3..14ec6b2b57 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -2426,6 +2426,9 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
// as soon as a public runtime becomes private.
updateQueries := h.Queries
var bindingTx pgx.Tx
+ // Set when queued/deferred rows were re-stamped, so the new runtime's daemon
+ // is woken after commit instead of waiting out its empty-claim cache.
+ var pendingMovedTo pgtype.UUID
if req.RuntimeID != nil {
member, ok := h.workspaceMember(w, r, uuidToString(existing.WorkspaceID))
if !ok {
@@ -2460,6 +2463,31 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
return
}
params.RuntimeMode = pgtype.Text{String: runtime.RuntimeMode, Valid: true}
+
+ // Runtime row, then agent row: the order teardown and revocation use.
+ // FOR UPDATE waits out an enqueue holding the agent FOR KEY SHARE, so its
+ // row is committed with the old runtime before the re-stamp below sees it.
+ locked, err := updateQueries.GetAgentForUpdate(r.Context(), existing.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock agent")
+ return
+ }
+ if locked.RuntimeID != runtime.ID {
+ reassignment, err := updateQueries.ReassignPendingAgentTasksToRuntime(r.Context(), db.ReassignPendingAgentTasksToRuntimeParams{
+ AgentID: existing.ID,
+ NewRuntimeID: runtime.ID,
+ })
+ if err != nil {
+ slog.Warn("update agent: reassign pending tasks failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
+ writeError(w, http.StatusInternalServerError, "failed to move queued tasks to the new runtime")
+ return
+ }
+ if !reassignment.FenceOk {
+ writeError(w, http.StatusConflict, "the agent or runtime was removed while switching runtimes")
+ return
+ }
+ pendingMovedTo = runtime.ID
+ }
}
updated, err := updateQueries.UpdateAgent(r.Context(), params)
if err != nil {
@@ -2488,6 +2516,9 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to commit agent binding")
return
}
+ if pendingMovedTo.Valid {
+ h.TaskService.NotifyRuntimeMayHaveWork(pendingMovedTo)
+ }
}
// Nullable runtime overrides: null/empty in the request means explicitly
diff --git a/server/internal/handler/agent_runtime_switch_tasks_test.go b/server/internal/handler/agent_runtime_switch_tasks_test.go
new file mode 100644
index 0000000000..b5004ac532
--- /dev/null
+++ b/server/internal/handler/agent_runtime_switch_tasks_test.go
@@ -0,0 +1,107 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// taskRuntimes reads each task's runtime_id, keyed by task id.
+func taskRuntimes(t *testing.T, taskIDs ...string) map[string]string {
+ t.Helper()
+ out := make(map[string]string, len(taskIDs))
+ for _, id := range taskIDs {
+ var runtimeID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT runtime_id::text FROM agent_task_queue WHERE id = $1`, id).Scan(&runtimeID); err != nil {
+ t.Fatalf("read task %s runtime: %v", id, err)
+ }
+ out[id] = runtimeID
+ }
+ return out
+}
+
+func patchAgentRuntime(t *testing.T, agentID, runtimeID string) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPatch, "/api/agents/"+agentID, map[string]any{
+ "runtime_id": runtimeID,
+ }), "id", agentID)
+ testHandler.UpdateAgent(w, req)
+ return w
+}
+
+func TestUpdateAgent_RuntimeSwitch_MovesPendingTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ oldRuntimeID := dbfx.Runtime(t, "runtime-switch-tasks-old")
+ newRuntimeID := dbfx.Runtime(t, "runtime-switch-tasks-new")
+ agentID := dbfx.Agent(t, "runtime-switch-tasks-agent", oldRuntimeID)
+ issueID := dbfx.Issue(t, "runtime switch pending tasks")
+ queuedID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": oldRuntimeID, "issue_id": issueID})
+ deferredID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": oldRuntimeID, "issue_id": issueID, "status": "deferred",
+ })
+ runningID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": oldRuntimeID, "issue_id": issueID, "status": "running",
+ "dispatched_at": testutil.Raw("now()"), "started_at": testutil.Raw("now()"),
+ })
+ finishedID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": oldRuntimeID, "issue_id": issueID, "status": "completed",
+ "completed_at": testutil.Raw("now()"),
+ })
+
+ w := patchAgentRuntime(t, agentID, newRuntimeID)
+ if w.Code != http.StatusOK {
+ t.Fatalf("switch runtime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ got := taskRuntimes(t, queuedID, deferredID, runningID, finishedID)
+ want := map[string]string{
+ queuedID: newRuntimeID,
+ deferredID: newRuntimeID,
+ runningID: oldRuntimeID,
+ finishedID: oldRuntimeID,
+ }
+ for id, runtimeID := range want {
+ if got[id] != runtimeID {
+ t.Errorf("task %s runtime = %s, want %s", id, got[id], runtimeID)
+ }
+ }
+}
+
+func TestUpdateAgent_RuntimeSwitch_ForbiddenLeavesTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ suffix := time.Now().UnixNano()
+ strangerID := dbfx.User(t,
+ fmt.Sprintf("runtime-switch-stranger-%d", suffix),
+ fmt.Sprintf("runtime-switch-stranger-%[email protected]", suffix),
+ )
+ dbfx.Member(t, testWorkspaceID, strangerID, "member")
+ oldRuntimeID := dbfx.Runtime(t, "runtime-switch-forbidden-old")
+ strangerRuntimeID := dbfx.Runtime(t, "runtime-switch-forbidden-private", testutil.Cols{
+ "visibility": "private", "owner_id": strangerID,
+ })
+ agentID := dbfx.Agent(t, "runtime-switch-forbidden-agent", oldRuntimeID)
+ queuedID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": oldRuntimeID, "issue_id": dbfx.Issue(t, "runtime switch forbidden"),
+ })
+
+ w := patchAgentRuntime(t, agentID, strangerRuntimeID)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("switch to another member's private runtime: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := taskRuntimes(t, queuedID)[queuedID]; got != oldRuntimeID {
+ t.Fatalf("queued task runtime = %s, want unchanged %s", got, oldRuntimeID)
+ }
+}
diff --git a/server/internal/handler/runtime_delete_guidance_test.go b/server/internal/handler/runtime_delete_guidance_test.go
index 0b8b662250..7e5f14f617 100644
--- a/server/internal/handler/runtime_delete_guidance_test.go
+++ b/server/internal/handler/runtime_delete_guidance_test.go
@@ -631,8 +631,9 @@ func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {
}
}
-// Retention GC needs both no bound agents AND no unfinished task. An agent
-// rebound to another machine can leave a deferred run pinned to the old
+// Retention GC needs both no bound agents AND no unfinished task. A rebind
+// moves the agent's pending runs along, but a run enqueued concurrently with
+// the rebind, or left from before that move existed, can still sit on the old
// runtime, so "no agents bound" alone is not a cleanup promise this server can
// keep. Regression contributed by review.
func TestDeleteAgentRuntime_OfflineInstanceWithUnfinishedTaskDoesNotPromiseCleanup(t *testing.T) {
@@ -643,10 +644,6 @@ func TestDeleteAgentRuntime_OfflineInstanceWithUnfinishedTaskDoesNotPromiseClean
runtimeID, _ := createProfileBackedRuntime(t, ctx, "Review Retired Host")
agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Review Moved Agent")
issueID := dbfx.Issue(t, "Review deferred task")
- taskID := dbfx.Task(t, agentID, testutil.Cols{
- "runtime_id": runtimeID, "issue_id": issueID, "status": "deferred",
- "fire_at": testutil.Raw("now() + interval '30 days'"),
- })
targetID := newTestRuntime(t, "Review New Host", "online")
w := httptest.NewRecorder()
testHandler.UpdateAgent(w, withURLParam(newRequest("PATCH", "/api/agents/"+agentID,
@@ -654,6 +651,10 @@ func TestDeleteAgentRuntime_OfflineInstanceWithUnfinishedTaskDoesNotPromiseClean
if w.Code != http.StatusOK {
t.Fatalf("rebind: %d %s", w.Code, w.Body.String())
}
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "status": "deferred",
+ "fire_at": testutil.Raw("now() + interval '30 days'"),
+ })
dbfx.Exec(t, `UPDATE agent_runtime SET status='offline', last_seen_at=now()-interval '8 days' WHERE id=$1`, runtimeID)
var taskRuntime, taskStatus string
dbfx.QueryRow(t, `SELECT runtime_id::text, status FROM agent_task_queue WHERE id=$1`, taskID).Scan(&taskRuntime, &taskStatus)
diff --git a/server/internal/service/runtime_claim_access_test.go b/server/internal/service/runtime_claim_access_test.go
index 4350f37390..a43c254220 100644
--- a/server/internal/service/runtime_claim_access_test.go
+++ b/server/internal/service/runtime_claim_access_test.go
@@ -266,6 +266,79 @@ func TestClaimTaskRejectsMismatchedAgentRuntime(t *testing.T) {
}
}
+// A runtime switch must leave the agent's pending work claimable. Before the
+// re-stamp, a queued row on the old runtime matched neither daemon: the old one
+// fails the agent-binding fence, the new one fails the task-runtime filter.
+func TestRuntimeSwitchKeepsPendingTasksClaimable(t *testing.T) {
+ ctx := context.Background()
+ fixture := newRuntimeClaimAccessFixture(t, "public", true, true, "queued")
+ q := db.New(fixture.pool)
+ oldRuntimeID := fixture.runtimeID
+
+ var workspaceID, ownerID pgtype.UUID
+ if err := fixture.pool.QueryRow(ctx,
+ `SELECT workspace_id, owner_id FROM agent WHERE id = $1`, fixture.agentID,
+ ).Scan(&workspaceID, &ownerID); err != nil {
+ t.Fatalf("read agent: %v", err)
+ }
+ fx := testutil.New(fixture.pool, util.UUIDToString(workspaceID), util.UUIDToString(ownerID))
+ newRuntimeID := util.MustParseUUID(fx.Runtime(t, "switched-runtime", testutil.Cols{"visibility": "public"}))
+ agentID := util.UUIDToString(fixture.agentID)
+ deferredID := fx.Task(t, agentID, testutil.Cols{
+ "runtime_id": util.UUIDToString(oldRuntimeID), "issue_id": fx.Issue(t, "deferred work"), "status": "deferred",
+ })
+ runningID := fx.Task(t, agentID, testutil.Cols{
+ "runtime_id": util.UUIDToString(oldRuntimeID), "issue_id": fx.Issue(t, "running work"), "status": "running",
+ "dispatched_at": testutil.Raw("now()"), "started_at": testutil.Raw("now()"),
+ })
+
+ tx, err := fixture.pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ qtx := q.WithTx(tx)
+ if _, err := qtx.GetAgentForUpdate(ctx, fixture.agentID); err != nil {
+ t.Fatalf("lock agent: %v", err)
+ }
+ if _, err := tx.Exec(ctx, `UPDATE agent SET runtime_id = $2 WHERE id = $1`, fixture.agentID, newRuntimeID); err != nil {
+ t.Fatalf("rebind agent: %v", err)
+ }
+ reassignment, err := qtx.ReassignPendingAgentTasksToRuntime(ctx, db.ReassignPendingAgentTasksToRuntimeParams{
+ AgentID: fixture.agentID, NewRuntimeID: newRuntimeID,
+ })
+ if err != nil {
+ t.Fatalf("reassign: %v", err)
+ }
+ if !reassignment.FenceOk || reassignment.ReassignedTasks != 2 {
+ t.Fatalf("reassignment = %+v, want fence ok and 2 rows (queued + deferred)", reassignment)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit: %v", err)
+ }
+
+ svc := NewTaskService(q, fixture.pool, nil, events.New())
+ if claimed, err := svc.claimTask(ctx, fixture.agentID, oldRuntimeID, claimScope{claimPath: claimPathRuntime}); err != nil || claimed != nil {
+ t.Fatalf("old runtime claim = %+v, %v; want nothing", claimed, err)
+ }
+ claimed, err := svc.claimTask(ctx, fixture.agentID, newRuntimeID, claimScope{claimPath: claimPathRuntime})
+ if err != nil {
+ t.Fatalf("new runtime claim: %v", err)
+ }
+ if claimed == nil || util.UUIDToString(claimed.ID) != fixture.taskID {
+ t.Fatalf("new runtime claimed %+v, want queued task %s", claimed, fixture.taskID)
+ }
+
+ for id, want := range map[string]pgtype.UUID{deferredID: newRuntimeID, runningID: oldRuntimeID} {
+ var got pgtype.UUID
+ if err := fixture.pool.QueryRow(ctx, `SELECT runtime_id FROM agent_task_queue WHERE id = $1`, id).Scan(&got); err != nil {
+ t.Fatalf("read task %s: %v", id, err)
+ }
+ if got != want {
+ t.Errorf("task %s runtime = %s, want %s", id, util.UUIDToString(got), util.UUIDToString(want))
+ }
+ }
+}
+
func TestClaimTaskForRuntimeKeepsOwnerlessPrivateAgentClaimable(t *testing.T) {
ctx := context.Background()
fixture := newRuntimeClaimAccessFixture(t, "private", true, true, "queued")
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 4038101202..34c2cff1a4 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3640,8 +3640,9 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.U
// 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.
+ // loaded Agent before returning any payload. Runtime mutation paths settle
+ // the remaining queued rows: teardown and revocation cancel them, and
+ // UpdateAgent re-stamps them to the new runtime.
if runtimeID.Valid && agent.RuntimeID != runtimeID {
outcome = "runtime_mismatch"
return nil
@@ -7441,6 +7442,12 @@ func (s *TaskService) NotifyRuntimeCapacityChanged(runtimeID pgtype.UUID) {
s.notifyRuntimeMayHaveWork(runtimeID, "")
}
+// NotifyRuntimeMayHaveWork wakes a runtime's daemon after queued work was
+// moved onto it outside an enqueue, such as an agent runtime switch.
+func (s *TaskService) NotifyRuntimeMayHaveWork(runtimeID pgtype.UUID) {
+ s.notifyRuntimeMayHaveWork(runtimeID, "")
+}
+
// notifyTasksFinished is the batch form used by bulk terminal transitions.
// Coalesce by runtime so cancelling many tasks on one machine produces one
// cache bump and one websocket hint rather than a burst of identical work.
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 007dd97cd6..24c6d38e38 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -7757,6 +7757,50 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr
return items, nil
}
+const reassignPendingAgentTasksToRuntime = `-- name: ReassignPendingAgentTasksToRuntime :one
+WITH fence AS MATERIALIZED (
+ SELECT lock_task_owner_rows($1, NULL, $2) AS ok
+),
+reassigned AS (
+ UPDATE agent_task_queue
+ SET runtime_id = $2
+ WHERE agent_id = $1
+ AND status IN ('queued', 'deferred')
+ AND runtime_id IS DISTINCT FROM $2
+ AND (SELECT ok FROM fence)
+ RETURNING id
+)
+SELECT
+ (SELECT ok FROM fence) AS fence_ok,
+ (SELECT count(*) FROM reassigned) AS reassigned_tasks
+`
+
+type ReassignPendingAgentTasksToRuntimeParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ NewRuntimeID pgtype.UUID `json:"new_runtime_id"`
+}
+
+type ReassignPendingAgentTasksToRuntimeRow struct {
+ FenceOk bool `json:"fence_ok"`
+ ReassignedTasks int64 `json:"reassigned_tasks"`
+}
+
+// Moves an agent's not-yet-dispatched tasks to the runtime it was just rebound
+// to. Claims fence on agent.runtime_id = task.runtime_id (MUL-6697), so a
+// queued or deferred row left on the old runtime is claimable by neither
+// daemon. Deferred rows move too: promotion is per runtime and would otherwise
+// strand them later. Dispatched, running and waiting rows are already held by
+// the old runtime's daemon and stay. Callers hold the agent row FOR UPDATE.
+//
+// Same fence-verdict shape as ReassignTasksToRuntime: FenceOk = false must
+// abort the rebind rather than commit a binding with stranded rows.
+func (q *Queries) ReassignPendingAgentTasksToRuntime(ctx context.Context, arg ReassignPendingAgentTasksToRuntimeParams) (ReassignPendingAgentTasksToRuntimeRow, error) {
+ row := q.db.QueryRow(ctx, reassignPendingAgentTasksToRuntime, arg.AgentID, arg.NewRuntimeID)
+ var i ReassignPendingAgentTasksToRuntimeRow
+ err := row.Scan(&i.FenceOk, &i.ReassignedTasks)
+ return i, err
+}
+
const rebindAgentBuilderRuntime = `-- name: RebindAgentBuilderRuntime :one
UPDATE agent
SET runtime_id = $1,
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 415da1d7b5..decbb1e6cc 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -646,6 +646,32 @@ WHERE issue_id = $1 AND agent_id = $2
AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(sqlc.narg('thread_comment_id')::uuid)
RETURNING *;
+-- name: ReassignPendingAgentTasksToRuntime :one
+-- Moves an agent's not-yet-dispatched tasks to the runtime it was just rebound
+-- to. Claims fence on agent.runtime_id = task.runtime_id (MUL-6697), so a
+-- queued or deferred row left on the old runtime is claimable by neither
+-- daemon. Deferred rows move too: promotion is per runtime and would otherwise
+-- strand them later. Dispatched, running and waiting rows are already held by
+-- the old runtime's daemon and stay. Callers hold the agent row FOR UPDATE.
+--
+-- Same fence-verdict shape as ReassignTasksToRuntime: FenceOk = false must
+-- abort the rebind rather than commit a binding with stranded rows.
+WITH fence AS MATERIALIZED (
+ SELECT lock_task_owner_rows(@agent_id, NULL, @new_runtime_id) AS ok
+),
+reassigned AS (
+ UPDATE agent_task_queue
+ SET runtime_id = @new_runtime_id
+ WHERE agent_id = @agent_id
+ AND status IN ('queued', 'deferred')
+ AND runtime_id IS DISTINCT FROM @new_runtime_id
+ AND (SELECT ok FROM fence)
+ RETURNING id
+)
+SELECT
+ (SELECT ok FROM fence) AS fence_ok,
+ (SELECT count(*) FROM reassigned) AS reassigned_tasks;
+
-- name: CancelAgentTasksByAgent :many
-- Bulk-cancel every active (queued/dispatched/running) task for an agent.
-- Returns the affected rows so callers can broadcast task:cancelled events.