Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(tasks): serialize pending writes with runtime rebinding (#10801)
Multica Eve1c35d16909b7
diff --git a/server/cmd/server/runtime_gc_test.go b/server/cmd/server/runtime_gc_test.goindex a62ae8e822..f83cf31b5e 100644--- a/server/cmd/server/runtime_gc_test.go+++ b/server/cmd/server/runtime_gc_test.go@@ -499,7 +499,10 @@ func TestRuntimeGC_RuntimeLockRejectsConcurrentEnqueue(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "enqueue-race")- agentID := runtimeGCFixtureAgentID(t, ctx)+ // A bound agent now routes to its current runtime instead of this stale+ // hint. Use an unbound agent so the enqueue still targets the runtime+ // being deleted and exercises the owner fence's lock and refusal.+ agentID := testutil.New(testPool, testWorkspaceID, testUserID).Agent(t, "runtime-gc-enqueue-race", "")locked := make(chan struct{})proceed := make(chan struct{})diff --git a/server/internal/handler/agent_runtime_switch_tasks_test.go b/server/internal/handler/agent_runtime_switch_tasks_test.goindex b5004ac532..9a01b07689 100644--- a/server/internal/handler/agent_runtime_switch_tasks_test.go+++ b/server/internal/handler/agent_runtime_switch_tasks_test.go@@ -53,6 +53,14 @@ func TestUpdateAgent_RuntimeSwitch_MovesPendingTasks(t *testing.T) {"runtime_id": oldRuntimeID, "issue_id": issueID, "status": "running","dispatched_at": testutil.Raw("now()"), "started_at": testutil.Raw("now()"),})+ dispatchedID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": oldRuntimeID, "issue_id": dbfx.Issue(t, "dispatched during runtime switch"),+ "status": "dispatched", "dispatched_at": testutil.Raw("now()"),+ })+ waitingID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": oldRuntimeID, "issue_id": issueID, "status": "waiting_local_directory",+ "dispatched_at": testutil.Raw("now()"),+ })finishedID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": oldRuntimeID, "issue_id": issueID, "status": "completed","completed_at": testutil.Raw("now()"),@@ -63,12 +71,14 @@ func TestUpdateAgent_RuntimeSwitch_MovesPendingTasks(t *testing.T) {t.Fatalf("switch runtime: expected 200, got %d: %s", w.Code, w.Body.String())}- got := taskRuntimes(t, queuedID, deferredID, runningID, finishedID)+ got := taskRuntimes(t, queuedID, deferredID, runningID, dispatchedID, waitingID, finishedID)want := map[string]string{- queuedID: newRuntimeID,- deferredID: newRuntimeID,- runningID: oldRuntimeID,- finishedID: oldRuntimeID,+ queuedID: newRuntimeID,+ deferredID: newRuntimeID,+ runningID: oldRuntimeID,+ dispatchedID: oldRuntimeID,+ waitingID: oldRuntimeID,+ finishedID: oldRuntimeID,}for id, runtimeID := range want {if got[id] != runtimeID {diff --git a/server/internal/handler/task_enqueue_snapshot_test.go b/server/internal/handler/task_enqueue_snapshot_test.gonew file mode 100644index 0000000000..fcbf23ad24--- /dev/null+++ b/server/internal/handler/task_enqueue_snapshot_test.go@@ -0,0 +1,107 @@+package handler++import (+ "context"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// An INSERT can take its statement snapshot while the binding change is still+// uncommitted, then wait inside the owner fence. It must use the updated tuple+// after that wait, rather than persisting either the snapshot or caller's A.+func TestTaskEnqueueRefreshesBindingAfterLockWait(t *testing.T) {+ for _, kind := range []string{"issue", "deferred_issue", "quick_create", "chat", "autopilot", "wakeup"} {+ t.Run(kind, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ oldRuntime := dbfx.Runtime(t, "enqueue-snapshot-A")+ newRuntime := dbfx.Runtime(t, "enqueue-snapshot-B")+ agentID := dbfx.Agent(t, "enqueue-snapshot-agent", oldRuntime)+ issueID := dbfx.Issue(t, "enqueue binding snapshot")+ chatID := dbfx.ChatSession(t, agentID)+ dbfx.Cleanup(t, "DELETE FROM agent_task_queue WHERE agent_id=$1", agentID)+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ q := testHandler.Queries.WithTx(tx)+ if _, err := q.LockWorkspaceForChatSessionCreate(ctx, parseUUID(testWorkspaceID)); err != nil {+ t.Fatal(err)+ }+ if _, err := q.LockAgentRuntimeForAccessChange(ctx, parseUUID(newRuntime)); err != nil {+ t.Fatal(err)+ }+ if _, err := q.GetAgentForUpdate(ctx, parseUUID(agentID)); err != nil {+ t.Fatal(err)+ }+ if _, err := q.UpdateAgent(ctx, db.UpdateAgentParams{ID: parseUUID(agentID), RuntimeID: parseUUID(newRuntime)}); err != nil {+ t.Fatal(err)+ }++ type outcome struct {+ task db.AgentTaskQueue+ err error+ }+ result := make(chan outcome, 1)+ done := make(chan struct{})+ go func() {+ defer close(done)+ var task db.AgentTaskQueue+ var err error+ a, r, i := parseUUID(agentID), parseUUID(oldRuntime), parseUUID(issueID)+ switch kind {+ case "issue":+ task, err = testHandler.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{AgentID: a, RuntimeID: r, IssueID: i, Priority: 4})+ case "deferred_issue":+ task, err = testHandler.Queries.CreateDeferredChannelIssueTask(ctx, db.CreateDeferredChannelIssueTaskParams{+ AgentID: a, RuntimeID: r, IssueID: i, Priority: 4,+ FireAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},+ })+ case "quick_create":+ task, err = testHandler.Queries.CreateQuickCreateTask(ctx, db.CreateQuickCreateTaskParams{AgentID: a, RuntimeID: r, Priority: 4, Context: []byte(`{"type":"quick_create"}`)})+ case "chat":+ task, err = testHandler.Queries.CreateChatTask(ctx, db.CreateChatTaskParams{AgentID: a, RuntimeID: r, ChatSessionID: parseUUID(chatID), Priority: 4})+ case "autopilot":+ task, err = testHandler.Queries.CreateAutopilotTask(ctx, db.CreateAutopilotTaskParams{AgentID: a, RuntimeID: r, Priority: 4})+ case "wakeup":+ task, err = testHandler.Queries.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{AgentID: a, RuntimeID: r, IssueID: i, Priority: 4, WakeupContext: []byte(`{}`)})+ }+ result <- outcome{task, err}+ }()+ defer func() { tx.Rollback(context.Background()); cancel(); <-done }()+ for {+ select {+ case got := <-result:+ t.Fatalf("write completed before binding lock was released: %v", got.err)+ default:+ }+ var blocked bool+ if err := testPool.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND $1=ANY(pg_blocking_pids(pid)))", tx.Conn().PgConn().PID()).Scan(&blocked); err != nil {+ t.Fatal(err)+ }+ if blocked {+ break+ }+ select {+ case <-time.After(5 * time.Millisecond):+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ }+ if err := tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ got := <-result+ if got.err != nil {+ t.Fatal(got.err)+ }+ if got.task.RuntimeID != parseUUID(newRuntime) || got.task.Priority != 4 {+ t.Fatalf("task runtime=%s priority=%d, want B=%s priority=4", uuidToString(got.task.RuntimeID), got.task.Priority, newRuntime)+ }+ })+ }+}diff --git a/server/internal/handler/task_retry_rebind_race_test.go b/server/internal/handler/task_retry_rebind_race_test.gonew file mode 100644index 0000000000..2255b2c59e--- /dev/null+++ b/server/internal/handler/task_retry_rebind_race_test.go@@ -0,0 +1,156 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++type retryInsertGate struct {+ pool *pgxpool.Pool+ ready chan uint32+ resume chan struct{}+ once sync.Once+}++func (g *retryInsertGate) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := g.pool.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return &retryInsertGateTx{Tx: tx, gate: g}, nil+}++type retryInsertGateTx struct {+ pgx.Tx+ gate *retryInsertGate+}++func (tx *retryInsertGateTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ if strings.HasPrefix(sql, "-- name: CreateRetryTask :one") {+ tx.gate.once.Do(func() {+ tx.gate.ready <- tx.Conn().PgConn().PID()+ select {+ case <-tx.gate.resume:+ case <-ctx.Done():+ }+ })+ }+ return tx.Tx.QueryRow(ctx, sql, args...)+}++// The retry INSERT must already hold the agent binding stable. Otherwise+// UpdateAgent can sweep the queue and commit B before the retry writes A.+func TestRetryInsertSerializesWithRuntimeSwitch(t *testing.T) {+ for _, path := range []string{"FailTask", "MaybeRetryFailedTask"} {+ t.Run(path, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ oldRuntime := dbfx.Runtime(t, "retry-race-A")+ newRuntime := dbfx.Runtime(t, "retry-race-B")+ agentID := dbfx.Agent(t, "retry-race-agent", oldRuntime)+ parentID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": oldRuntime, "issue_id": dbfx.Issue(t, "retry during rebind"),+ "status": "dispatched", "attempt": 1, "max_attempts": 2,+ })+ dbfx.Cleanup(t, "DELETE FROM agent_task_queue WHERE parent_task_id=$1", parentID)+ if path == "MaybeRetryFailedTask" {+ dbfx.Exec(t, "UPDATE agent_task_queue SET status='failed', failure_reason='timeout' WHERE id=$1", parentID)+ }+ gate := &retryInsertGate{pool: testPool, ready: make(chan uint32, 1), resume: make(chan struct{})}+ svc := service.NewTaskService(testHandler.Queries, gate, nil, events.New())+ retryResult := make(chan error, 1)+ retryDone := make(chan struct{})+ go func() {+ defer close(retryDone)+ if path == "FailTask" {+ _, err := svc.FailTask(ctx, parseUUID(parentID), "prepare timeout", "", "", "", "timeout", false, "", "")+ retryResult <- err+ return+ }+ parent, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(parentID))+ if err == nil {+ _, err = svc.MaybeRetryFailedTask(ctx, parent)+ }+ retryResult <- err+ }()+ defer func() { cancel(); <-retryDone }()+ var retryPID uint32+ select {+ case retryPID = <-gate.ready:+ case err := <-retryResult:+ t.Fatalf("retry stopped before insert: %v", err)+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }++ req := withURLParam(newRequest(http.MethodPatch, "/api/agents/"+agentID, map[string]string{"runtime_id": newRuntime}).WithContext(ctx), "id", agentID)+ rebindResult := make(chan *httptest.ResponseRecorder, 1)+ rebindDone := make(chan struct{})+ go func() {+ defer close(rebindDone)+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, req)+ rebindResult <- w+ }()+ defer func() { cancel(); <-rebindDone }()++ var response *httptest.ResponseRecorder+ // Observe a real PostgreSQL lock wait, or the old broken switch+ // completing before the insert. No scheduler timing assumption.+ for response == nil {+ select {+ case response = <-rebindResult:+ default:+ }+ var blocked bool+ if err := testPool.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND $1=ANY(pg_blocking_pids(pid)))", retryPID).Scan(&blocked); err != nil {+ t.Fatal(err)+ }+ if blocked || response != nil {+ break+ }+ select {+ case <-time.After(5 * time.Millisecond):+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ }+ close(gate.resume)+ if err := <-retryResult; err != nil {+ t.Fatalf("retry: %v", err)+ }+ if response == nil {+ response = <-rebindResult+ }+ if response.Code != http.StatusOK {+ t.Fatalf("rebind: %d %s", response.Code, response.Body.String())+ }+ var childID string+ dbfx.QueryRow(t, "SELECT id::text FROM agent_task_queue WHERE parent_task_id=$1", parentID).Scan(&childID)+ if got := taskRuntimes(t, childID)[childID]; got != newRuntime {+ t.Fatalf("retry INSERT escaped the runtime switch: runtime=%s, want B=%s", got, newRuntime)+ }+ if old, err := svc.ClaimTaskForRuntime(ctx, parseUUID(oldRuntime)); err != nil || old != nil {+ t.Fatalf("old runtime claim=%+v/%v, want nothing", old, err)+ }+ claimed, err := svc.ClaimTaskForRuntime(ctx, parseUUID(newRuntime))+ if err != nil || claimed == nil || uuidToString(claimed.ID) != childID {+ t.Fatalf("new runtime claim=%+v/%v, want retry %s", claimed, err, childID)+ }+ if again, err := svc.ClaimTaskForRuntime(ctx, parseUUID(newRuntime)); err != nil || again != nil {+ t.Fatalf("duplicate claim=%+v/%v", again, err)+ }+ })+ }+}diff --git a/server/internal/handler/task_runtime_binding_test.go b/server/internal/handler/task_runtime_binding_test.gonew file mode 100644index 0000000000..300e2d4c01--- /dev/null+++ b/server/internal/handler/task_runtime_binding_test.go@@ -0,0 +1,192 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Hold an enqueue after its application-level binding read but before SQL.+// The database must resolve and lock the current binding when the write lands.+type mul9393EnqueueGate struct {+ db.DBTX+ entered chan struct{}+ resume chan struct{}+}++func (g *mul9393EnqueueGate) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {+ if strings.HasPrefix(query, "-- name: CreateAgentTask :one") {+ close(g.entered)+ select {+ case <-g.resume:+ case <-ctx.Done():+ }+ }+ return g.DBTX.QueryRow(ctx, query, args...)+}++func TestEnqueueAfterRuntimeSwitchUsesCurrentBinding(t *testing.T) {+ for _, provider := range []string{"claude", "codex"} {+ t.Run("claude_to_"+provider, func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ oldRuntime := dbfx.Runtime(t, "mul9393-enqueue-A", testutil.Cols{"provider": "claude"})+ newRuntime := dbfx.Runtime(t, "mul9393-enqueue-B", testutil.Cols{"provider": provider})+ agentID := dbfx.Agent(t, "mul9393-enqueue-agent", oldRuntime)+ issueID := dbfx.Issue(t, "enqueue concurrent with rebind", testutil.Cols{"assignee_type": "agent", "assignee_id": agentID})+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE agent_id=$1`, agentID)+ gate := &mul9393EnqueueGate{DBTX: testPool, entered: make(chan struct{}), resume: make(chan struct{})}+ svc := service.NewTaskService(db.New(gate), testPool, nil, events.New())+ type outcome struct {+ task db.AgentTaskQueue+ err error+ }+ result := make(chan outcome, 1)+ done := make(chan struct{})+ go func() {+ defer close(done)+ task, err := svc.EnqueueTaskForIssueByActor(ctx, issue, parseUUID(testUserID))+ result <- outcome{task, err}+ }()+ defer func() { cancel(); <-done }()+ select {+ case <-gate.entered:+ case got := <-result:+ t.Fatalf("enqueue returned before insert barrier: %v", got.err)+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ // Enqueue has loaded A and built its insert arguments. Commit the+ // real UpdateAgent request before letting that insert acquire locks.+ w := patchAgentRuntime(t, agentID, newRuntime)+ if w.Code != http.StatusOK {+ t.Fatalf("rebind: %d %s", w.Code, w.Body.String())+ }+ close(gate.resume)+ got := <-result+ if got.err != nil {+ t.Fatalf("enqueue: %v", got.err)+ }+ // Use the ordinary service after the gated enqueue has completed.+ _, duplicateErr := testHandler.TaskService.EnqueueTaskForIssueByActor(ctx, issue, parseUUID(testUserID))+ if !errors.Is(duplicateErr, service.ErrDuplicatePendingTask) {+ t.Fatalf("second enqueue: %v, want pending-task dedup", duplicateErr)+ }+ oldClaim, oldErr := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(oldRuntime))+ newClaim, newErr := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(newRuntime))+ var binding, taskRuntime, status string+ dbfx.QueryRow(t, `SELECT a.runtime_id::text, q.runtime_id::text, q.status FROM agent a JOIN agent_task_queue q ON q.agent_id=a.id WHERE q.id=$1`, got.task.ID).Scan(&binding, &taskRuntime, &status)+ t.Logf("agent_runtime=%s B=%s task_runtime=%s A=%s status=%s old_claim=%v/%v new_claim=%v/%v duplicate=%v", binding, newRuntime, taskRuntime, oldRuntime, status, oldClaim != nil, oldErr, newClaim != nil, newErr, duplicateErr)+ if oldErr != nil || newErr != nil || oldClaim != nil {+ t.Fatalf("claim errors or stale-runtime claim: old=%v/%v new=%v/%v", oldClaim, oldErr, newClaim, newErr)+ }+ if newClaim == nil {+ t.Errorf("successful enqueue after committed rebind is stranded; B should claim it")+ }+ })+ }+}++func TestRequeueClaimAfterRuntimeSwitch(t *testing.T) {+ ctx := context.Background()+ oldRuntime := dbfx.Runtime(t, "mul9393-requeue-A")+ newRuntime := dbfx.Runtime(t, "mul9393-requeue-B")+ agentID := dbfx.Agent(t, "mul9393-requeue-agent", oldRuntime)+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": oldRuntime, "issue_id": dbfx.Issue(t, "claim failure after rebind"),+ "priority": 4, "attempt": 2, "max_attempts": 3,+ "session_id": "prior-session", "work_dir": "/prior/workdir",+ })+ claimed, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(oldRuntime))+ if err != nil || claimed == nil || uuidToString(claimed.ID) != taskID {+ t.Fatalf("claim: %+v %v", claimed, err)+ }+ w := patchAgentRuntime(t, agentID, newRuntime)+ if w.Code != http.StatusOK {+ t.Fatalf("rebind: %d %s", w.Code, w.Body.String())+ }+ // This recovery is used when token/receipt finalization fails before+ // the claim response is delivered. It puts the same generation back.+ requeued, err := testHandler.TaskService.RequeueTaskAfterClaimFailure(ctx, *claimed)+ if err != nil || requeued == nil {+ t.Fatalf("requeue: %+v %v", requeued, err)+ }+ if requeued.ID != claimed.ID || requeued.Priority != claimed.Priority ||+ requeued.Attempt != claimed.Attempt || requeued.MaxAttempts != claimed.MaxAttempts ||+ requeued.CreatedAt != claimed.CreatedAt || requeued.SessionID != claimed.SessionID ||+ requeued.WorkDir != claimed.WorkDir {+ t.Fatal("requeue changed task identity, ordering, retry budget, or continuity pointers")+ }+ oldClaim, oldErr := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(oldRuntime))+ newClaim, newErr := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(newRuntime))+ t.Logf("requeued_status=%s requeued_runtime=%s A=%s B=%s old_claim=%v/%v new_claim=%v/%v", requeued.Status, uuidToString(requeued.RuntimeID), oldRuntime, newRuntime, oldClaim != nil, oldErr, newClaim != nil, newErr)+ if oldErr != nil || newErr != nil || oldClaim != nil {+ t.Fatal("claim error or stale-runtime claim")+ }+ if newClaim == nil {+ t.Fatal("undelivered dispatch requeued after rebind is stranded on A")+ }+ testutil.Call(t, testHandler.StartTask, startClaimRequest(taskID, oldRuntime, claimed.DispatchedAt.Time)).Want(http.StatusConflict)+ testutil.Call(t, testHandler.StartTask, startClaimRequest(taskID, newRuntime, newClaim.DispatchedAt.Time)).Want(http.StatusOK)+}++func TestConcurrentClaimsAfterRuntimeSwitch(t *testing.T) {+ ctx := context.Background()+ oldRuntime := dbfx.Runtime(t, "mul9393-claim-A")+ newRuntime := dbfx.Runtime(t, "mul9393-claim-B")+ agentID := dbfx.Agent(t, "mul9393-claim-agent", oldRuntime)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": oldRuntime, "issue_id": dbfx.Issue(t, "concurrent claim after rebind")})+ w := patchAgentRuntime(t, agentID, newRuntime)+ if w.Code != http.StatusOK {+ t.Fatalf("rebind: %d %s", w.Code, w.Body.String())+ }+ type outcome struct {+ runtime string+ task *db.AgentTaskQueue+ err error+ }+ start := make(chan struct{})+ results := make(chan outcome, 8)+ for i := 0; i < 8; i++ {+ runtime := oldRuntime+ if i%2 == 0 {+ runtime = newRuntime+ }+ go func(runtime string) {+ <-start+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(runtime))+ results <- outcome{runtime, task, err}+ }(runtime)+ }+ close(start)+ claims := 0+ for i := 0; i < 8; i++ {+ got := <-results+ if got.err != nil {+ t.Errorf("claim: %v", got.err)+ }+ if got.task != nil {+ claims+++ if got.runtime != newRuntime || uuidToString(got.task.ID) != taskID {+ t.Errorf("wrong owner or task: %+v", got)+ }+ }+ }+ if claims != 1 {+ t.Errorf("claims=%d, want exactly 1 on B", claims)+ }+ t.Logf("simultaneous polls=8 total_claims=%d; original queued task migrated to B", claims)+}diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.goindex ee43dcc2bb..eeb8d6070c 100644--- a/server/internal/handler/workspace_delete_fence_test.go+++ b/server/internal/handler/workspace_delete_fence_test.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -71,6 +72,9 @@ func TestTaskWriteFence_BlocksOnWorkspaceLockAlone(t *testing.T) {}ctx := context.Background()f := newWorkspaceDeletePathFixture(t, "fenceonly")+ // A bound agent ignores a stale runtime hint. With no binding, the hint+ // remains the write's target, so this still isolates the runtime's fence.+ unboundAgent := testutil.New(testPool, f.neighbourID, testUserID).Agent(t, "fence-runtime-only", "")holder, err := testPool.Begin(ctx)if err != nil {@@ -106,7 +110,7 @@ func TestTaskWriteFence_BlocksOnWorkspaceLockAlone(t *testing.T) {}blockedEnqueue("enqueue via the victim's agent", f.victimAgent, f.neighbourRuntime, f.neighbourIssue)- blockedEnqueue("enqueue via the victim's runtime", f.neighbourAgent, f.victimRuntime, f.neighbourIssue)+ blockedEnqueue("enqueue via the victim's runtime", unboundAgent, f.victimRuntime, f.neighbourIssue)blockedEnqueue("enqueue via the victim's issue", f.neighbourAgent, f.neighbourRuntime, f.victimIssue)// Reassignment onto the victim's runtime is fenced too.diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 5b40c5b85a..fdb5473d4c 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1833,6 +1833,9 @@ func (s *TaskService) RetrySourceContextQuickCreate(ctx context.Context, workspaif err != nil || locked.ID != contextID {return nil, ErrSourceContextRetryUnavailable}+ if _, err := qtx.LockAgentForTaskEnqueue(ctx, parent.AgentID); err != nil {+ return nil, fmt.Errorf("lock source context retry agent: %w", err)+ }child, err := qtx.CreateManualQuickCreateRetryTask(ctx, db.CreateManualQuickCreateRetryTaskParams{ActorUserID: requesterID,RuntimeMcpOverlay: overlay.Overlay,@@ -5494,14 +5497,18 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.}}if createRetry {- child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{- NewTaskID: dbid.NewV7(),- ID: taskID,- FireAt: retryFireAt,- MaxAttempts: retryMaxAttempts,- RuntimeMcpOverlay: retryOverlay.Overlay,- RuntimeConnectedApps: retryOverlay.ConnectedApps,- })+ var child db.AgentTaskQueue+ _, cerr := qtx.LockAgentForTaskEnqueue(ctx, t.AgentID)+ if cerr == nil {+ child, cerr = qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{+ NewTaskID: dbid.NewV7(),+ ID: taskID,+ FireAt: retryFireAt,+ MaxAttempts: retryMaxAttempts,+ RuntimeMcpOverlay: retryOverlay.Overlay,+ RuntimeConnectedApps: retryOverlay.ConnectedApps,+ })+ }switch {case cerr == nil:transferErr := transferPendingSourceContextToRetry(ctx, qtx, t, child)@@ -6000,14 +6007,18 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT}return nil, err}- child, err := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{- NewTaskID: dbid.NewV7(),- ID: parent.ID,- FireAt: retryFireAt,- MaxAttempts: pgtype.Int4{Int32: retryAttemptCeiling(reason, parent.MaxAttempts), Valid: true},- RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,- RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,- })+ var child db.AgentTaskQueue+ _, err = qtx.LockAgentForTaskEnqueue(ctx, parent.AgentID)+ if err == nil {+ child, err = qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{+ NewTaskID: dbid.NewV7(),+ ID: parent.ID,+ FireAt: retryFireAt,+ MaxAttempts: pgtype.Int4{Int32: retryAttemptCeiling(reason, parent.MaxAttempts), Valid: true},+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,+ })+ }if errors.Is(err, pgx.ErrNoRows) {// Workspace torn down, or the pending slot was taken between the check// above and this insert. Same contract as FailTask's path: no retry, nodiff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 40b7d5b4e1..d8b4096c4d 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -2264,6 +2264,13 @@ func (q *Queries) CreateAgentBuilder(ctx context.Context, arg CreateAgentBuilder}const createAgentTask = `-- name: CreateAgentTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $27::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $27::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -2272,28 +2279,29 @@ INSERT INTO agent_task_queue (workflow_step, fire_at, id)SELECT- $1, $2, $3,- CASE WHEN $5::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,- $4, $6,- COALESCE($7::uuid[], '{}'),- $8,+ $1, enqueue_agent.runtime_id, $2,+ CASE WHEN $3::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,+ $4, $5,+ COALESCE($6::uuid[], '{}'),+ $7,+ COALESCE($8::boolean, FALSE),COALESCE($9::boolean, FALSE),- COALESCE($10::boolean, FALSE),+ $10,$11,- $12,NULLIF(CASE- WHEN COALESCE($13::text, '') <> ''- THEN jsonb_build_object('head_sha', $13::text)+ WHEN COALESCE($12::text, '') <> ''+ THEN jsonb_build_object('head_sha', $12::text)ELSE '{}'::jsonbEND || CASE- WHEN COALESCE($14::boolean, FALSE)+ WHEN COALESCE($13::boolean, FALSE)THEN '{"fresh_rerun":true}'::jsonbELSE '{}'::jsonbEND || CASE- WHEN $15::bigint IS NOT NULL- THEN jsonb_build_object('workflow_handoff_revision', $15::bigint)+ WHEN $14::bigint IS NOT NULL+ THEN jsonb_build_object('workflow_handoff_revision', $14::bigint)ELSE '{}'::jsonbEND, '{}'::jsonb),+ $15,$16,$17,$18,@@ -2303,21 +2311,19 @@ SELECT$22,$23,$24,- $25,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- COALESCE($26::text, (SELECT i.status FROM issue i WHERE i.id = $3)),- $5,- COALESCE($27::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+ COALESCE($25::text, (SELECT i.status FROM issue i WHERE i.id = $2)),+ $3,+ COALESCE($26::uuid, gen_random_uuid())+FROM enqueue_agentRETURNING 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, workflow_step`type CreateAgentTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`IssueID pgtype.UUID `json:"issue_id"`- Priority int32 `json:"priority"`FireAt pgtype.Timestamptz `json:"fire_at"`+ Priority int32 `json:"priority"`TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`TriggerSummary pgtype.Text `json:"trigger_summary"`@@ -2340,6 +2346,7 @@ type CreateAgentTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`WorkflowStep pgtype.Text `json:"workflow_step"`ID pgtype.UUID `json:"id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -2364,13 +2371,14 @@ type CreateAgentTaskParams struct {// Workflow handoffs pass their original step and source revision explicitly.// A fire_at value admits a durable deferred task outside the pending slot;// existing callers omit it and continue to insert queued tasks.+// Lock the selected agent tuple so a rebind that commits during the owner-fence+// wait refreshes the runtime used by INSERT. Materialize that locked route once.func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createAgentTask,arg.AgentID,- arg.RuntimeID,arg.IssueID,- arg.Priority,arg.FireAt,+ arg.Priority,arg.TriggerCommentID,arg.CoalescedCommentIds,arg.TriggerSummary,@@ -2393,6 +2401,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.TriggerEvidenceRefID,arg.WorkflowStep,arg.ID,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(@@ -2461,6 +2470,13 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams}const createDeferredChannelIssueTask = `-- name: CreateDeferredChannelIssueTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $24::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $24::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -2470,17 +2486,18 @@ INSERT INTO agent_task_queue (workflow_step, id)SELECT- $1, $2, $3, 'deferred', $4, $5,- COALESCE($6::uuid[], '{}'),- $7,+ $1, enqueue_agent.runtime_id, $2, 'deferred', $3, $4,+ COALESCE($5::uuid[], '{}'),+ $6,+ COALESCE($7::boolean, FALSE),COALESCE($8::boolean, FALSE),- COALESCE($9::boolean, FALSE),+ $9,$10,- $11,jsonb_strip_nulls(jsonb_build_object(- 'head_sha', NULLIF(COALESCE($12::text, ''), ''),+ 'head_sha', NULLIF(COALESCE($11::text, ''), ''),'channel_issue_media_pending', TRUE)),+ $12,$13,$14,$15,@@ -2491,17 +2508,15 @@ SELECT$20,$21,$22,- $23,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- (SELECT i.status FROM issue i WHERE i.id = $3),- COALESCE($24::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+ (SELECT i.status FROM issue i WHERE i.id = $2),+ COALESCE($23::uuid, gen_random_uuid())+FROM enqueue_agentRETURNING 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, workflow_step`type CreateDeferredChannelIssueTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`IssueID pgtype.UUID `json:"issue_id"`Priority int32 `json:"priority"`TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`@@ -2524,6 +2539,7 @@ type CreateDeferredChannelIssueTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`FireAt pgtype.Timestamptz `json:"fire_at"`ID pgtype.UUID `json:"id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -2536,7 +2552,6 @@ type CreateDeferredChannelIssueTaskParams struct {func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg CreateDeferredChannelIssueTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createDeferredChannelIssueTask,arg.AgentID,- arg.RuntimeID,arg.IssueID,arg.Priority,arg.TriggerCommentID,@@ -2559,6 +2574,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Createarg.TriggerEvidenceRefID,arg.FireAt,arg.ID,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(@@ -2744,6 +2760,13 @@ func (q *Queries) CreateManualQuickCreateRetryTask(ctx context.Context, arg Crea}const createQuickCreateTask = `-- name: CreateQuickCreateTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $12::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, $12::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,@@ -2751,22 +2774,21 @@ INSERT INTO agent_task_queue (id)SELECT- $1, $2, NULL, 'queued', $3, $4,+ $1, enqueue_agent.runtime_id, NULL, 'queued', $2, $3,+ $4,$5,$6,$7,$8,$9,$10,- $11,- COALESCE($12::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, NULL, $2)+ COALESCE($11::uuid, gen_random_uuid())+FROM enqueue_agentRETURNING 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, workflow_step`type CreateQuickCreateTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`Priority int32 `json:"priority"`Context []byte `json:"context"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`@@ -2777,6 +2799,7 @@ type CreateQuickCreateTaskParams struct {TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`ID pgtype.UUID `json:"id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -2792,7 +2815,6 @@ type CreateQuickCreateTaskParams struct {func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreateTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createQuickCreateTask,arg.AgentID,- arg.RuntimeID,arg.Priority,arg.Context,arg.OriginatorUserID,@@ -2803,6 +2825,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreaarg.TriggerEvidenceKind,arg.TriggerEvidenceRefID,arg.ID,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(@@ -6959,6 +6982,23 @@ func (q *Queries) LockAgentForAutopilotAssignment(ctx context.Context, arg LockAreturn i, err}+const lockAgentForTaskEnqueue = `-- name: LockAgentForTaskEnqueue :one+SELECT a.id FROM agent a+WHERE a.id = $1 AND lock_task_owner_rows(a.id, NULL, NULL)+FOR KEY SHARE OF a+`++// Retry INSERTs resolve their route in a subsequent statement, so lock before+// that statement takes its snapshot. The workspace fence keeps the lock order+// compatible with teardown. UpdateAgent waits for this lock before sweeping+// queued/deferred rows; claims still enforce the current binding.+func (q *Queries) LockAgentForTaskEnqueue(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockAgentForTaskEnqueue, id)+ var id_2 pgtype.UUID+ err := row.Scan(&id_2)+ return id_2, err+}+const lockAgentTaskStartClaim = `-- name: LockAgentTaskStartClaim :oneSELECT 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, workflow_step FROM agent_task_queueWHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3@@ -8528,17 +8568,27 @@ func (q *Queries) RegisterPlannedCommentForActiveTask(ctx context.Context, arg R}const requeueAgentTaskAfterClaimFailure = `-- name: RequeueAgentTaskAfterClaimFailure :one-UPDATE agent_task_queue+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, a.runtime_id FROM agent a+ WHERE a.id = (SELECT agent_id FROM agent_task_queue WHERE id = $1)+ AND lock_task_owner_rows(a.id, NULL, NULL)+ FOR KEY SHARE OF a+)+UPDATE agent_task_queue AS taskSET status = 'queued',+ runtime_id = COALESCE(enqueue_agent.runtime_id, task.runtime_id),dispatched_at = NULL,prepare_lease_expires_at = NULL,delivered_comment_ids = '{}'-WHERE id = $1- AND runtime_id = $2- AND status = 'dispatched'- AND started_at IS NULL- AND dispatched_at = $3-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, workflow_step+FROM enqueue_agent+WHERE task.id = $1+ AND task.agent_id = enqueue_agent.id+ AND task.runtime_id = $2+ AND task.status = 'dispatched'+ AND task.started_at IS NULL+ AND task.dispatched_at = $3+ AND lock_task_owner_rows(task.agent_id, task.issue_id, COALESCE(enqueue_agent.runtime_id, task.runtime_id))+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step`type RequeueAgentTaskAfterClaimFailureParams struct {@@ -8552,6 +8602,8 @@ type RequeueAgentTaskAfterClaimFailureParams struct {// queue so another poll can retry immediately instead of waiting for stale// dispatch recovery. The dispatched_at CAS prevents an old handler from// rolling back a newer reclaim.+// An undelivered claim follows the current binding when returned to the queue.+// Lock the agent before the task, as the binding transaction does.func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg RequeueAgentTaskAfterClaimFailureParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, requeueAgentTaskAfterClaimFailure, arg.TaskID, arg.RuntimeID, arg.DispatchedAt)var i AgentTaskQueuediff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 08c20f1855..ff090b54bd 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -284,6 +284,13 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunconst createAutopilotTask = `-- name: CreateAutopilotTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $12::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, $12::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,originator_user_id, accountable_user_id, rule_version_id,@@ -291,21 +298,20 @@ INSERT INTO agent_task_queue (id)SELECT- $1, $2, NULL, 'queued', $3, $4, $5,+ $1, enqueue_agent.runtime_id, NULL, 'queued', $2, $3, $4,+ $5,$6,$7,$8,$9,$10,- $11,- COALESCE($12::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, NULL, $2)+ COALESCE($11::uuid, gen_random_uuid())+FROM enqueue_agentRETURNING 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, workflow_step`type CreateAutopilotTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`Priority int32 `json:"priority"`AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`TriggerSummary pgtype.Text `json:"trigger_summary"`@@ -316,6 +322,7 @@ type CreateAutopilotTaskParams struct {TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`ID pgtype.UUID `json:"id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// =====================@@ -340,7 +347,6 @@ type CreateAutopilotTaskParams struct {func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createAutopilotTask,arg.AgentID,- arg.RuntimeID,arg.Priority,arg.AutopilotRunID,arg.TriggerSummary,@@ -351,6 +357,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTaarg.TriggerEvidenceKind,arg.TriggerEvidenceRefID,arg.ID,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex b5a47e6c34..b33abc5468 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -376,6 +376,13 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa}const createChatTask = `-- name: CreateChatTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $17::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, $17::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id,initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,@@ -383,32 +390,31 @@ INSERT INTO agent_task_queue (fire_at, channel_context_revision, id, context)SELECT- $1, $2, NULL,- CASE WHEN $6::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,+ $1, enqueue_agent.runtime_id, NULL,+ CASE WHEN $2::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,$3, $4, $5,+ $6,$7,- $8,- COALESCE($9::boolean, FALSE),+ COALESCE($8::boolean, FALSE),+ $9,$10,$11,$12,$13,- $14,- $6::timestamptz,- $15::bigint,- COALESCE($16::uuid, gen_random_uuid()),- $17::jsonb-WHERE lock_task_owner_rows($1, NULL, $2)+ $2::timestamptz,+ $14::bigint,+ COALESCE($15::uuid, gen_random_uuid()),+ $16::jsonb+FROM enqueue_agentRETURNING 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, workflow_step`type CreateChatTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`+ FireAt pgtype.Timestamptz `json:"fire_at"`Priority int32 `json:"priority"`ChatSessionID pgtype.UUID `json:"chat_session_id"`InitiatorUserID pgtype.UUID `json:"initiator_user_id"`- FireAt pgtype.Timestamptz `json:"fire_at"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`AccountableUserID pgtype.UUID `json:"accountable_user_id"`ForceFreshSession pgtype.Bool `json:"force_fresh_session"`@@ -420,6 +426,7 @@ type CreateChatTaskParams struct {ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`ID pgtype.UUID `json:"id"`Context []byte `json:"context"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -432,11 +439,10 @@ type CreateChatTaskParams struct {func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createChatTask,arg.AgentID,- arg.RuntimeID,+ arg.FireAt,arg.Priority,arg.ChatSessionID,arg.InitiatorUserID,- arg.FireAt,arg.OriginatorUserID,arg.AccountableUserID,arg.ForceFreshSession,@@ -448,6 +454,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)arg.ChannelContextRevision,arg.ID,arg.Context,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.goindex 5fbd0c004a..4d2fc51c9b 100644--- a/server/pkg/db/generated/wakeup.sql.go+++ b/server/pkg/db/generated/wakeup.sql.go@@ -370,6 +370,13 @@ func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupPa}const createWakeupTask = `-- name: CreateWakeupTask :one+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, $24::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = $1+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $24::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -378,18 +385,19 @@ INSERT INTO agent_task_queue (workflow_step, id)SELECT- $1, $2, $3, 'queued', $4, $5,- COALESCE($6::uuid[], '{}'),- $7,+ $1, enqueue_agent.runtime_id, $2, 'queued', $3, $4,+ COALESCE($5::uuid[], '{}'),+ $6,+ COALESCE($7::boolean, FALSE),COALESCE($8::boolean, FALSE),- COALESCE($9::boolean, FALSE),+ $9,$10,- $11,CASE- WHEN COALESCE($12::text, '') <> ''- THEN jsonb_build_object('head_sha', $12::text)+ WHEN COALESCE($11::text, '') <> ''+ THEN jsonb_build_object('head_sha', $11::text)ELSE '{}'::jsonb- END || $13::jsonb,+ END || $12::jsonb,+ $13,$14,$15,$16,@@ -399,23 +407,21 @@ SELECT$20,$21,$22,- $23,-- The workflow step this run works on (MUL-7420). A wakeup continues the-- run that registered it, so it keeps that run's step: a status change it-- makes after someone else moved the issue is refused like the run's own-- would be. A wakeup a member registered starts from the issue's status.COALESCE(- (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = $19 AND s.issue_id = $3),- (SELECT i.status FROM issue i WHERE i.id = $3)+ (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = $18 AND s.issue_id = $2),+ (SELECT i.status FROM issue i WHERE i.id = $2)),- COALESCE($24::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+ COALESCE($23::uuid, gen_random_uuid())+FROM enqueue_agentRETURNING 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, workflow_step`type CreateWakeupTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`IssueID pgtype.UUID `json:"issue_id"`Priority int32 `json:"priority"`TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`@@ -438,6 +444,7 @@ type CreateWakeupTaskParams struct {TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`ID pgtype.UUID `json:"id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -461,7 +468,6 @@ type CreateWakeupTaskParams struct {func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createWakeupTask,arg.AgentID,- arg.RuntimeID,arg.IssueID,arg.Priority,arg.TriggerCommentID,@@ -484,6 +490,7 @@ func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskParaarg.TriggerEvidenceKind,arg.TriggerEvidenceRefID,arg.ID,+ arg.RuntimeID,)var i AgentTaskQueueerr := row.Scan(diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 8d6d9fd882..109eac2fbe 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -34,6 +34,15 @@ SELECT * FROM agentWHERE id = $1FOR UPDATE;+-- name: LockAgentForTaskEnqueue :one+-- Retry INSERTs resolve their route in a subsequent statement, so lock before+-- that statement takes its snapshot. The workspace fence keeps the lock order+-- compatible with teardown. UpdateAgent waits for this lock before sweeping+-- queued/deferred rows; claims still enforce the current binding.+SELECT a.id FROM agent a+WHERE a.id = $1 AND lock_task_owner_rows(a.id, NULL, NULL)+FOR KEY SHARE OF a;+-- name: GetAgentInWorkspace :oneSELECT * FROM agentWHERE id = $1 AND workspace_id = $2 AND kind = 'user';@@ -339,6 +348,15 @@ LIMIT @page_limit;-- Workflow handoffs pass their original step and source revision explicitly.-- A fire_at value admits a durable deferred task outside the pending slot;-- existing callers omit it and continue to insert queued tasks.+-- Lock the selected agent tuple so a rebind that commits during the owner-fence+-- wait refreshes the runtime used by INSERT. Materialize that locked route once.+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, sqlc.narg(issue_id), COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -347,9 +365,9 @@ INSERT INTO agent_task_queue (workflow_step, fire_at, id)SELECT- $1, $2, $3,+ sqlc.arg(agent_id), enqueue_agent.runtime_id, sqlc.narg(issue_id),CASE WHEN sqlc.narg(fire_at)::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,- $4, sqlc.narg(trigger_comment_id),+ sqlc.arg(priority), sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),@@ -380,10 +398,10 @@ SELECTsqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- COALESCE(sqlc.narg(workflow_step)::text, (SELECT i.status FROM issue i WHERE i.id = $3)),+ COALESCE(sqlc.narg(workflow_step)::text, (SELECT i.status FROM issue i WHERE i.id = sqlc.narg(issue_id))),sqlc.narg(fire_at),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+FROM enqueue_agentRETURNING *;-- name: CreateDeferredChannelIssueTask :one@@ -394,6 +412,13 @@ RETURNING *;-- Channel /issue media resolves after issue creation. Persist the assigned-- issue task up front for crash safety, but keep it inert until attachment-- binding settles or the fire_at fallback is promoted by the normal sweeper.+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, sqlc.narg(issue_id), COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -403,7 +428,7 @@ INSERT INTO agent_task_queue (workflow_step, id)SELECT- $1, $2, $3, 'deferred', $4, sqlc.narg(trigger_comment_id),+ sqlc.arg(agent_id), enqueue_agent.runtime_id, sqlc.narg(issue_id), 'deferred', sqlc.arg(priority), sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),@@ -426,9 +451,9 @@ SELECTsqlc.narg(trigger_evidence_ref_id),@fire_at,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- (SELECT i.status FROM issue i WHERE i.id = $3),+ (SELECT i.status FROM issue i WHERE i.id = sqlc.narg(issue_id)),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+FROM enqueue_agentRETURNING *;-- name: PromoteDeferredChannelIssueTask :one@@ -463,6 +488,13 @@ WHERE id = @id-- The requester who opened the quick-create modal is a direct_human originator-- and accountable; attribution provenance is stamped so this path is not a-- NULL-source enqueue bypass (MUL-4302 §2).+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,@@ -470,7 +502,7 @@ INSERT INTO agent_task_queue (id)SELECT- $1, $2, NULL, 'queued', $3, $4,+ sqlc.arg(agent_id), enqueue_agent.runtime_id, NULL, 'queued', sqlc.arg(priority), sqlc.narg(context),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),sqlc.narg(runtime_mcp_overlay),@@ -479,7 +511,7 @@ SELECTsqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, NULL, $2)+FROM enqueue_agentRETURNING *;-- name: LinkTaskToIssue :exec@@ -887,17 +919,29 @@ WHERE id = @task_id-- queue so another poll can retry immediately instead of waiting for stale-- dispatch recovery. The dispatched_at CAS prevents an old handler from-- rolling back a newer reclaim.-UPDATE agent_task_queue+-- An undelivered claim follows the current binding when returned to the queue.+-- Lock the agent before the task, as the binding transaction does.+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, a.runtime_id FROM agent a+ WHERE a.id = (SELECT agent_id FROM agent_task_queue WHERE id = @task_id)+ AND lock_task_owner_rows(a.id, NULL, NULL)+ FOR KEY SHARE OF a+)+UPDATE agent_task_queue AS taskSET status = 'queued',+ runtime_id = COALESCE(enqueue_agent.runtime_id, task.runtime_id),dispatched_at = NULL,prepare_lease_expires_at = NULL,delivered_comment_ids = '{}'-WHERE id = @task_id- AND runtime_id = @runtime_id- AND status = 'dispatched'- AND started_at IS NULL- AND dispatched_at = @dispatched_at-RETURNING *;+FROM enqueue_agent+WHERE task.id = @task_id+ AND task.agent_id = enqueue_agent.id+ AND task.runtime_id = @runtime_id+ AND task.status = 'dispatched'+ AND task.started_at IS NULL+ AND task.dispatched_at = @dispatched_at+ AND lock_task_owner_rows(task.agent_id, task.issue_id, COALESCE(enqueue_agent.runtime_id, task.runtime_id))+RETURNING task.*;-- name: ReclaimStaleDispatchedTaskForRuntime :one-- Re-delivers a task whose previous claim likely succeeded server-side butdiff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex db9df41649..3e03b43cb5 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -611,6 +611,13 @@ ORDER BY t.id;-- When no version/publisher resolves on the non-manual path, the caller passes NULL-- accountable + originator_source='unattributed' so the row is still not a-- NULL-source bypass (MUL-4302 §2).+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,originator_user_id, accountable_user_id, rule_version_id,@@ -618,7 +625,7 @@ INSERT INTO agent_task_queue (id)SELECT- $1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary),+ sqlc.arg(agent_id), enqueue_agent.runtime_id, NULL, 'queued', sqlc.arg(priority), sqlc.narg(autopilot_run_id), sqlc.narg(trigger_summary),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),sqlc.narg(rule_version_id),@@ -626,7 +633,7 @@ SELECTsqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, NULL, $2)+FROM enqueue_agentRETURNING *;-- name: GetAutopilotTaskByRun :onediff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 6d87905c74..4a49280fb8 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1147,6 +1147,13 @@ WHERE id = $1;-- The chat sender (initiator) is a direct_human originator and accountable;-- attribution provenance is stamped so this path is not a NULL-source enqueue-- bypass (MUL-4302 §2).+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id,initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,@@ -1154,9 +1161,9 @@ INSERT INTO agent_task_queue (fire_at, channel_context_revision, id, context)SELECT- $1, $2, NULL,+ sqlc.arg(agent_id), enqueue_agent.runtime_id, NULL,CASE WHEN sqlc.narg('fire_at')::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,- $3, $4, $5,+ sqlc.arg(priority), sqlc.narg(chat_session_id), sqlc.narg(initiator_user_id),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),@@ -1169,7 +1176,7 @@ SELECTsqlc.narg('channel_context_revision')::bigint,COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()),sqlc.narg('context')::jsonb-WHERE lock_task_owner_rows($1, NULL, $2)+FROM enqueue_agentRETURNING *;-- name: PromoteChannelChatTasksIfMediaReady :manydiff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sqlindex 135b082b63..e3786509e7 100644--- a/server/pkg/db/queries/wakeup.sql+++ b/server/pkg/db/queries/wakeup.sql@@ -174,6 +174,13 @@ SELECT * FROM agent_task_queue WHERE context->>'wakeup_id'= @wakeup_id::text AND-- COALESCE keeps the column's gen_random_uuid() default reachable, so a caller-- that passes no id still inserts — it just gets a random v4, exactly as before.-- The same pattern is used by every INSERT listed in pkg/dbid's write table.+WITH enqueue_agent AS MATERIALIZED (+ SELECT a.id, COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid) AS runtime_id+ FROM agent a+ WHERE a.id = sqlc.arg(agent_id)+ AND lock_task_owner_rows(a.id, sqlc.narg(issue_id), COALESCE(a.runtime_id, sqlc.narg(runtime_id)::uuid))+ FOR KEY SHARE OF a+)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,@@ -182,7 +189,7 @@ INSERT INTO agent_task_queue (workflow_step, id)SELECT- $1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),+ sqlc.arg(agent_id), enqueue_agent.runtime_id, sqlc.narg(issue_id), 'queued', sqlc.arg(priority), sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),@@ -209,11 +216,11 @@ SELECT-- makes after someone else moved the issue is refused like the run's own-- would be. A wakeup a member registered starts from the issue's status.COALESCE(- (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = sqlc.narg(delegated_from_task_id) AND s.issue_id = $3),- (SELECT i.status FROM issue i WHERE i.id = $3)+ (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = sqlc.narg(delegated_from_task_id) AND s.issue_id = sqlc.narg(issue_id)),+ (SELECT i.status FROM issue i WHERE i.id = sqlc.narg(issue_id))),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)+FROM enqueue_agentRETURNING *;-- name: LocklessWakeup :one