Skip to content

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

Go

MUL-7610: fix(autopilot): avoid loading task history during webhook recovery (#8710)

YYClawdbfc014bdd0f
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 7a72fe62f4..4d20084398 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -321,11 +321,11 @@ func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(
// moved downstream; otherwise enqueue exactly the same assignee path used by
// the original dispatch.
func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, autopilot db.Autopilot, run db.AutopilotRun) error {
- tasks, err := s.Queries.ListTasksByIssue(ctx, run.IssueID)
+ hasTasks, err := s.Queries.HasTaskForIssue(ctx, run.IssueID)
if err != nil {
return fmt.Errorf("dispatch for webhook delivery: inspect issue tasks: %w", err)
}
- if len(tasks) > 0 {
+ if hasTasks {
return nil
}
issue, err := s.Queries.GetIssue(ctx, run.IssueID)
diff --git a/server/internal/service/autopilot_webhook_exists_test.go b/server/internal/service/autopilot_webhook_exists_test.go
new file mode 100644
index 0000000000..538329ef60
--- /dev/null
+++ b/server/internal/service/autopilot_webhook_exists_test.go
@@ -0,0 +1,105 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type webhookTaskReadTrace struct {
+ reads int
+ maxRows int64
+}
+type webhookTaskReadTraceKey struct{}
+
+func (tr *webhookTaskReadTrace) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
+ return context.WithValue(ctx, webhookTaskReadTraceKey{}, strings.Contains(data.SQL, "FROM agent_task_queue"))
+}
+func (tr *webhookTaskReadTrace) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
+ if tracked, _ := ctx.Value(webhookTaskReadTraceKey{}).(bool); tracked {
+ tr.reads++
+ tr.maxRows = max(tr.maxRows, data.CommandTag.RowsAffected())
+ }
+}
+
+func TestWebhookRecoveryTaskExistenceReadIsBounded(t *testing.T) {
+ ctx := context.Background()
+ tr := &webhookTaskReadTrace{}
+ config := sharedTestPool(t).Config()
+ config.ConnConfig.Tracer = tr
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ fx := testutil.New(pool, "", "")
+ suffix := time.Now().UnixNano()
+ fx.UserID = fx.User(t, "webhook reader", fmt.Sprintf("webhook-reader-%[email protected]", suffix))
+ fx.WorkspaceID = fx.Workspace(t, "webhook reader", fmt.Sprintf("webhook-reader-%d", suffix))
+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")
+ runtimeID := fx.Runtime(t, "webhook reader")
+ agentID := fx.Agent(t, "webhook reader", runtimeID)
+ q := db.New(pool)
+ svc := &AutopilotService{Queries: q}
+ for _, status := range []string{"completed", "failed", "cancelled", "queued", "deferred"} {
+ t.Run(status, func(t *testing.T) {
+ issueID := fx.Issue(t, "already handed off")
+ // A nil TaskSvc deliberately makes an accidental duplicate enqueue fail.
+ count := 64
+ if status == "queued" || status == "deferred" {
+ count = 1
+ }
+ for i := 0; i < count; i++ {
+ taskStatus := status
+ fx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": taskStatus, "context": testutil.Raw(`jsonb_build_object('large',repeat('x',65536))`), "result": testutil.Raw(`jsonb_build_object('large',repeat('y',65536))`)})
+ }
+ tr.reads = 0
+ tr.maxRows = 0
+ if err := svc.ensureWebhookCreateIssueTask(ctx, db.Autopilot{}, db.AutopilotRun{IssueID: util.MustParseUUID(issueID)}); err != nil {
+ t.Fatal(err)
+ }
+ if tr.reads != 1 || tr.maxRows > 1 {
+ t.Fatalf("task inspection transferred %d rows across %d reads", tr.maxRows, tr.reads)
+ }
+ })
+ }
+ // No task on this issue must still take the lifecycle/repair path, even
+ // when other issues have tasks; a deleted issue must surface its load error.
+ missing := util.MustParseUUID("ffffffff-ffff-ffff-ffff-fffffffffff1")
+ if err := svc.ensureWebhookCreateIssueTask(ctx, db.Autopilot{}, db.AutopilotRun{IssueID: missing}); err == nil || !strings.Contains(err.Error(), "load linked issue") {
+ t.Fatalf("missing issue: %v", err)
+ }
+ parked := fx.Issue(t, "parked issue", testutil.Cols{"status": "backlog"})
+ if err := svc.ensureWebhookCreateIssueTask(ctx, db.Autopilot{}, db.AutopilotRun{IssueID: util.MustParseUUID(parked)}); err != nil {
+ t.Fatal(err)
+ }
+ runnable := fx.Issue(t, "repair missing task", testutil.Cols{"status": "todo", "assignee_type": "agent", "assignee_id": agentID})
+ svc.TaskSvc = NewTaskService(q, pool, nil, events.New())
+ fx.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id=$1", runnable)
+ for range 2 {
+ if err := svc.ensureWebhookCreateIssueTask(ctx, db.Autopilot{}, db.AutopilotRun{IssueID: util.MustParseUUID(runnable)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var taskCount int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM agent_task_queue WHERE issue_id=$1", runnable).Scan(&taskCount); err != nil {
+ t.Fatal(err)
+ }
+ if taskCount != 1 {
+ t.Fatalf("repair/replay produced %d tasks, want one", taskCount)
+ }
+ cancelled, cancel := context.WithCancel(ctx)
+ cancel()
+ if err := svc.ensureWebhookCreateIssueTask(cancelled, db.Autopilot{}, db.AutopilotRun{IssueID: util.MustParseUUID(parked)}); err == nil || !strings.Contains(err.Error(), "inspect issue tasks") {
+ t.Fatalf("query failure: %v", err)
+ }
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 0fb50fe8ac..09f5bc4122 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5069,6 +5069,19 @@ func (q *Queries) HasTaskCoveringDelegatedFailureComment(ctx context.Context, ar
return covered, err
}
+const hasTaskForIssue = `-- name: HasTaskForIssue :one
+SELECT EXISTS (SELECT 1 FROM agent_task_queue WHERE issue_id = $1)
+`
+
+// Returns true if the issue has any task in any status. Webhook recovery
+// treats even a terminal task as proof that ownership moved downstream.
+func (q *Queries) HasTaskForIssue(ctx context.Context, issueID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, hasTaskForIssue, issueID)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
const linkTaskToIssue = `-- name: LinkTaskToIssue :exec
UPDATE agent_task_queue
SET issue_id = $2
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 74fc1b03a3..a86d28439e 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -1784,6 +1784,11 @@ SELECT * FROM agent
WHERE id = $1
FOR UPDATE;
+-- name: HasTaskForIssue :one
+-- Returns true if the issue has any task in any status. Webhook recovery
+-- treats even a terminal task as proof that ownership moved downstream.
+SELECT EXISTS (SELECT 1 FROM agent_task_queue WHERE issue_id = $1);
+
-- name: HasActiveTaskForIssue :one
-- Returns true if there is any queued, dispatched, waiting_local_directory,
-- or running task for the issue.