Skip to content

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

Go

MUL-6146 fix(rerun): stop cancelling an in-flight agent run on manual rerun (#7282)

Bohan Jiang8c9b7503a12d
diff --git a/server/internal/handler/fail_task_successor_test.go b/server/internal/handler/fail_task_successor_test.go
new file mode 100644
index 0000000000..e7460fe259
--- /dev/null
+++ b/server/internal/handler/fail_task_successor_test.go
@@ -0,0 +1,532 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestFailTask_SkipsAutoRetryWhenManualRerunAlreadyQueued covers the interaction
+// opened up by letting a manual rerun queue BEHIND a running task instead of
+// cancelling it (MUL-6146).
+//
+// Sequence: a task is running, an operator reruns the issue (so a queued row now
+// sits behind it), and then the running task fails for a reason whose retry
+// child is created immediately rather than deferred. That child is inserted as a
+// second queued row for the same (issue, agent) and collides with
+// idx_one_pending_task_per_issue_agent_v2. That insert shares FailTask's
+// transaction, so the unique violation would roll the parent's failed status back
+// with it: the fail call surfaces an error and the task is left stuck in
+// 'running'.
+//
+// Expected instead: the failure commits, the auto-retry is skipped because a
+// successor already exists, and exactly one runnable row remains — the rerun.
+//
+// The reason matters: retryDelayForAttempt defers runtime_offline and
+// provider_network's FINAL attempt, and a deferred child is not covered by the
+// unique index, so those cannot collide. The cases below are the ones that
+// produce an immediately-claimable 'queued' child.
+func TestFailTask_SkipsAutoRetryWhenManualRerunAlreadyQueued(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ for _, tc := range []struct {
+ name string
+ failureReason string
+ }{
+ {name: "timeout", failureReason: "timeout"},
+ {name: "first_provider_network", failureReason: "agent_error.provider_network"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ failTaskSuccessorCase(t, tc.failureReason)
+ })
+ }
+}
+
+func failTaskSuccessorCase(t *testing.T, failureReason string) {
+ t.Helper()
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "fail-successor-runtime-"+failureReason)
+ agentID := dbfx.Agent(t, "fail-successor-agent-"+failureReason, runtimeID)
+ issueID := dbfx.Issue(t, "manual rerun races auto-retry", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ // The in-flight run. attempt/max_attempts leave the auto-retry budget open,
+ // so without the successor check FailTask would try to insert a retry child.
+ runningID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "running",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+
+ // The operator reruns while that task is still running: allowed now, and it
+ // takes the single queued/dispatched slot the unique index permits.
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), nil)
+ if err != nil {
+ t.Fatalf("RerunIssue behind running task: %v", err)
+ }
+ if rerun.Status != "queued" {
+ t.Fatalf("precondition: rerun should be queued, got %q", rerun.Status)
+ }
+
+ // The retry child for this reason is created immediately as 'queued' — the
+ // exact shape that collides with the rerun already holding the slot.
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(runningID),
+ "run died", "", "", "", failureReason, false, "", ""); err != nil {
+ t.Fatalf("FailTask with a manual rerun already queued: %v", err)
+ }
+
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, runningID).Scan(&status); err != nil {
+ t.Fatalf("read failed task: %v", err)
+ }
+ if status != "failed" {
+ t.Fatalf("the parent's failure must commit even when the retry is skipped; status = %q", status)
+ }
+
+ rows, err := testPool.Query(ctx, `
+ SELECT id::text FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')
+ `, issueID, agentID)
+ if err != nil {
+ t.Fatalf("list runnable successors: %v", err)
+ }
+ defer rows.Close()
+ var successors []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan successor: %v", err)
+ }
+ successors = append(successors, id)
+ }
+ if len(successors) != 1 {
+ t.Fatalf("expected exactly one runnable successor, got %d: %v", len(successors), successors)
+ }
+ if successors[0] != uuidToString(rerun.ID) {
+ t.Fatalf("the surviving successor should be the manual rerun %s, got %s", uuidToString(rerun.ID), successors[0])
+ }
+}
+
+// TestCreateRetryTask_YieldsPendingSlotInsteadOfRaising is the deterministic half
+// of the concurrency contract. The successor pre-check in FailTask takes no lock
+// (a plain count under READ COMMITTED), so a rerun can always commit between that
+// check and the retry insert. What makes the failure transaction safe regardless
+// of interleaving is the insert itself: ON CONFLICT DO NOTHING yields the slot
+// rather than raising 23505 and aborting the caller's transaction.
+//
+// Asserting pgx.ErrNoRows here — not a unique violation — is what proves the
+// enclosing transaction can never be poisoned by losing the race.
+func TestCreateRetryTask_YieldsPendingSlotInsteadOfRaising(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "retry-yield-runtime")
+ agentID := dbfx.Agent(t, "retry-yield-agent", runtimeID)
+ issueID := dbfx.Issue(t, "retry yields the pending slot", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ // A failed parent that is otherwise a perfectly good retry candidate.
+ parentID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "failed",
+ "failure_reason": "timeout",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+ // Someone else already holds the single queued/dispatched slot.
+ dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "queued",
+ })
+
+ _, err := testHandler.TaskService.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: parseUUID(parentID)})
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("CreateRetryTask against an occupied slot must yield (pgx.ErrNoRows), got %v", err)
+ }
+}
+
+// TestFailTaskAndRerunConcurrently_NeverStrandsRunningTask forces the interleaving
+// the successor pre-check cannot prevent: FailTask and RerunIssue racing for the
+// same (issue, agent) slot on two separate connections, released together from a
+// barrier so the rerun can commit inside FailTask's transaction window.
+//
+// The invariants must hold no matter who wins:
+// - FailTask never returns an error (its transaction is never aborted by the
+// retry insert), so the parent's failure always commits.
+// - The parent ends 'failed', never stranded back in 'running'.
+// - At most one runnable successor exists, since the unique index allows one.
+func TestFailTaskAndRerunConcurrently_NeverStrandsRunningTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "rerun-race-runtime")
+ agentID := dbfx.Agent(t, "rerun-race-agent", runtimeID)
+ issueID := dbfx.Issue(t, "rerun races auto-retry", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ const rounds = 15
+ for i := 0; i < rounds; i++ {
+ runningID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "running",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ var failErr, rerunErr error
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ <-start
+ _, failErr = testHandler.TaskService.FailTask(ctx, parseUUID(runningID),
+ "run died", "", "", "", "timeout", false, "", "")
+ }()
+ go func() {
+ defer wg.Done()
+ <-start
+ _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), nil)
+ }()
+ close(start)
+ wg.Wait()
+
+ if failErr != nil {
+ t.Fatalf("round %d: FailTask must never abort on slot contention: %v", i, failErr)
+ }
+ if rerunErr != nil {
+ t.Fatalf("round %d: RerunIssue must reclaim the slot rather than surface a conflict: %v", i, rerunErr)
+ }
+
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, runningID).Scan(&status); err != nil {
+ t.Fatalf("round %d: read parent: %v", i, err)
+ }
+ if status != "failed" {
+ t.Fatalf("round %d: parent must commit as failed, got %q (stranded)", i, status)
+ }
+
+ var pending int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')
+ `, issueID, agentID).Scan(&pending); err != nil {
+ t.Fatalf("round %d: count successors: %v", i, err)
+ }
+ if pending > 1 {
+ t.Fatalf("round %d: the unique index allows one runnable successor, found %d", i, pending)
+ }
+
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ }
+}
+
+// TestPromoteDueDeferred_CancelsSupersededRetry pins the product invariant this
+// PR exists to protect: one rerun click means exactly ONE more run.
+//
+// runtime_offline and provider_network's final attempt arm their retry as a
+// 'deferred' row, which is outside idx_one_pending_task_per_issue_agent_v2 — so
+// it survives alongside a manual rerun (the rerun clears the slot, the retry
+// commits, the rerun's enqueue then succeeds because deferred does not conflict).
+//
+// Merely declining to promote it is not enough. The rerun eventually starts
+// running and stops occupying the queued slot, at which point the stale retry
+// would promote and run the agent a SECOND time — duplicate comments, duplicate
+// side effects, duplicate cost, and no error anywhere to show for it. The retry
+// is superseded, so it is cancelled outright.
+func TestPromoteDueDeferred_CancelsSupersededRetry(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "promote-supersede-runtime")
+ agentID := dbfx.Agent(t, "promote-supersede-agent", runtimeID)
+ issueID := dbfx.Issue(t, "deferred retry superseded by rerun", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ failedID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "failed", "failure_reason": "runtime_offline",
+ })
+ // The manual rerun the operator asked for.
+ rerunID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "queued",
+ })
+ // The retry armed by the old failure, already due.
+ retryID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "deferred",
+ "fire_at": testutil.Raw("now() - interval '1 minute'"),
+ "retry_of_task_id": failedID,
+ })
+
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, parseUUID(runtimeID)); err != nil {
+ t.Fatalf("promotion must not fail while the slot is occupied: %v", err)
+ }
+ if got := taskStatusByID(t, retryID); got != "cancelled" {
+ t.Fatalf("the superseded retry must be cancelled, got %q", got)
+ }
+ if got := taskStatusByID(t, rerunID); got != "queued" {
+ t.Fatalf("the manual rerun must be untouched, got %q", got)
+ }
+
+ // The rerun starts and then finishes, freeing the slot. The retry must stay
+ // dead — this is the exact point at which it used to come back and run again.
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, rerunID); err != nil {
+ t.Fatalf("free the slot: %v", err)
+ }
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, parseUUID(runtimeID)); err != nil {
+ t.Fatalf("second promotion: %v", err)
+ }
+ if got := taskStatusByID(t, retryID); got != "cancelled" {
+ t.Fatalf("a superseded retry must never come back after the rerun finishes, got %q", got)
+ }
+}
+
+// TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone bounds the cancellation
+// above. Assignee-fallback escalations are deferred rows that are SUPPOSED to
+// coexist with an active primary task — they own their own fire_at lifecycle and
+// exist precisely to fire when the primary goes quiet. Cancelling those would
+// silently disable escalation, so the sweep is scoped to auto-retry clones.
+//
+// The index fence still applies to them: they stay deferred while the slot is
+// occupied rather than colliding on promotion.
+func TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "promote-escalation-runtime")
+ agentID := dbfx.Agent(t, "promote-escalation-agent", runtimeID)
+ issueID := dbfx.Issue(t, "escalation survives an active primary", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ primaryID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "queued",
+ })
+ escalationID := dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "deferred",
+ "fire_at": testutil.Raw("now() - interval '1 minute'"),
+ "escalation_for_task_id": primaryID,
+ })
+
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, parseUUID(runtimeID)); err != nil {
+ t.Fatalf("promotion: %v", err)
+ }
+ if got := taskStatusByID(t, escalationID); got != "deferred" {
+ t.Fatalf("an escalation must be neither cancelled nor promoted into an occupied slot, got %q", got)
+ }
+ if got := taskStatusByID(t, primaryID); got != "queued" {
+ t.Fatalf("primary must be untouched, got %q", got)
+ }
+}
+
+func taskStatusByID(t *testing.T, id string) string {
+ t.Helper()
+ var status string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status FROM agent_task_queue WHERE id = $1`, id).Scan(&status); err != nil {
+ t.Fatalf("read task status: %v", err)
+ }
+ return status
+}
+
+// TestFailTaskAndRerunConcurrently_NonAssigneeTarget runs the same race as
+// TestFailTaskAndRerunConcurrently_NeverStrandsRunningTask, but for a rerun whose
+// target is NOT the issue's current agent assignee — a past task re-fired by
+// task_id after the issue was reassigned.
+//
+// That routes the enqueue through enqueueMentionTaskWithCommentPlan, which
+// normalizes the unique violation into the bare ErrDuplicatePendingTask sentinel
+// instead of surfacing the pgconn error. The reclaim branch has to recognise that
+// shape too, otherwise every squad-leader / displaced-agent / mentioned-agent
+// rerun losing this race reports a hard failure to the operator.
+func TestFailTaskAndRerunConcurrently_NonAssigneeTarget(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "non-assignee-race-runtime")
+ assigneeID := dbfx.Agent(t, "non-assignee-race-current", runtimeID)
+ displacedID := dbfx.Agent(t, "non-assignee-race-displaced", runtimeID)
+ issueID := dbfx.Issue(t, "rerun a displaced agent while it fails", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": assigneeID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ // The execution-log row the operator clicks retry on: it belonged to the
+ // displaced agent, so the rerun targets that agent rather than the assignee.
+ sourceTaskID := dbfx.Task(t, displacedID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "completed",
+ })
+
+ const rounds = 15
+ for i := 0; i < rounds; i++ {
+ runningID := dbfx.Task(t, displacedID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "running",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ var failErr, rerunErr error
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ <-start
+ _, failErr = testHandler.TaskService.FailTask(ctx, parseUUID(runningID),
+ "run died", "", "", "", "timeout", false, "", "")
+ }()
+ go func() {
+ defer wg.Done()
+ <-start
+ _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), parseUUID(sourceTaskID), pgtype.UUID{}, parseUUID(testUserID), nil)
+ }()
+ close(start)
+ wg.Wait()
+
+ if failErr != nil {
+ t.Fatalf("round %d: FailTask must never abort on slot contention: %v", i, failErr)
+ }
+ if rerunErr != nil {
+ t.Fatalf("round %d: a non-assignee rerun must reclaim the slot, not surface the normalized sentinel: %v", i, rerunErr)
+ }
+ if got := taskStatusByID(t, runningID); got != "failed" {
+ t.Fatalf("round %d: parent must commit as failed, got %q", i, got)
+ }
+
+ var pending int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')
+ `, issueID, displacedID).Scan(&pending); err != nil {
+ t.Fatalf("round %d: count successors: %v", i, err)
+ }
+ if pending > 1 {
+ t.Fatalf("round %d: expected at most one runnable successor, found %d", i, pending)
+ }
+
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1 AND id <> $2`, issueID, sourceTaskID)
+ }
+}
+
+// TestPromoteDueDeferred_ToleratesConcurrentUncommittedEnqueue covers the one
+// window the in-query NOT EXISTS fence cannot: an enqueue that has not committed
+// yet is invisible to it, so promotion still walks into the unique index and
+// waits on the other transaction's lock, receiving 23505 once it commits.
+//
+// The fix is tolerance rather than prevention. This is a self-healing blip — the
+// next tick sees the committed row and skips cleanly — so the only thing that
+// must hold is that one contended row does not fail the claim call. Before that
+// tolerance, the single-runtime path returned the error outright and the batch
+// path failed the claim for every runtime in the set.
+func TestPromoteDueDeferred_ToleratesConcurrentUncommittedEnqueue(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ runtimeID := dbfx.Runtime(t, "promote-uncommitted-runtime")
+ agentID := dbfx.Agent(t, "promote-uncommitted-agent", runtimeID)
+ issueID := dbfx.Issue(t, "promotion meets an uncommitted enqueue", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ // A due deferred row with no visible competitor: neither the supersede sweep
+ // nor the promotion fence has any reason to leave it alone.
+ dbfx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID,
+ "runtime_id": runtimeID,
+ "status": "deferred",
+ "fire_at": testutil.Raw("now() - interval '1 minute'"),
+ })
+
+ // A second connection inserts the competing queued row and holds it open, so
+ // it is invisible to promotion's fence but still owns the index entry.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder tx: %v", err)
+ }
+ defer tx.Rollback(context.Background())
+ if _, err := tx.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, 'queued', 0)
+ `, agentID, runtimeID, issueID); err != nil {
+ t.Fatalf("insert uncommitted competitor: %v", err)
+ }
+
+ // Commit the competitor shortly after promotion starts, so promotion is
+ // already blocked on the index and is handed 23505 when the lock releases.
+ committed := make(chan error, 1)
+ go func() {
+ time.Sleep(150 * time.Millisecond)
+ committed <- tx.Commit(context.Background())
+ }()
+
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, parseUUID(runtimeID)); err != nil {
+ t.Fatalf("a single contended row must not fail the claim: %v", err)
+ }
+ if err := <-committed; err != nil {
+ t.Fatalf("commit competitor: %v", err)
+ }
+}
diff --git a/server/internal/service/pending_slot_err_test.go b/server/internal/service/pending_slot_err_test.go
new file mode 100644
index 0000000000..53ae2e9e31
--- /dev/null
+++ b/server/internal/service/pending_slot_err_test.go
@@ -0,0 +1,64 @@
+package service
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgconn"
+)
+
+// TestPendingSlotTakenErr_RecognizesBothShapes pins the two error shapes that can
+// reach RerunIssue's reclaim branch. The issue-assignee enqueue surfaces the raw
+// unique violation, but enqueueMentionTaskWithCommentPlan normalizes it into the
+// bare ErrDuplicatePendingTask sentinel — and that is the path EVERY rerun takes
+// whose target is not the issue's current agent assignee (squad leader, an agent
+// re-fired by task_id after being displaced, a mentioned agent).
+//
+// Matching only the pgconn shape silently excluded all of those from the reclaim,
+// so a system retry winning the slot surfaced to the operator as a hard error.
+func TestPendingSlotTakenErr_RecognizesBothShapes(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ want bool
+ }{
+ {
+ name: "raw unique violation from the issue-assignee path",
+ err: &pgconn.PgError{Code: "23505", ConstraintName: "idx_one_pending_task_per_issue_agent_v2"},
+ want: true,
+ },
+ {
+ name: "legacy v1 index name during a rolling deploy",
+ err: &pgconn.PgError{Code: "23505", ConstraintName: "idx_one_pending_task_per_issue_agent"},
+ want: true,
+ },
+ {
+ name: "normalized sentinel from the mention path",
+ err: ErrDuplicatePendingTask,
+ want: true,
+ },
+ {
+ name: "wrapped sentinel",
+ err: fmt.Errorf("enqueue rerun: %w", ErrDuplicatePendingTask),
+ want: true,
+ },
+ {
+ name: "a different unique violation must not trigger a reclaim",
+ err: &pgconn.PgError{Code: "23505", ConstraintName: "agent_workspace_name_unique"},
+ want: false,
+ },
+ {
+ name: "unrelated error",
+ err: errors.New("connection reset"),
+ want: false,
+ },
+ {name: "nil", err: nil, want: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := pendingSlotTakenErr(tc.err); got != tc.want {
+ t.Fatalf("pendingSlotTakenErr(%v) = %v, want %v", tc.err, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/rerun_queue_behind_active_test.go b/server/internal/service/rerun_queue_behind_active_test.go
new file mode 100644
index 0000000000..5cc19613fc
--- /dev/null
+++ b/server/internal/service/rerun_queue_behind_active_test.go
@@ -0,0 +1,120 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "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/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// rerunQueueFixture seeds the shared (workspace, agent, issue) trio and returns
+// the service under test plus the agent's runtime id, which
+// agent_task_queue.runtime_id needs (NOT NULL).
+func rerunQueueFixture(t *testing.T) (svc *TaskService, pool *pgxpool.Pool, creatorID, agentID, issueID, runtimeID string) {
+ t.Helper()
+ pool = newResolveOriginatorPool(t)
+ _, creatorID, agentID, issueID = seedAttributionFixture(t, pool)
+
+ if err := pool.QueryRow(context.Background(), `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("read agent runtime: %v", err)
+ }
+ svc = &TaskService{Queries: db.New(pool), TxStarter: pool, Bus: events.New()}
+ return svc, pool, creatorID, agentID, issueID, runtimeID
+}
+
+func seedRerunTask(t *testing.T, pool *pgxpool.Pool, agentID, runtimeID, issueID, status string) pgtype.UUID {
+ t.Helper()
+ var id pgtype.UUID
+ if err := pool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, $4, 0)
+ RETURNING id
+ `, agentID, runtimeID, issueID, status).Scan(&id); err != nil {
+ t.Fatalf("insert %s task: %v", status, err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, id) })
+ return id
+}
+
+func taskStatus(t *testing.T, pool *pgxpool.Pool, id pgtype.UUID) string {
+ t.Helper()
+ var status string
+ if err := pool.QueryRow(context.Background(),
+ `SELECT status FROM agent_task_queue WHERE id = $1`, id).Scan(&status); err != nil {
+ t.Fatalf("read task status: %v", err)
+ }
+ return status
+}
+
+// TestRerunIssueQueuesBehindActiveTaskWithoutCancelling is the regression this
+// change exists for. 'running' and 'waiting_local_directory' both mean an agent
+// is executing, and neither appears in idx_one_pending_task_per_issue_agent_v2 —
+// so a rerun enqueues a queued row alongside the active one and ClaimAgentTask's
+// per-(issue, agent) serialization holds it there until the active run reaches a
+// terminal state.
+//
+// The load-bearing assertion is that the active task is untouched. Rerun used to
+// call a cancel query covering every active status, so clicking "run this again"
+// silently killed the pass the agent was still working on.
+func TestRerunIssueQueuesBehindActiveTaskWithoutCancelling(t *testing.T) {
+ for _, activeStatus := range []string{"running", "waiting_local_directory"} {
+ t.Run(activeStatus, func(t *testing.T) {
+ svc, pool, creatorID, agentID, issueID, runtimeID := rerunQueueFixture(t)
+ activeID := seedRerunTask(t, pool, agentID, runtimeID, issueID, activeStatus)
+
+ task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID) })
+
+ if got := taskStatus(t, pool, activeID); got != activeStatus {
+ t.Fatalf("rerun must NOT cancel an executing task; %s task is now %q", activeStatus, got)
+ }
+ if util.UUIDToString(task.ID) == util.UUIDToString(activeID) {
+ t.Fatal("rerun must enqueue its own row, not hand back the active task")
+ }
+ if task.Status != "queued" {
+ t.Fatalf("the rerun row must wait its turn as queued, got %q", task.Status)
+ }
+ if !task.ForceFreshSession {
+ t.Fatal("a rerun row must carry force_fresh_session (MUL-4869)")
+ }
+ })
+ }
+}
+
+// TestRerunIssueReplacesNotYetStartedTask keeps the other half of the contract:
+// a row that has not begun executing is still cancelled and replaced. Nothing is
+// lost by doing so (no agent was working), the unique index leaves no choice for
+// queued/dispatched, and replacing rather than reusing is what keeps the new run
+// attributed to the rerunning member instead of inheriting the attribution of
+// whoever created the pending row (MUL-4302 §5).
+func TestRerunIssueReplacesNotYetStartedTask(t *testing.T) {
+ for _, pendingStatus := range []string{"queued", "dispatched"} {
+ t.Run(pendingStatus, func(t *testing.T) {
+ svc, pool, creatorID, agentID, issueID, runtimeID := rerunQueueFixture(t)
+ pendingID := seedRerunTask(t, pool, agentID, runtimeID, issueID, pendingStatus)
+
+ task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID) })
+
+ if util.UUIDToString(task.ID) == util.UUIDToString(pendingID) {
+ t.Fatal("expected a fresh rerun task, got the pre-existing pending row")
+ }
+ if got := taskStatus(t, pool, pendingID); got != "cancelled" {
+ t.Fatalf("a not-yet-started %s task must be cancelled to make room for the rerun, got %q", pendingStatus, got)
+ }
+ if task.Status != "queued" {
+ t.Fatalf("rerun task status = %q, want queued", task.Status)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 086c5aab0c..84248742f9 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -606,6 +606,20 @@ func isDuplicatePendingTaskErr(err error) bool {
}
}
+// pendingSlotTakenErr reports whether err means "the (issue, agent) pending slot
+// was already occupied when we tried to enqueue".
+//
+// Two shapes reach RerunIssue. The issue-assignee path surfaces the raw unique
+// violation, while enqueueMentionTaskWithCommentPlan normalizes it into the bare
+// ErrDuplicatePendingTask sentinel — and that is the path taken by EVERY rerun
+// whose target is not the issue's current agent assignee: a squad leader, a
+// displaced agent re-fired by task_id, a mentioned agent. Matching only the raw
+// pgconn error meant the reclaim never ran for those, so a system retry winning
+// the slot surfaced as a hard error instead.
+func pendingSlotTakenErr(err error) bool {
+ return isDuplicatePendingTaskErr(err) || errors.Is(err, ErrDuplicatePendingTask)
+}
+
// applyAttributionFallback applies the workspace's degraded-attribution policy to a
// resolved attribution whose source came back unattributed (no precise human). A
// PRECISE attribution passes through untouched (no policy read at all). For an
@@ -3342,11 +3356,18 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
// MarkEmpty from a prior idle poll would short-circuit the runtime and the
// promoted task would sit unclaimed until the empty key's TTL. Also emits
// the deferred→queued UI event and the enqueue analytics sample.
+ s.cancelSupersededDeferredRetries(ctx, uniqueIDs)
promoted, err := s.Queries.PromoteDueDeferredTasksForRuntimes(ctx, db.PromoteDueDeferredTasksForRuntimesParams{
RuntimeIds: uniqueIDs,
RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,
})
- if err != nil {
+ if isDuplicatePendingTaskErr(err) {
+ // Same tolerance as the single-runtime path, and it matters more here:
+ // one contended row would otherwise fail the claim for EVERY runtime in
+ // the batch. Promote nothing this tick and let the claim continue.
+ slog.Info("promote deferred tasks (batch): slot taken by a concurrent enqueue, skipping this tick")
+ promoted = nil
+ } else if err != nil {
return nil, fmt.Errorf("promote deferred tasks: %w", err)
}
for _, task := range promoted {
@@ -3473,11 +3494,48 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg
return claimed, nil
}
+// cancelSupersededDeferredRetries drops deferred auto-retry rows that an active
+// task already supersedes, so a single rerun click still produces exactly one
+// more run. Runs immediately before promotion — promotion is the moment a stale
+// retry would otherwise become claimable. Best-effort: a failure here must not
+// stop the claim loop, it just leaves the row for the next tick.
+func (s *TaskService) cancelSupersededDeferredRetries(ctx context.Context, runtimeIDs []pgtype.UUID) {
+ if len(runtimeIDs) == 0 {
+ return
+ }
+ cancelled, err := s.Queries.CancelSupersededDeferredRetriesForRuntimes(ctx, runtimeIDs)
+ if err != nil {
+ slog.Warn("cancel superseded deferred retries failed", "error", err)
+ return
+ }
+ for _, task := range cancelled {
+ slog.Info("deferred auto-retry cancelled: superseded by an active task",
+ "task_id", util.UUIDToString(task.ID),
+ "issue_id", util.UUIDToString(task.IssueID),
+ "agent_id", util.UUIDToString(task.AgentID),
+ )
+ s.captureTaskCancelled(ctx, task)
+ s.ReconcileAgentStatus(ctx, task.AgentID)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)
+ }
+}
+
func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
+ s.cancelSupersededDeferredRetries(ctx, []pgtype.UUID{runtimeID})
tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, db.PromoteDueDeferredTasksForRuntimeParams{
RuntimeID: runtimeID,
RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,
})
+ if isDuplicatePendingTaskErr(err) {
+ // The NOT EXISTS fence inside the query cannot see an enqueue that has
+ // not committed yet, so a rerun landing in the same instant still
+ // collides here. One row losing its slot must not fail the whole claim:
+ // the row stays deferred and the next tick — by which time the rerun is
+ // visible — skips it cleanly. Costs one poll interval, never a stall.
+ slog.Info("promote due deferred tasks: slot taken by a concurrent enqueue, skipping this tick",
+ "runtime_id", util.UUIDToString(runtimeID))
+ return nil
+ }
if err != nil {
return fmt.Errorf("promote due deferred tasks: %w", err)
}
@@ -4204,7 +4262,30 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// Create the retry child atomically with the fail. CreateRetryTask reads
// the just-failed parent row (same tx), so it inherits chat_input_task_id
// and the bumped chat-retry priority; broadcast/notify happen after commit.
- if wantRetry {
+ // This check is an optimisation, NOT the safety mechanism. It is a plain
+ // count at READ COMMITTED and takes no lock, so a rerun can always commit
+ // between it and the insert below; it only saves the work when a
+ // successor is already visible and gives the skip a readable log line.
+ // Correctness under that race belongs to CreateRetryTask's
+ // ON CONFLICT DO NOTHING, which yields the slot instead of raising and so
+ // can never abort this transaction — which also carries the parent's
+ // failed status.
+ createRetry := wantRetry
+ if createRetry {
+ successor, herr := hasRunnableSuccessor(ctx, qtx, t)
+ if herr != nil {
+ return fmt.Errorf("check runnable successor: %w", herr)
+ }
+ if successor {
+ slog.Info("fail task auto-retry skipped: a successor is already pending",
+ "task_id", util.UUIDToString(taskID),
+ "issue_id", util.UUIDToString(t.IssueID),
+ "agent_id", util.UUIDToString(t.AgentID),
+ )
+ createRetry = false
+ }
+ }
+ if createRetry {
child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{
NewTaskID: dbid.NewV7(),
ID: taskID,
@@ -4213,10 +4294,24 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
RuntimeMcpOverlay: retryOverlay.Overlay,
RuntimeConnectedApps: retryOverlay.ConnectedApps,
})
- if cerr != nil {
+ switch {
+ case cerr == nil:
+ retried = &child
+ case errors.Is(cerr, pgx.ErrNoRows):
+ // The statement wrote nothing: either the owning workspace was
+ // torn down mid-flight, or a rerun took the pending slot after
+ // the unlocked check above (ON CONFLICT DO NOTHING). Neither is
+ // a reason to abort — this transaction still owns the parent's
+ // failed status, and losing that would leave the task stuck in
+ // 'running'. Record the failure and move on without a retry.
+ slog.Info("fail task auto-retry not created: no row written",
+ "task_id", util.UUIDToString(taskID),
+ "issue_id", util.UUIDToString(t.IssueID),
+ "agent_id", util.UUIDToString(t.AgentID),
+ )
+ default:
return fmt.Errorf("create retry task: %w", cerr)
}
- retried = &child
}
// A terminal non-retried chat failure is a visible assistant outcome.
@@ -4508,6 +4603,32 @@ func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
(t.IssueID.Valid || t.ChatSessionID.Valid)
}
+// hasRunnableSuccessor reports whether another not-yet-started task already
+// occupies the single queued/dispatched slot that
+// idx_one_pending_task_per_issue_agent_v2 allows per (issue, agent).
+//
+// Both auto-retry paths consult this before inserting a retry child. A manual
+// rerun can now be enqueued BEHIND a still-running task instead of cancelling
+// it, so by the time that task fails its slot may already be taken, and the
+// retry exists to give the issue a runnable successor that already exists.
+//
+// This is advisory only: the query takes no lock, so a rerun committing after it
+// returns is always possible. CreateRetryTask's ON CONFLICT DO NOTHING is what
+// makes losing that race harmless. Skipping early just avoids pointless work and
+// records why no retry was made.
+//
+// Chat / quick-create tasks carry no issue_id, so the index cannot apply to them
+// and their retries can never collide.
+func hasRunnableSuccessor(ctx context.Context, q *db.Queries, task db.AgentTaskQueue) (bool, error) {
+ if !task.IssueID.Valid {
+ return false, nil
+ }
+ return q.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: task.IssueID,
+ AgentID: task.AgentID,
+ })
+}
+
// MaybeRetryFailedTask spawns a fresh queued attempt for a recently-failed
// task when the failure was infrastructure-shaped (daemon crash, runtime
// went offline, dispatch/run timeout) and the task hasn't exhausted its
@@ -4572,6 +4693,20 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
if delay := retryDelayForAttempt(reason, parent.Attempt); delay > 0 {
retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
}
+ // Same advisory slot check as FailTask's path, for the same reason: skip the
+ // work when a successor is already visible. Losing the race is handled by
+ // CreateRetryTask yielding the slot, which this caller reads as "no retry".
+ if successor, herr := hasRunnableSuccessor(ctx, s.Queries, parent); herr != nil {
+ slog.Warn("task auto-retry: successor check failed; attempting retry anyway",
+ "parent_task_id", util.UUIDToString(parent.ID), "error", herr)
+ } else if successor {
+ slog.Info("task auto-retry skipped: a successor is already pending",
+ "parent_task_id", util.UUIDToString(parent.ID),
+ "issue_id", util.UUIDToString(parent.IssueID),
+ "agent_id", util.UUIDToString(parent.AgentID),
+ )
+ return nil, nil
+ }
child, err := s.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{
NewTaskID: dbid.NewV7(),
ID: parent.ID,
@@ -4580,6 +4715,16 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
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, no
+ // error.
+ slog.Info("task auto-retry not created: no row written",
+ "parent_task_id", util.UUIDToString(parent.ID),
+ "reason", reason,
+ )
+ return nil, nil
+ }
if err != nil {
slog.Warn("task auto-retry failed",
"parent_task_id", util.UUIDToString(parent.ID),
@@ -4734,27 +4879,40 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
}
}
- // Cancel only the target agent's active/queued tasks on this issue. A manual
- // rerun is a request to resume the issue, not to dismiss planned recovery
- // signals, so this intentionally stays on the server-cancel query. Any
- // undelivered delegated-failure signal remains an outbox obligation and the
- // sweeper can merge it into the fresh rerun task.
- cancelled, err := s.Queries.CancelAgentTasksByIssueAndAgent(ctx, db.CancelAgentTasksByIssueAndAgentParams{
- IssueID: issueID,
- AgentID: agentID,
- })
- if err != nil {
- slog.Warn("rerun: cancel prior tasks failed",
- "issue_id", util.UUIDToString(issueID),
- "agent_id", util.UUIDToString(agentID),
- "error", err,
- )
- }
- for _, t := range cancelled {
- s.captureTaskCancelled(ctx, t)
- s.ReconcileAgentStatus(ctx, t.AgentID)
- s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ // Clear only the tasks that have not begun executing. Those are the rows the
+ // fresh enqueue would collide with under
+ // idx_one_pending_task_per_issue_agent_v2, and replacing them costs no work
+ // while keeping the new run attributed to the rerunning member (MUL-4302 §5)
+ // rather than inheriting whoever created the pending row.
+ //
+ // A running / waiting_local_directory task is deliberately left alone: an
+ // agent is executing in it. Neither status appears in that unique index, so
+ // the enqueue below inserts a queued row BEHIND the active one, and
+ // ClaimAgentTask's per-(issue, agent) serialization holds it there until the
+ // active run reaches a terminal state. Rerun used to cancel these too, so
+ // asking an agent for another pass silently killed the pass it was still
+ // working on; interrupting an in-flight run is what CancelTask /
+ // `multica issue cancel-task` is for.
+ clearPendingSlot := func() int {
+ cancelled, cerr := s.Queries.CancelPendingTasksByIssueAndAgent(ctx, db.CancelPendingTasksByIssueAndAgentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+ if cerr != nil {
+ slog.Warn("rerun: cancel pending tasks failed",
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(agentID),
+ "error", cerr,
+ )
+ }
+ for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
+ s.ReconcileAgentStatus(ctx, t.AgentID)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+ return len(cancelled)
}
+ cancelledCount := clearPendingSlot()
// A manual rerun is a NEW direct_human trigger attributed to the rerunning
// member, not the original run's human (MUL-4302 §5); actorUserID carries them.
@@ -4762,6 +4920,23 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// (rerun_of_task_id) so the queued event / daemon claim never sees a NULL
// lineage, and it stays distinct from system-retry's retry_of_task_id (§5).
task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID)
+ if pendingSlotTakenErr(err) {
+ // The clear above and this enqueue are separate commits, so a system
+ // retry created by a concurrent FailTask can take the pending slot in
+ // between. CreateRetryTask yields the slot when it is already occupied,
+ // but it cannot yield to a row that does not exist yet, so a retry
+ // committing inside this window gets there first. Clear once more and
+ // retry: the deliberate human action is the one that should hold the
+ // slot. Bounded to a single extra attempt — a second collision would mean
+ // something is enqueueing in a loop, which is worth surfacing rather than
+ // spinning on.
+ slog.Info("issue rerun: pending slot taken concurrently, reclaiming",
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(agentID),
+ )
+ cancelledCount += clearPendingSlot()
+ task, err = s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID)
+ }
if err != nil {
return nil, err
}
@@ -4771,7 +4946,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
"agent_id", util.UUIDToString(agentID),
"source_task_id", util.UUIDToString(sourceTaskID),
"is_leader", isLeader,
- "cancelled_prior", len(cancelled),
+ "cancelled_pending", cancelledCount,
)
return &task, nil
}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index c333b20800..3904ebff27 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -581,7 +581,7 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
// Returns the affected rows so callers can broadcast task:cancelled events.
-// Mirrors the shape of CancelAgentTasksByIssue / CancelAgentTasksByIssueAndAgent
+// Mirrors the shape of CancelAgentTasksByIssue / CancelPendingTasksByIssueAndAgent
// (also :many + RETURNING + completed_at) so the three sibling cancel paths
// behave consistently.
func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -830,96 +830,6 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
return items, nil
}
-const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgent :many
-UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
-`
-
-type CancelAgentTasksByIssueAndAgentParams struct {
- IssueID pgtype.UUID `json:"issue_id"`
- AgentID pgtype.UUID `json:"agent_id"`
-}
-
-// Cancels active tasks for a single (issue, agent) pair without touching
-// tasks belonging to other agents on the same issue. Used by the manual
-// rerun flow so re-running the assignee doesn't collateral-cancel a
-// still-running @-mention agent on the same issue.
-func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg CancelAgentTasksByIssueAndAgentParams) ([]AgentTaskQueue, error) {
- rows, err := q.db.Query(ctx, cancelAgentTasksByIssueAndAgent, arg.IssueID, arg.AgentID)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []AgentTaskQueue{}
- for rows.Next() {
- var i AgentTaskQueue
- if err := rows.Scan(
- &i.ID,
- &i.AgentID,
- &i.IssueID,
- &i.Status,
- &i.Priority,
- &i.DispatchedAt,
- &i.StartedAt,
- &i.CompletedAt,
- &i.Result,
- &i.Error,
- &i.CreatedAt,
- &i.Context,
- &i.RuntimeID,
- &i.SessionID,
- &i.WorkDir,
- &i.TriggerCommentID,
- &i.ChatSessionID,
- &i.AutopilotRunID,
- &i.Attempt,
- &i.MaxAttempts,
- &i.ParentTaskID,
- &i.FailureReason,
- &i.TriggerSummary,
- &i.ForceFreshSession,
- &i.IsLeaderTask,
- &i.WaitReason,
- &i.InitiatorUserID,
- &i.HandoffNote,
- &i.PrepareLeaseExpiresAt,
- &i.SquadID,
- &i.RuntimeMcpOverlay,
- &i.EscalationForTaskID,
- &i.FireAt,
- &i.OriginatorUserID,
- &i.RuntimeConnectedApps,
- &i.CoalescedCommentIds,
- &i.DeliveredCommentIds,
- &i.ChatInputTaskID,
- &i.ChatFinalizeDeferredAt,
- &i.OriginatorSource,
- &i.DelegatedFromTaskID,
- &i.RetryOfTaskID,
- &i.RerunOfTaskID,
- &i.RuleVersionID,
- &i.TriggerEvidenceKind,
- &i.TriggerEvidenceRefID,
- &i.AccountableUserID,
- &i.SessionRolloutMissing,
- &i.RetiredSessionID,
- &i.QuickActionsDisabled,
- &i.RegenerateQuickActionsFor,
- &i.BranchName,
- &i.DurableWorkDir,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
@@ -1237,6 +1147,109 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
return items, nil
}
+const cancelPendingTasksByIssueAndAgent = `-- name: CancelPendingTasksByIssueAndAgent :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE issue_id = $1 AND agent_id = $2
+ AND status IN ('queued', 'dispatched', 'deferred')
+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
+`
+
+type CancelPendingTasksByIssueAndAgentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// Cancels the not-yet-started tasks for a single (issue, agent) pair, so the
+// manual rerun flow can enqueue a replacement without colliding with
+// idx_one_pending_task_per_issue_agent_v2 and without dropping the rerun's own
+// attribution onto a row somebody else created.
+//
+// 'running' and 'waiting_local_directory' are deliberately NOT cancelled: an
+// agent is executing in them. Neither status appears in that unique index, so a
+// fresh queued row can be inserted alongside one, and ClaimAgentTask's
+// per-(issue, agent) serialization holds the new row until the active run
+// reaches a terminal state. Cancelling them made a manual rerun kill the pass
+// the agent was still working on; interrupting an in-flight run is CancelTask's
+// job, not rerun's.
+//
+// Everything that has NOT begun executing is still cleared, including deferred
+// escalations, so rerun keeps its prior "replace the pending plan" behaviour for
+// those rows.
+func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg CancelPendingTasksByIssueAndAgentParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelPendingTasksByIssueAndAgent, arg.IssueID, arg.AgentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const cancelQueuedAgentTask = `-- name: CancelQueuedAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
@@ -1418,6 +1431,123 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
return items, nil
}
+const cancelSupersededDeferredRetriesForRuntimes = `-- name: CancelSupersededDeferredRetriesForRuntimes :many
+UPDATE agent_task_queue r
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE r.runtime_id = ANY($1::uuid[])
+ AND r.status = 'deferred'
+ AND r.issue_id IS NOT NULL
+ AND r.retry_of_task_id IS NOT NULL
+ AND r.escalation_for_task_id IS NULL
+ AND COALESCE(r.context->>'channel_issue_media_pending', '') <> 'true'
+ AND EXISTS (
+ SELECT 1 FROM agent_task_queue successor
+ WHERE successor.issue_id = r.issue_id
+ AND successor.agent_id = r.agent_id
+ AND successor.id <> r.id
+ AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ )
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+`
+
+// Cancels deferred auto-retry rows that a newer active task has already
+// superseded, so one rerun click still means exactly one more run.
+//
+// The narrow race: a manual rerun clears the pending slot, a concurrent FailTask
+// commits a deferred retry (runtime_offline / provider_network's final attempt
+// arm fire_at), and the rerun's own enqueue then succeeds because 'deferred' is
+// outside idx_one_pending_task_per_issue_agent_v2. Both rows now exist. Merely
+// refusing to promote the retry is not enough: once the rerun stops occupying the
+// slot the retry promotes and runs a SECOND time, duplicating the agent's
+// comments, side effects and cost with nothing to signal it. That contradicts
+// both "a manual rerun replaces the pending plan" and FailTask's own "a runnable
+// successor already exists, so no retry is needed".
+//
+// Scope is deliberately tight:
+// - retry_of_task_id IS NOT NULL — only auto-retry clones, never a fresh run.
+// - escalation_for_task_id IS NULL — assignee-fallback escalations own their
+// fire_at lifecycle and are SUPPOSED to coexist with an active primary.
+// - channel-media pending rows are excluded for the same reason: that deferred
+// row is the issue's own task waiting on media, not a superseded retry.
+// - issue_id IS NOT NULL — chat / quick-create tasks have no slot semantics.
+//
+// 'running' and 'waiting_local_directory' count as superseding: the duplicate
+// fires precisely when the rerun has STARTED, which is when the row would
+// otherwise no longer look blocked.
+func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context, runtimeIds []pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelSupersededDeferredRetriesForRuntimes, runtimeIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const claimAgentTask = `-- name: ClaimAgentTask :one
UPDATE agent_task_queue
SET status = 'dispatched',
@@ -2719,6 +2849,9 @@ SELECT
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
+ON CONFLICT (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+DO NOTHING
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
`
@@ -2735,6 +2868,22 @@ type CreateRetryTaskParams struct {
// locks the owners' workspace rows in the writer's own transaction and returns
// false once they are gone, so this statement writes no row instead of stranding
// a task in a workspace that has just been deleted (MUL-5999).
+//
+// Fenced against slot contention too: ON CONFLICT DO NOTHING yields the single
+// queued/dispatched slot idx_one_pending_task_per_issue_agent_v2 allows per
+// (issue, agent) rather than raising 23505. A manual rerun may now be enqueued
+// behind a still-running task, and it can commit at any point — including
+// between a caller's "is a successor already pending?" check and this insert,
+// since that check takes no lock. Raising here would abort the caller's
+// transaction, and on the FailTask path that transaction also carries the
+// parent's failed status, so the failure would roll back and leave the task
+// stuck in 'running'. Yielding instead makes the policy explicit: whoever
+// already holds the slot keeps it, and a deliberate human rerun therefore wins
+// over an automatic retry.
+//
+// Both fences surface the same way — zero rows, i.e. pgx.ErrNoRows from this
+// :one query. Callers must treat that as "no retry was created" and still commit
+// their own work, NOT as a failure.
// Clones a parent task into a fresh queued attempt. Carries forward the
// agent's resume context (session_id/work_dir) so the child can continue
// the conversation when the backend supports it. Resume-unsafe failures are
@@ -6575,18 +6724,38 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
}
const promoteDueDeferredTasksForRuntime = `-- name: PromoteDueDeferredTasksForRuntime :many
+WITH due AS (
+ SELECT t.id,
+ t.issue_id,
+ row_number() OVER (
+ PARTITION BY t.issue_id, t.agent_id
+ ORDER BY t.priority DESC, t.created_at ASC, t.id
+ ) AS rn
+ FROM agent_task_queue t
+ WHERE t.runtime_id = $1
+ AND t.status = 'deferred'
+ AND t.fire_at <= now()
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND r.status = 'online'
+ AND COALESCE(r.last_seen_at, r.updated_at) >=
+ now() - make_interval(secs => $2::double precision)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue occupant
+ WHERE occupant.issue_id = t.issue_id
+ AND occupant.agent_id = t.agent_id
+ AND occupant.id <> t.id
+ AND (
+ occupant.status IN ('queued', 'dispatched')
+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')
+ )
+ )
+)
UPDATE agent_task_queue
SET status = 'queued'
-WHERE runtime_id = $1
- AND status = 'deferred'
- AND fire_at <= now()
- AND EXISTS (
- SELECT 1 FROM agent_runtime r
- WHERE r.id = agent_task_queue.runtime_id
- AND r.status = 'online'
- AND COALESCE(r.last_seen_at, r.updated_at) >=
- now() - make_interval(secs => $2::double precision)
- )
+WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
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
`
@@ -6595,6 +6764,21 @@ type PromoteDueDeferredTasksForRuntimeParams struct {
RuntimeStaleSecs float64 `json:"runtime_stale_secs"`
}
+// Promotion is fenced against the single queued/dispatched slot
+// idx_one_pending_task_per_issue_agent_v2 allows per (issue, agent). A deferred
+// row is NOT covered by that index, so it can legitimately coexist with a queued
+// one — a manual rerun enqueued behind a running task, plus the deferred retry
+// that task's failure armed (runtime_offline, provider_network's final attempt).
+// Flipping such a row to 'queued' unconditionally violates the index, and because
+// the claim loop promotes before it claims, that error blocked every claim on the
+// runtime — including the rerun the operator was waiting for.
+//
+// Two fences: skip a row whose (issue, agent) slot is already occupied, and
+// promote at most ONE row per (issue, agent) so a single statement cannot collide
+// with itself. A skipped row stays deferred with fire_at in the past and is
+// promoted by a later tick once the slot frees, so nothing is lost — the human's
+// rerun simply goes first. Chat / quick-create rows (issue_id NULL) are outside
+// the index and bypass both fences.
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg PromoteDueDeferredTasksForRuntimeParams) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntime, arg.RuntimeID, arg.RuntimeStaleSecs)
if err != nil {
@@ -6670,18 +6854,38 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro
}
const promoteDueDeferredTasksForRuntimes = `-- name: PromoteDueDeferredTasksForRuntimes :many
+WITH due AS (
+ SELECT t.id,
+ t.issue_id,
+ row_number() OVER (
+ PARTITION BY t.issue_id, t.agent_id
+ ORDER BY t.priority DESC, t.created_at ASC, t.id
+ ) AS rn
+ FROM agent_task_queue t
+ WHERE t.runtime_id = ANY($1::uuid[])
+ AND t.status = 'deferred'
+ AND t.fire_at <= now()
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND r.status = 'online'
+ AND COALESCE(r.last_seen_at, r.updated_at) >=
+ now() - make_interval(secs => $2::double precision)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue occupant
+ WHERE occupant.issue_id = t.issue_id
+ AND occupant.agent_id = t.agent_id
+ AND occupant.id <> t.id
+ AND (
+ occupant.status IN ('queued', 'dispatched')
+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')
+ )
+ )
+)
UPDATE agent_task_queue
SET status = 'queued'
-WHERE runtime_id = ANY($1::uuid[])
- AND status = 'deferred'
- AND fire_at <= now()
- AND EXISTS (
- SELECT 1 FROM agent_runtime r
- WHERE r.id = agent_task_queue.runtime_id
- AND r.status = 'online'
- AND COALESCE(r.last_seen_at, r.updated_at) >=
- now() - make_interval(secs => $2::double precision)
- )
+WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
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
`
@@ -6691,7 +6895,8 @@ type PromoteDueDeferredTasksForRuntimesParams struct {
}
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
-// due deferred tasks across the runtime set in one UPDATE.
+// due deferred tasks across the runtime set in one UPDATE. Carries the same two
+// fences as the singular query; see its comment for why.
func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg PromoteDueDeferredTasksForRuntimesParams) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntimes, arg.RuntimeIds, arg.RuntimeStaleSecs)
if err != nil {
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 2e4cfcf79b..dc0d29e3de 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -512,6 +512,22 @@ WHERE id = $1 AND issue_id IS NULL
-- locks the owners' workspace rows in the writer's own transaction and returns
-- false once they are gone, so this statement writes no row instead of stranding
-- a task in a workspace that has just been deleted (MUL-5999).
+--
+-- Fenced against slot contention too: ON CONFLICT DO NOTHING yields the single
+-- queued/dispatched slot idx_one_pending_task_per_issue_agent_v2 allows per
+-- (issue, agent) rather than raising 23505. A manual rerun may now be enqueued
+-- behind a still-running task, and it can commit at any point — including
+-- between a caller's "is a successor already pending?" check and this insert,
+-- since that check takes no lock. Raising here would abort the caller's
+-- transaction, and on the FailTask path that transaction also carries the
+-- parent's failed status, so the failure would roll back and leave the task
+-- stuck in 'running'. Yielding instead makes the policy explicit: whoever
+-- already holds the slot keeps it, and a deliberate human rerun therefore wins
+-- over an automatic retry.
+--
+-- Both fences surface the same way — zero rows, i.e. pgx.ErrNoRows from this
+-- :one query. Callers must treat that as "no retry was created" and still commit
+-- their own work, NOT as a failure.
-- Clones a parent task into a fresh queued attempt. Carries forward the
-- agent's resume context (session_id/work_dir) so the child can continue
-- the conversation when the backend supports it. Resume-unsafe failures are
@@ -599,6 +615,9 @@ SELECT
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
+ON CONFLICT (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+DO NOTHING
RETURNING *;
-- name: CancelAgentTasksByIssue :many
@@ -612,20 +631,33 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
--- name: CancelAgentTasksByIssueAndAgent :many
--- Cancels active tasks for a single (issue, agent) pair without touching
--- tasks belonging to other agents on the same issue. Used by the manual
--- rerun flow so re-running the assignee doesn't collateral-cancel a
--- still-running @-mention agent on the same issue.
+-- name: CancelPendingTasksByIssueAndAgent :many
+-- Cancels the not-yet-started tasks for a single (issue, agent) pair, so the
+-- manual rerun flow can enqueue a replacement without colliding with
+-- idx_one_pending_task_per_issue_agent_v2 and without dropping the rerun's own
+-- attribution onto a row somebody else created.
+--
+-- 'running' and 'waiting_local_directory' are deliberately NOT cancelled: an
+-- agent is executing in them. Neither status appears in that unique index, so a
+-- fresh queued row can be inserted alongside one, and ClaimAgentTask's
+-- per-(issue, agent) serialization holds the new row until the active run
+-- reaches a terminal state. Cancelling them made a manual rerun kill the pass
+-- the agent was still working on; interrupting an in-flight run is CancelTask's
+-- job, not rerun's.
+--
+-- Everything that has NOT begun executing is still cleared, including deferred
+-- escalations, so rerun keeps its prior "replace the pending plan" behaviour for
+-- those rows.
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+WHERE issue_id = $1 AND agent_id = $2
+ AND status IN ('queued', 'dispatched', 'deferred')
RETURNING *;
-- 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.
--- Mirrors the shape of CancelAgentTasksByIssue / CancelAgentTasksByIssueAndAgent
+-- Mirrors the shape of CancelAgentTasksByIssue / CancelPendingTasksByIssueAndAgent
-- (also :many + RETURNING + completed_at) so the three sibling cancel paths
-- behave consistently.
UPDATE agent_task_queue
@@ -1951,19 +1983,96 @@ SELECT * FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC;
+-- name: CancelSupersededDeferredRetriesForRuntimes :many
+-- Cancels deferred auto-retry rows that a newer active task has already
+-- superseded, so one rerun click still means exactly one more run.
+--
+-- The narrow race: a manual rerun clears the pending slot, a concurrent FailTask
+-- commits a deferred retry (runtime_offline / provider_network's final attempt
+-- arm fire_at), and the rerun's own enqueue then succeeds because 'deferred' is
+-- outside idx_one_pending_task_per_issue_agent_v2. Both rows now exist. Merely
+-- refusing to promote the retry is not enough: once the rerun stops occupying the
+-- slot the retry promotes and runs a SECOND time, duplicating the agent's
+-- comments, side effects and cost with nothing to signal it. That contradicts
+-- both "a manual rerun replaces the pending plan" and FailTask's own "a runnable
+-- successor already exists, so no retry is needed".
+--
+-- Scope is deliberately tight:
+-- * retry_of_task_id IS NOT NULL — only auto-retry clones, never a fresh run.
+-- * escalation_for_task_id IS NULL — assignee-fallback escalations own their
+-- fire_at lifecycle and are SUPPOSED to coexist with an active primary.
+-- * channel-media pending rows are excluded for the same reason: that deferred
+-- row is the issue's own task waiting on media, not a superseded retry.
+-- * issue_id IS NOT NULL — chat / quick-create tasks have no slot semantics.
+--
+-- 'running' and 'waiting_local_directory' count as superseding: the duplicate
+-- fires precisely when the rerun has STARTED, which is when the row would
+-- otherwise no longer look blocked.
+UPDATE agent_task_queue r
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE r.runtime_id = ANY(@runtime_ids::uuid[])
+ AND r.status = 'deferred'
+ AND r.issue_id IS NOT NULL
+ AND r.retry_of_task_id IS NOT NULL
+ AND r.escalation_for_task_id IS NULL
+ AND COALESCE(r.context->>'channel_issue_media_pending', '') <> 'true'
+ AND EXISTS (
+ SELECT 1 FROM agent_task_queue successor
+ WHERE successor.issue_id = r.issue_id
+ AND successor.agent_id = r.agent_id
+ AND successor.id <> r.id
+ AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ )
+RETURNING *;
+
-- name: PromoteDueDeferredTasksForRuntime :many
+-- Promotion is fenced against the single queued/dispatched slot
+-- idx_one_pending_task_per_issue_agent_v2 allows per (issue, agent). A deferred
+-- row is NOT covered by that index, so it can legitimately coexist with a queued
+-- one — a manual rerun enqueued behind a running task, plus the deferred retry
+-- that task's failure armed (runtime_offline, provider_network's final attempt).
+-- Flipping such a row to 'queued' unconditionally violates the index, and because
+-- the claim loop promotes before it claims, that error blocked every claim on the
+-- runtime — including the rerun the operator was waiting for.
+--
+-- Two fences: skip a row whose (issue, agent) slot is already occupied, and
+-- promote at most ONE row per (issue, agent) so a single statement cannot collide
+-- with itself. A skipped row stays deferred with fire_at in the past and is
+-- promoted by a later tick once the slot frees, so nothing is lost — the human's
+-- rerun simply goes first. Chat / quick-create rows (issue_id NULL) are outside
+-- the index and bypass both fences.
+WITH due AS (
+ SELECT t.id,
+ t.issue_id,
+ row_number() OVER (
+ PARTITION BY t.issue_id, t.agent_id
+ ORDER BY t.priority DESC, t.created_at ASC, t.id
+ ) AS rn
+ FROM agent_task_queue t
+ WHERE t.runtime_id = @runtime_id
+ AND t.status = 'deferred'
+ AND t.fire_at <= now()
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND r.status = 'online'
+ AND COALESCE(r.last_seen_at, r.updated_at) >=
+ now() - make_interval(secs => @runtime_stale_secs::double precision)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue occupant
+ WHERE occupant.issue_id = t.issue_id
+ AND occupant.agent_id = t.agent_id
+ AND occupant.id <> t.id
+ AND (
+ occupant.status IN ('queued', 'dispatched')
+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')
+ )
+ )
+)
UPDATE agent_task_queue
SET status = 'queued'
-WHERE runtime_id = @runtime_id
- AND status = 'deferred'
- AND fire_at <= now()
- AND EXISTS (
- SELECT 1 FROM agent_runtime r
- WHERE r.id = agent_task_queue.runtime_id
- AND r.status = 'online'
- AND COALESCE(r.last_seen_at, r.updated_at) >=
- now() - make_interval(secs => @runtime_stale_secs::double precision)
- )
+WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
RETURNING *;
-- name: ListQueuedClaimCandidatesByRuntimes :many
@@ -1983,19 +2092,40 @@ ORDER BY priority DESC, created_at ASC;
-- name: PromoteDueDeferredTasksForRuntimes :many
-- Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
--- due deferred tasks across the runtime set in one UPDATE.
+-- due deferred tasks across the runtime set in one UPDATE. Carries the same two
+-- fences as the singular query; see its comment for why.
+WITH due AS (
+ SELECT t.id,
+ t.issue_id,
+ row_number() OVER (
+ PARTITION BY t.issue_id, t.agent_id
+ ORDER BY t.priority DESC, t.created_at ASC, t.id
+ ) AS rn
+ FROM agent_task_queue t
+ WHERE t.runtime_id = ANY(@runtime_ids::uuid[])
+ AND t.status = 'deferred'
+ AND t.fire_at <= now()
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND r.status = 'online'
+ AND COALESCE(r.last_seen_at, r.updated_at) >=
+ now() - make_interval(secs => @runtime_stale_secs::double precision)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue occupant
+ WHERE occupant.issue_id = t.issue_id
+ AND occupant.agent_id = t.agent_id
+ AND occupant.id <> t.id
+ AND (
+ occupant.status IN ('queued', 'dispatched')
+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')
+ )
+ )
+)
UPDATE agent_task_queue
SET status = 'queued'
-WHERE runtime_id = ANY(@runtime_ids::uuid[])
- AND status = 'deferred'
- AND fire_at <= now()
- AND EXISTS (
- SELECT 1 FROM agent_runtime r
- WHERE r.id = agent_task_queue.runtime_id
- AND r.status = 'online'
- AND COALESCE(r.last_seen_at, r.updated_at) >=
- now() - make_interval(secs => @runtime_stale_secs::double precision)
- )
+WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
RETURNING *;
-- name: CancelDeferredEscalationsForTask :many