Skip to content

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

Go

MUL-8200: fix(autopilot): don't fail create_issue runs on issue blocked (#9472)

Multica Eveb51f42c54be4
diff --git a/server/cmd/server/autopilot_listeners.go b/server/cmd/server/autopilot_listeners.go
index 425e6601c6..056d88b627 100644
--- a/server/cmd/server/autopilot_listeners.go
+++ b/server/cmd/server/autopilot_listeners.go
@@ -39,7 +39,7 @@ func registerAutopilotListeners(bus *events.Bus, svc *service.AutopilotService)
// SyncRunFromIssue normalize once it has the issue. (MUL-6243)
if issuestatus.IsBuiltIn(issue.Status) &&
issue.Status != "done" && issue.Status != "in_review" &&
- issue.Status != "cancelled" && issue.Status != "blocked" {
+ issue.Status != "cancelled" {
return
}
// Load the full issue from DB to check origin_type.
@@ -80,7 +80,9 @@ func syncRunFromTaskEvent(ctx context.Context, svc *service.AutopilotService, e
svc.SyncRunFromTask(ctx, task)
return
}
- if e.Type == protocol.EventTaskFailed {
+ // create_issue tasks link to their run only through issue_id. Completion
+ // settles the run as success; terminal failure settles it as failed.
+ if e.Type == protocol.EventTaskCompleted || e.Type == protocol.EventTaskFailed {
svc.SyncRunFromLinkedIssueTask(ctx, task)
}
}
diff --git a/server/cmd/server/autopilot_listeners_test.go b/server/cmd/server/autopilot_listeners_test.go
index f902ea4efe..8bde24c6a1 100644
--- a/server/cmd/server/autopilot_listeners_test.go
+++ b/server/cmd/server/autopilot_listeners_test.go
@@ -8,7 +8,10 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/service"
+ dbfx "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// seedAutopilotScheduleTrigger gives an autopilot a schedule trigger recording its
@@ -148,10 +151,11 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
// issue_created with exactly one issue task that carries no autopilot_run_id
// (so it must be reached via the issue_id lookup, not SyncRunFromTask).
type linkedIssueAutopilotFixture struct {
- taskSvc *service.TaskService
- queries *db.Queries
- run *db.AutopilotRun
- taskID pgtype.UUID
+ taskSvc *service.TaskService
+ autopilotSvc *service.AutopilotService
+ queries *db.Queries
+ run *db.AutopilotRun
+ taskID pgtype.UUID
}
// dispatchCreateIssueAutopilot creates an active create_issue autopilot,
@@ -220,7 +224,7 @@ func dispatchCreateIssueAutopilot(t *testing.T, title string) linkedIssueAutopil
t.Fatalf("expected pre-failure run status issue_created, got %q", run.Status)
}
- return linkedIssueAutopilotFixture{taskSvc: taskSvc, queries: queries, run: run, taskID: tasks[0].ID}
+ return linkedIssueAutopilotFixture{taskSvc: taskSvc, autopilotSvc: autopilotSvc, queries: queries, run: run, taskID: tasks[0].ID}
}
// runTaskWithBudget marks the issue task dispatched with the given attempt
@@ -329,6 +333,400 @@ func TestAutopilotCreateIssueTaskRetryPendingKeepsRunOpen(t *testing.T) {
}
}
+// setLinkedIssueStatus moves the run's linked issue to status and feeds the
+// reloaded row to SyncRunFromIssue, the same entry the issue:updated listener
+// reaches after its status gate.
+func setLinkedIssueStatus(t *testing.T, f linkedIssueAutopilotFixture, status string) {
+ t.Helper()
+ ctx := context.Background()
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET status = $2 WHERE id = $1`, f.run.IssueID, status); err != nil {
+ t.Fatalf("set issue status %q: %v", status, err)
+ }
+ issue, err := f.queries.GetIssue(ctx, f.run.IssueID)
+ if err != nil {
+ t.Fatalf("GetIssue: %v", err)
+ }
+ f.autopilotSvc.SyncRunFromIssue(ctx, issue)
+}
+
+func requireRunStatus(t *testing.T, f linkedIssueAutopilotFixture, want string) db.AutopilotRun {
+ t.Helper()
+ run, err := f.queries.GetAutopilotRun(context.Background(), f.run.ID)
+ if err != nil {
+ t.Fatalf("GetAutopilotRun: %v", err)
+ }
+ if run.Status != want {
+ t.Fatalf("expected run status %q, got %q (reason %+v)", want, run.Status, run.FailureReason)
+ }
+ return run
+}
+
+// TestAutopilotCreateIssueTaskCompletionCompletesRun: the first agent task on
+// the linked issue finishing cleanly is run success, and a later blocked
+// status on the issue must not flip it to failed. (MUL-8200)
+func TestAutopilotCreateIssueTaskCompletionCompletesRun(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Create-issue completion listener")
+
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ if _, err := f.taskSvc.CompleteTask(ctx, f.taskID, []byte(`{"output":"done"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ requireRunStatus(t, f, "completed")
+
+ setLinkedIssueStatus(t, f, "blocked")
+ requireRunStatus(t, f, "completed")
+ setLinkedIssueStatus(t, f, "cancelled")
+ requireRunStatus(t, f, "completed")
+}
+
+// TestAutopilotCreateIssueBlockedIssueKeepsRunOpen is the MUL-8198 shape: a
+// reviewer blocks the issue while the autopilot's task is still running. The
+// run must stay open and complete once the task finishes. (MUL-8200)
+func TestAutopilotCreateIssueBlockedIssueKeepsRunOpen(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Create-issue blocked listener")
+
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ setLinkedIssueStatus(t, f, "blocked")
+ requireRunStatus(t, f, "issue_created")
+
+ if _, err := f.taskSvc.CompleteTask(ctx, f.taskID, []byte(`{"output":"done"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ requireRunStatus(t, f, "completed")
+}
+
+// TestAutopilotCreateIssueCancelledBeforeTaskFailsRun: cancelling the issue
+// before any task finishes still fails the run, so it does not hang. (MUL-8200)
+func TestAutopilotCreateIssueCancelledBeforeTaskFailsRun(t *testing.T) {
+ f := dispatchCreateIssueAutopilot(t, "Create-issue cancelled listener")
+
+ setLinkedIssueStatus(t, f, "cancelled")
+ run := requireRunStatus(t, f, "failed")
+ if !run.FailureReason.Valid || run.FailureReason.String != "issue cancelled" {
+ t.Fatalf("expected failure reason %q, got %+v", "issue cancelled", run.FailureReason)
+ }
+}
+
+// TestAutopilotCreateIssueEarlyDeliveryWaitsForTaskOutcome: an issue moved to
+// in_review/done while the dispatch task still runs must not complete the run;
+// the task's failure decides it. (MUL-8200 review)
+func TestAutopilotCreateIssueEarlyDeliveryWaitsForTaskOutcome(t *testing.T) {
+ for _, status := range []string{"in_review", "done"} {
+ t.Run(status, func(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Create-issue early delivery "+status)
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ setLinkedIssueStatus(t, f, status)
+ before, err := f.queries.GetAutopilotRun(ctx, f.run.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if before.Status != "issue_created" {
+ t.Errorf("issue became %s while first task is still running: run=%s, want issue_created", status, before.Status)
+ }
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime exited after setting issue status", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+ })
+ }
+}
+
+// TestAutopilotCreateIssueUnrelatedMentionDoesNotSettleRun: a mention task on
+// the same issue completing must not stand in for the autopilot's own
+// dispatch. (MUL-8200 review)
+func TestAutopilotCreateIssueUnrelatedMentionDoesNotSettleRun(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Create-issue unrelated mention")
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ first, err := f.queries.GetAgentTask(ctx, f.taskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ otherAgent := fixture.Agent(t, "Other mentioned agent", util.UUIDToString(first.RuntimeID))
+ comment := fixture.Comment(t, util.UUIDToString(f.run.IssueID), "Please answer a quick question")
+ issue, err := f.queries.GetIssue(ctx, f.run.IssueID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := f.taskSvc.EnqueueTaskForMention(ctx, issue, parseUUID(otherAgent), parseUUID(comment), service.OriginNamed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixture.Cleanup(t, "DELETE FROM agent_task_queue WHERE id = $1", other.ID)
+ runTaskWithBudget(t, f.queries, other.ID, 1)
+ if _, err := f.taskSvc.CompleteTask(ctx, other.ID, []byte(`{"output":"Answer to the quick question"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ before, err := f.queries.GetAutopilotRun(ctx, f.run.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if before.Status != "issue_created" {
+ t.Errorf("unrelated mention completed while original task is running: run=%s, want issue_created", before.Status)
+ }
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "original autopilot task crashed", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+}
+
+// TestAutopilotCreateIssueRetryCompletionCompletesRun: an auto-retry of the
+// dispatch task is part of the dispatch chain, so its success completes the run.
+func TestAutopilotCreateIssueRetryCompletionCompletesRun(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Create-issue retry completion listener")
+
+ runTaskWithBudget(t, f.queries, f.taskID, 2)
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime went offline", "", "", "", "timeout", false, "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+ requireRunStatus(t, f, "issue_created")
+
+ var retryID pgtype.UUID
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_task_queue WHERE retry_of_task_id = $1`, f.taskID).Scan(&retryID); err != nil {
+ t.Fatalf("load retry task: %v", err)
+ }
+ runTaskWithBudget(t, f.queries, retryID, 2)
+ if _, err := f.taskSvc.CompleteTask(ctx, retryID, []byte(`{"output":"done"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask retry: %v", err)
+ }
+ requireRunStatus(t, f, "completed")
+}
+
+// TestAutopilotCreateIssueDeliveryAfterCommittedFailureFailsRun: the dispatch
+// failure is committed but task:failed not yet processed when the issue moves
+// to in_review; the committed failure must win. (MUL-8200 re-review)
+func TestAutopilotCreateIssueDeliveryAfterCommittedFailureFailsRun(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Delivery racing failure notification")
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ observed := false
+ // Failure comments publish after the failed row commits but before task:failed.
+ // Interleave an issue status update in that real callback window.
+ f.taskSvc.Bus.Subscribe(protocol.EventCommentCreated, func(e events.Event) {
+ task, err := f.queries.GetAgentTask(ctx, f.taskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if task.Status != "failed" {
+ t.Fatalf("expected a committed failure, got %s", task.Status)
+ }
+ observed = true
+ setLinkedIssueStatus(t, f, "in_review")
+ })
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "dispatch task crashed", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ if !observed {
+ t.Fatal("did not exercise the post-commit/pre-task-event window")
+ }
+ requireRunStatus(t, f, "failed")
+}
+
+// TestAutopilotCreateIssueMentionEnqueuedBeforeDispatch: a mention task
+// enqueued between issue:created and the dispatch enqueue is older than the
+// real dispatch and must still not settle the run. (MUL-8200 re-review)
+func TestAutopilotCreateIssueMentionEnqueuedBeforeDispatch(t *testing.T) {
+ ctx := context.Background()
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ runtimeID := fixture.Runtime(t, "Dispatch order runtime")
+ ownerID := fixture.Agent(t, "Autopilot assignee", runtimeID)
+ otherID := fixture.Agent(t, "Early mention agent", runtimeID)
+ queries := db.New(testPool)
+ bus := events.New()
+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)
+ apSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)
+ registerAutopilotListeners(bus, apSvc)
+ ap, err := queries.CreateAutopilot(ctx, db.CreateAutopilotParams{
+ WorkspaceID: parseUUID(testWorkspaceID), Title: "Dispatch order autopilot",
+ AssigneeType: "agent", AssigneeID: parseUUID(ownerID), Status: "active",
+ ExecutionMode: "create_issue", IssueTitleTemplate: pgtype.Text{String: "Dispatch order issue", Valid: true},
+ CreatedByType: "member", CreatedByID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixture.Cleanup(t, "DELETE FROM autopilot WHERE id = $1", ap.ID)
+ var mention db.AgentTaskQueue
+ // The issue is already committed and externally readable at issue:created.
+ // Pause dispatch here to exercise a mention arriving before its later enqueue.
+ bus.Subscribe(protocol.EventIssueCreated, func(e events.Event) {
+ var issueID pgtype.UUID
+ fixture.QueryRow(t, "SELECT id FROM issue WHERE origin_id = $1", ap.ID).Scan(&issueID)
+ fixture.Cleanup(t, "DELETE FROM issue WHERE id = $1", issueID)
+ fixture.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", issueID)
+ fixture.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", issueID)
+ issue, err := queries.GetIssue(ctx, issueID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ commentID := fixture.Comment(t, util.UUIDToString(issueID), "Quick question for the other agent")
+ mention, err = taskSvc.EnqueueTaskForMention(ctx, issue, parseUUID(otherID), parseUUID(commentID), service.OriginNamed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ })
+ run, err := apSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "schedule", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var dispatchedID pgtype.UUID
+ fixture.QueryRow(t, "SELECT id FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2", run.IssueID, ownerID).Scan(&dispatchedID)
+ f := linkedIssueAutopilotFixture{taskSvc: taskSvc, autopilotSvc: apSvc, queries: queries, run: run, taskID: dispatchedID}
+ runTaskWithBudget(t, queries, dispatchedID, 1)
+ runTaskWithBudget(t, queries, mention.ID, 1)
+ if _, err := taskSvc.CompleteTask(ctx, mention.ID, []byte(`{"output":"Quick answer"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ state, err := queries.GetAutopilotRun(ctx, run.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if state.Status != "issue_created" {
+ t.Errorf("early unrelated mention completed the run: got %s, want issue_created", state.Status)
+ }
+ if _, err := taskSvc.FailTask(ctx, dispatchedID, "real dispatch failed", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+}
+
+// TestAutopilotCreateIssueDeliveryBetweenEnqueueAndLink: in_review lands after
+// the dispatch task is queued but before its link is written; the task's
+// failure must still fail the run. (MUL-8200 third review)
+func TestAutopilotCreateIssueDeliveryBetweenEnqueueAndLink(t *testing.T) {
+ ctx := context.Background()
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ runtimeID := fixture.Runtime(t, "Link window runtime")
+ agentID := fixture.Agent(t, "Link window assignee", runtimeID)
+ queries := db.New(testPool)
+ bus := events.New()
+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)
+ apSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)
+ registerAutopilotListeners(bus, apSvc)
+ ap, err := queries.CreateAutopilot(ctx, db.CreateAutopilotParams{
+ WorkspaceID: parseUUID(testWorkspaceID), Title: "Link window autopilot",
+ AssigneeType: "agent", AssigneeID: parseUUID(agentID), Status: "active",
+ ExecutionMode: "create_issue", IssueTitleTemplate: pgtype.Text{String: "Link window issue", Valid: true},
+ CreatedByType: "member", CreatedByID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ fixture.Cleanup(t, "DELETE FROM autopilot WHERE id = $1", ap.ID)
+ var f linkedIssueAutopilotFixture
+ // The task is committed and announced before EnqueueTaskForIssue returns.
+ // A status request may be handled here before linkDispatchTask runs.
+ bus.Subscribe(protocol.EventTaskQueued, func(e events.Event) {
+ taskID := parseUUID(e.Payload.(map[string]any)["task_id"].(string))
+ task, err := queries.GetAgentTask(ctx, taskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ run, err := queries.GetAutopilotRunByIssue(ctx, task.IssueID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if run.TaskID.Valid {
+ t.Fatal("did not exercise the pre-link window")
+ }
+ fixture.Cleanup(t, "DELETE FROM issue WHERE id = $1", task.IssueID)
+ fixture.Cleanup(t, "DELETE FROM comment WHERE issue_id = $1", task.IssueID)
+ fixture.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", task.IssueID)
+ f = linkedIssueAutopilotFixture{taskSvc: taskSvc, autopilotSvc: apSvc, queries: queries, run: &run, taskID: taskID}
+ runTaskWithBudget(t, queries, taskID, 1)
+ setLinkedIssueStatus(t, f, "in_review")
+ })
+ if _, err := apSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "schedule", nil); err != nil {
+ t.Fatal(err)
+ }
+ if f.run == nil {
+ t.Fatal("queued event was not observed")
+ }
+ if _, err := taskSvc.FailTask(ctx, f.taskID, "failed after early delivery", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+}
+
+// TestAutopilotCreateIssueWebhookRecoveryLinksDispatch: a webhook-recovered
+// dispatch (crash before enqueue or before link) still settles the run from
+// its task outcome. (MUL-8200 third review)
+func TestAutopilotCreateIssueWebhookRecoveryLinksDispatch(t *testing.T) {
+ for _, taskWasEnqueued := range []bool{false, true} {
+ name := "before_enqueue"
+ if taskWasEnqueued {
+ name = "after_enqueue_before_link"
+ }
+ t.Run(name, func(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Webhook recovery "+name)
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ // Reproduce the durable state left by a worker crash after issue
+ // creation, either before enqueue or just before recording the link.
+ fixture.Exec(t, "UPDATE autopilot_run SET task_id = NULL, source = 'webhook', webhook_delivery_id = id WHERE id = $1", f.run.ID)
+ if !taskWasEnqueued {
+ fixture.Exec(t, "DELETE FROM agent_task_queue WHERE id = $1", f.taskID)
+ }
+ ap, err := f.queries.GetAutopilot(ctx, f.run.AutopilotID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.autopilotSvc.DispatchAutopilotForWebhookDelivery(ctx, ap, f.run.TriggerID, nil, f.run.ID); err != nil {
+ t.Fatal(err)
+ }
+ tasks, err := f.queries.ListTasksByIssue(ctx, f.run.IssueID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tasks) != 1 {
+ t.Fatalf("recovery produced %d tasks, want one", len(tasks))
+ }
+ runTaskWithBudget(t, f.queries, tasks[0].ID, 1)
+ if _, err := f.taskSvc.FailTask(ctx, tasks[0].ID, "recovered dispatch failed", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+ })
+ }
+}
+
+// TestAutopilotCreateIssuePreUpgradeRunObservesTaskFailure: an active run
+// dispatched before task_id was recorded still fails from its dispatch task.
+// (MUL-8200 third review)
+func TestAutopilotCreateIssuePreUpgradeRunObservesTaskFailure(t *testing.T) {
+ ctx := context.Background()
+ f := dispatchCreateIssueAutopilot(t, "Pre-upgrade running autopilot")
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ fixture.Exec(t, "UPDATE autopilot_run SET task_id = NULL WHERE id = $1", f.run.ID)
+ runTaskWithBudget(t, f.queries, f.taskID, 1)
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "pre-upgrade dispatch failed", "", "", "", "agent_error", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ requireRunStatus(t, f, "failed")
+}
+
+// TestAutopilotCreateIssueDeliveryWithoutDispatchTask: with no dispatch task
+// yet, in_review waits while the issue is agent-assigned (enqueue pending) and
+// completes the run once the issue belongs to a member. (MUL-8200)
+func TestAutopilotCreateIssueDeliveryWithoutDispatchTask(t *testing.T) {
+ f := dispatchCreateIssueAutopilot(t, "Create-issue delivery without dispatch task")
+ fixture := dbfx.New(testPool, testWorkspaceID, testUserID)
+ fixture.Exec(t, "UPDATE autopilot_run SET task_id = NULL WHERE id = $1", f.run.ID)
+ fixture.Exec(t, "DELETE FROM agent_task_queue WHERE id = $1", f.taskID)
+
+ setLinkedIssueStatus(t, f, "in_review")
+ requireRunStatus(t, f, "issue_created")
+
+ fixture.Exec(t, "UPDATE issue SET assignee_type = 'member', assignee_id = $2 WHERE id = $1", f.run.IssueID, parseUUID(testUserID))
+ setLinkedIssueStatus(t, f, "done")
+ requireRunStatus(t, f, "completed")
+}
+
// TestAutopilotDispatchSkipsWhenRuntimeOffline locks in the MUL-1899
// admission gate: when the assignee agent's runtime is not online we must
// record a `skipped` autopilot_run with a failure_reason and NOT enqueue an
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 4e3ebbae54..bb68b91dca 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -367,14 +367,18 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, aut
if err != nil {
return fmt.Errorf("dispatch for webhook delivery: resolve squad leader: %w", err)
}
- if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}, OriginDerived); err != nil {
+ task, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}, OriginDerived)
+ if err != nil {
return fmt.Errorf("dispatch for webhook delivery: repair squad task: %w", err)
}
+ s.linkDispatchTask(ctx, &run, task)
return nil
}
- if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
+ task, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue)
+ if err != nil {
return fmt.Errorf("dispatch for webhook delivery: repair issue task: %w", err)
}
+ s.linkDispatchTask(ctx, &run, task)
return nil
}
@@ -838,6 +842,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
// webhook dispatch has no actor and takes the plain entry points, where the
// autopilot-origin issue resolves to the trigger's created_by principal
// (MUL-6951). The *ByActor variants are the actor-carrying enqueue methods.
+ var dispatchTask db.AgentTaskQueue
if ap.AssigneeType == "squad" {
// Fail-closed invocation gate: verify the admission principal (manual
// clicker, else the trigger's created_by — see autopilotAdmitInvoke) may
@@ -847,19 +852,20 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
return fmt.Errorf("not allowed to invoke private squad leader")
}
if actorUserID.Valid {
- if _, err := s.TaskSvc.EnqueueTaskForSquadLeaderByActor(ctx, issue, leader.ID, ap.AssigneeID, actorUserID); err != nil {
+ if dispatchTask, err = s.TaskSvc.EnqueueTaskForSquadLeaderByActor(ctx, issue, leader.ID, ap.AssigneeID, actorUserID); err != nil {
return fmt.Errorf("enqueue squad leader task: %w", err)
}
- } else if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}, OriginDerived); err != nil {
+ } else if dispatchTask, err = s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}, OriginDerived); err != nil {
return fmt.Errorf("enqueue squad leader task: %w", err)
}
} else if actorUserID.Valid {
- if _, err := s.TaskSvc.EnqueueTaskForIssueByActor(ctx, issue, actorUserID); err != nil {
+ if dispatchTask, err = s.TaskSvc.EnqueueTaskForIssueByActor(ctx, issue, actorUserID); err != nil {
return fmt.Errorf("enqueue task for issue: %w", err)
}
- } else if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
+ } else if dispatchTask, err = s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
return fmt.Errorf("enqueue task for issue: %w", err)
}
+ s.linkDispatchTask(ctx, run, dispatchTask)
slog.Info("autopilot dispatched (create_issue)",
"autopilot_id", util.UUIDToString(ap.ID),
@@ -1087,7 +1093,26 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
return nil
}
-// SyncRunFromIssue updates the autopilot run when its linked issue reaches a terminal status.
+// SyncRunFromIssue updates the autopilot run when its linked issue reaches a
+// status that settles the run without a task outcome.
+//
+// For create_issue runs, the run tracks the autopilot's own execution, not the
+// business outcome of the issue: the first agent task finishing cleanly
+// completes the run (SyncRunFromLinkedIssueTask). `blocked` is therefore no
+// longer a run failure — a review that blocks the issue is a normal result,
+// not an autopilot fault, and counting it as one also skewed the failure-rate
+// auto-pause. Only two issue transitions still settle an active run here:
+// - done / in_review: the work was delivered. While the run's dispatch
+// task is in flight (or not yet enqueued) this waits; once it is terminal
+// its completed/failed outcome decides. Only an issue no agent will be
+// dispatched to (reassigned to a member / unassigned) or a cancelled
+// dispatch completes from the issue status.
+// - cancelled: someone cancelled the issue before any task finished, so the
+// run fails with "issue cancelled" instead of hanging forever.
+//
+// Both only apply while the run is still active (GetAutopilotRunByIssue
+// filters on issue_created/running), so a run already completed by its task
+// is never reopened or flipped by later issue status changes. (MUL-8200)
func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue) {
if !issue.OriginType.Valid || issue.OriginType.String != "autopilot" {
return
@@ -1105,7 +1130,7 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
wsID := util.UUIDToString(issue.WorkspaceID)
// Custom statuses only finalize terminal lifecycle (done/closed). Review
- // completion and blocked failure remain exclusive to the fixed built-in keys.
+ // completion remains exclusive to the fixed built-in key.
// The failure reason below deliberately keeps issue.Status, not the
// normalized key, so the audit trail names the status a human actually
// chose. (MUL-6243)
@@ -1113,6 +1138,34 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
switch effectiveStatus {
case "done", "in_review":
+ // The run's own dispatch decides the run. While it (or its
+ // auto-retry) is still in flight, an early delivery status — often
+ // set by the agent itself mid-run — must not complete the run. Once
+ // it is terminal, its outcome wins over the issue status: a failure
+ // committed before its task:failed event is processed must not be
+ // masked as success. The delivery status only completes runs with no
+ // dispatch task (e.g. a member assignee) or a dispatch that ended
+ // cancelled.
+ chain, err := s.loadDispatchChain(ctx, run)
+ if err != nil {
+ slog.Warn("failed to load autopilot dispatch chain", "run_id", util.UUIDToString(run.ID), "error", err)
+ return
+ }
+ if chain.active() {
+ return
+ }
+ last, ok := chain.last()
+ if ok && (last.Status == "completed" || last.Status == "failed") {
+ s.settleRunFromDispatchTask(ctx, run, last)
+ return
+ }
+ if !ok && issueAwaitsAgentDispatch(issue) {
+ // No dispatch task exists yet but the issue is still assigned to
+ // an agent/squad: the dispatch enqueue is pending (issue:created
+ // fires before the enqueue) or being repaired. Its task outcome
+ // settles the run; do not treat "not yet dispatched" as success.
+ return
+ }
updatedRun, err := s.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{
ID: run.ID,
})
@@ -1122,7 +1175,7 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
}
s.captureAutopilotRunCompleted(autopilot, updatedRun)
s.publishRunDone(wsID, updatedRun, "completed")
- case "cancelled", "blocked":
+ case "cancelled":
reason := "issue " + issue.Status
updatedRun, err := s.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
@@ -1181,9 +1234,18 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
}
}
-// SyncRunFromLinkedIssueTask fails a create_issue autopilot run when its
-// linked issue task fails terminally before the issue itself reaches a
-// terminal status. create_issue tasks are linked through issue_id rather than
+// SyncRunFromLinkedIssueTask settles a create_issue autopilot run from the
+// outcome of its linked issue's agent task.
+//
+// A completed task completes the run: the autopilot created the issue and the
+// agent ran to the end without error, which is what run success means. Any
+// later issue status change (blocked, cancelled, ...) no longer touches the
+// run. (MUL-8200)
+//
+// Only the run's dispatch chain counts (see loadDispatchChain): tasks
+// started by @mentions or comments on the same issue are ignored.
+//
+// A task that fails terminally before the run is settled fails the run. create_issue tasks are linked through issue_id rather than
// autopilot_run_id, so SyncRunFromTask cannot see them directly. Without this
// the run would hang in `issue_created` forever — and because the failure-rate
// auto-pause monitor excludes issue_created/running runs, a consistently
@@ -1196,7 +1258,10 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
// failing the run prematurely. Once retries are exhausted (or the failure was
// never retryable in the first place), the run fails carrying the task's reason.
func (s *AutopilotService) SyncRunFromLinkedIssueTask(ctx context.Context, task db.AgentTaskQueue) {
- if task.AutopilotRunID.Valid || !task.IssueID.Valid || task.Status != "failed" {
+ if task.AutopilotRunID.Valid || !task.IssueID.Valid {
+ return
+ }
+ if task.Status != "completed" && task.Status != "failed" {
return
}
// Only create_issue runs link through issue_id (and their linked issue is
@@ -1207,18 +1272,37 @@ func (s *AutopilotService) SyncRunFromLinkedIssueTask(ctx context.Context, task
if err != nil {
return // no active run linked to this issue
}
- // A still-active task — typically the auto-retry FailTask just enqueued —
- // means the dispatch isn't terminal yet; wait for the final attempt.
- hasActive, err := s.Queries.HasActiveTaskForIssue(ctx, task.IssueID)
+ // Only the autopilot's own dispatch (and its auto-retries) settles the
+ // run. Other tasks on the issue — an @mention, a comment reply — say
+ // nothing about whether the autopilot's execution succeeded.
+ chain, err := s.loadDispatchChain(ctx, run)
if err != nil {
- slog.Warn("failed to check active tasks for autopilot issue failure",
+ slog.Warn("failed to load autopilot dispatch chain",
"issue_id", util.UUIDToString(task.IssueID),
"task_id", util.UUIDToString(task.ID),
"error", err,
)
return
}
- if hasActive {
+ if !chain.contains(task.ID) {
+ return
+ }
+ if task.Status == "failed" && chain.active() {
+ // A still-active attempt — typically the auto-retry FailTask just
+ // enqueued — means the dispatch isn't terminal yet; wait for it.
+ return
+ }
+ s.settleRunFromDispatchTask(ctx, run, task)
+}
+
+// settleRunFromDispatchTask completes or fails an active create_issue run from
+// a terminal attempt of its dispatch chain.
+func (s *AutopilotService) settleRunFromDispatchTask(ctx context.Context, run db.AutopilotRun, task db.AgentTaskQueue) {
+ if task.Status == "completed" {
+ s.completeRunFromLinkedIssueTask(ctx, run, task)
+ return
+ }
+ if task.Status != "failed" {
return
}
autopilot, err := s.Queries.GetAutopilot(ctx, run.AutopilotID)
@@ -1244,6 +1328,150 @@ func (s *AutopilotService) SyncRunFromLinkedIssueTask(ctx context.Context, task
s.publishRunDone(util.UUIDToString(autopilot.WorkspaceID), updatedRun, "failed")
}
+// completeRunFromLinkedIssueTask marks a create_issue run completed once its
+// linked issue's agent task finishes successfully. The run keeps no result
+// payload: create_issue runs surface the linked issue, not task output.
+func (s *AutopilotService) completeRunFromLinkedIssueTask(ctx context.Context, run db.AutopilotRun, task db.AgentTaskQueue) {
+ autopilot, err := s.Queries.GetAutopilot(ctx, run.AutopilotID)
+ if err != nil {
+ return
+ }
+ updatedRun, err := s.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{
+ ID: run.ID,
+ })
+ if err != nil {
+ slog.Warn("failed to complete autopilot run from linked issue task",
+ "run_id", util.UUIDToString(run.ID),
+ "issue_id", util.UUIDToString(task.IssueID),
+ "task_id", util.UUIDToString(task.ID),
+ "error", err,
+ )
+ return
+ }
+ s.captureAutopilotRunCompleted(autopilot, updatedRun)
+ s.publishRunDone(util.UUIDToString(autopilot.WorkspaceID), updatedRun, "completed")
+}
+
+// autopilotDispatchChain is the create_issue run's own dispatch: the task
+// recorded in autopilot_run.task_id at dispatch time plus its auto-retry
+// descendants (retry_of_task_id lineage), oldest first.
+type autopilotDispatchChain struct {
+ tasks []db.AgentTaskQueue
+}
+
+func (c autopilotDispatchChain) contains(id pgtype.UUID) bool {
+ for _, t := range c.tasks {
+ if t.ID == id {
+ return true
+ }
+ }
+ return false
+}
+
+// active reports whether any attempt in the chain is not yet terminal.
+func (c autopilotDispatchChain) active() bool {
+ for _, t := range c.tasks {
+ switch t.Status {
+ case "completed", "failed", "cancelled":
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// last returns the newest attempt in the chain.
+func (c autopilotDispatchChain) last() (db.AgentTaskQueue, bool) {
+ if len(c.tasks) == 0 {
+ return db.AgentTaskQueue{}, false
+ }
+ return c.tasks[len(c.tasks)-1], true
+}
+
+// loadDispatchChain returns the dispatch chain of a create_issue run.
+//
+// The root is the task dispatchCreateIssue recorded on the run. The link is
+// written after the enqueue (the task is already visible and announced by
+// then), and runs dispatched before the link existed or repaired after a
+// webhook-worker crash may have none. In that case the root falls back to the
+// oldest non-retry task owned by the dispatch agent — the issue's creator,
+// which dispatchCreateIssue sets to the executing agent/squad leader — and is
+// persisted on the run so later lookups are stable. Tasks of other agents
+// (e.g. a mention enqueued between issue:created and the dispatch enqueue)
+// are never the root. An empty chain means no dispatch task exists yet.
+func (s *AutopilotService) loadDispatchChain(ctx context.Context, run db.AutopilotRun) (autopilotDispatchChain, error) {
+ if !run.IssueID.Valid {
+ return autopilotDispatchChain{}, nil
+ }
+ tasks, err := s.Queries.ListTasksByIssue(ctx, run.IssueID)
+ if err != nil {
+ return autopilotDispatchChain{}, err
+ }
+ rootID := run.TaskID
+ if !rootID.Valid {
+ issue, err := s.Queries.GetIssue(ctx, run.IssueID)
+ if err != nil {
+ return autopilotDispatchChain{}, err
+ }
+ // ListTasksByIssue is newest first; the last match is the oldest.
+ for _, t := range tasks {
+ if !t.RetryOfTaskID.Valid && issue.CreatorType == "agent" && t.AgentID == issue.CreatorID {
+ rootID = t.ID
+ }
+ }
+ if !rootID.Valid {
+ return autopilotDispatchChain{}, nil
+ }
+ if _, err := s.Queries.SetAutopilotRunDispatchTask(ctx, db.SetAutopilotRunDispatchTaskParams{ID: run.ID, TaskID: rootID}); err != nil {
+ slog.Warn("failed to backfill autopilot dispatch task",
+ "run_id", util.UUIDToString(run.ID),
+ "task_id", util.UUIDToString(rootID),
+ "error", err,
+ )
+ }
+ }
+ // Walk oldest first so each retry's parent is seen before the retry.
+ inChain := map[pgtype.UUID]bool{}
+ var chain autopilotDispatchChain
+ for i := len(tasks) - 1; i >= 0; i-- {
+ t := tasks[i]
+ if t.ID != rootID && !(t.RetryOfTaskID.Valid && inChain[t.RetryOfTaskID]) {
+ continue
+ }
+ inChain[t.ID] = true
+ chain.tasks = append(chain.tasks, t)
+ }
+ return chain, nil
+}
+
+// issueAwaitsAgentDispatch reports whether the linked issue is still assigned
+// to an agent or squad, i.e. an autopilot dispatch task is expected for it.
+func issueAwaitsAgentDispatch(issue db.Issue) bool {
+ return issue.AssigneeType.Valid && (issue.AssigneeType.String == "agent" || issue.AssigneeType.String == "squad")
+}
+
+// linkDispatchTask records the task a create_issue dispatch enqueued on its
+// run. It is best effort: until it lands, loadDispatchChain resolves the same
+// task through its dispatch-agent fallback, so task events that arrive before
+// the link still settle the run.
+func (s *AutopilotService) linkDispatchTask(ctx context.Context, run *db.AutopilotRun, task db.AgentTaskQueue) {
+ if !task.ID.Valid {
+ return
+ }
+ n, err := s.Queries.SetAutopilotRunDispatchTask(ctx, db.SetAutopilotRunDispatchTaskParams{ID: run.ID, TaskID: task.ID})
+ if err != nil {
+ slog.Warn("failed to link autopilot dispatch task",
+ "run_id", util.UUIDToString(run.ID),
+ "task_id", util.UUIDToString(task.ID),
+ "error", err,
+ )
+ return
+ }
+ if n > 0 {
+ run.TaskID = task.ID
+ }
+}
+
func taskFailureReasonForAutopilotRun(task db.AgentTaskQueue) string {
if task.Error.Valid && strings.TrimSpace(task.Error.String) != "" {
return task.Error.String
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 3e192dda5f..72c3e5f94f 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -1979,6 +1979,29 @@ func (q *Queries) SelectAutopilotsExceedingFailureThreshold(ctx context.Context,
return items, nil
}
+const setAutopilotRunDispatchTask = `-- name: SetAutopilotRunDispatchTask :execrows
+UPDATE autopilot_run
+SET task_id = $2
+WHERE id = $1 AND status = 'issue_created' AND task_id IS NULL
+`
+
+type SetAutopilotRunDispatchTaskParams struct {
+ ID pgtype.UUID `json:"id"`
+ TaskID pgtype.UUID `json:"task_id"`
+}
+
+// Records the agent task a create_issue run actually enqueued, so lifecycle
+// sync can tell the run's own dispatch apart from mention/comment tasks on
+// the same issue. Status stays issue_created; only an unlinked active run is
+// written. (MUL-8200)
+func (q *Queries) SetAutopilotRunDispatchTask(ctx context.Context, arg SetAutopilotRunDispatchTaskParams) (int64, error) {
+ result, err := q.db.Exec(ctx, setAutopilotRunDispatchTask, arg.ID, arg.TaskID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const setAutopilotTriggerPublisher = `-- name: SetAutopilotTriggerPublisher :exec
UPDATE autopilot_trigger
SET published_by_type = $2, published_by_id = $3, updated_at = now()
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 4a50ddd513..f1c0bc2b3d 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -426,6 +426,15 @@ SET status = 'issue_created', issue_id = $2
WHERE id = $1
RETURNING *;
+-- name: SetAutopilotRunDispatchTask :execrows
+-- Records the agent task a create_issue run actually enqueued, so lifecycle
+-- sync can tell the run's own dispatch apart from mention/comment tasks on
+-- the same issue. Status stays issue_created; only an unlinked active run is
+-- written. (MUL-8200)
+UPDATE autopilot_run
+SET task_id = $2
+WHERE id = $1 AND status = 'issue_created' AND task_id IS NULL;
+
-- name: UpdateAutopilotRunRunning :one
UPDATE autopilot_run
SET status = 'running', task_id = $2