Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(autopilots): deduplicate webhook issues by delivery (#10559)
wzc1753fda2dbf5b921
diff --git a/server/internal/handler/webhook_delivery_test.go b/server/internal/handler/webhook_delivery_test.goindex 37173c1194..b528daa313 100644--- a/server/internal/handler/webhook_delivery_test.go+++ b/server/internal/handler/webhook_delivery_test.go@@ -14,7 +14,9 @@ import ("time""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol")// ── Setup helpers ───────────────────────────────────────────────────────────@@ -206,6 +208,38 @@ func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {}}+func TestWebhookDeliveryWorker_DistinctDeliveriesCreateSameTitleIssues(t *testing.T) {+ agentID := createWebhookTestAgent(t, "MR review agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "create_issue")+ trig := createWebhookTriggerViaHandler(t, apID)+ seen := make(map[pgtype.UUID]bool)+ for _, event := range []struct {+ iid int+ action string+ key string+ }{+ {658, "update", "mr-658"},+ {704, "open", "mr-704"},+ {704, "open", ""},+ {704, "open", ""},+ } {+ body := map[string]any{"object_kind": "merge_request", "object_attributes": map[string]any{"iid": event.iid, "action": event.action}}+ headers := map[string]string{"X-Gitlab-Event": "Merge Request Hook"}+ if event.key != "" {+ headers["Idempotency-Key"] = event.key+ }+ w := postWebhook(t, *trig.WebhookToken, body, headers)+ delivery := processQueuedWebhookDelivery(t, requireAcceptedWebhookResponse(t, w))+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), delivery.AutopilotRunID)+ if err != nil || !run.IssueID.Valid || seen[run.IssueID] {+ t.Fatalf("MR !%d %s (key %q): issue=%v status=%s reason=%s err=%v", event.iid, event.action, event.key, run.IssueID, run.Status, run.ReasonCode.String, err)+ }+ seen[run.IssueID] = true+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, run.IssueID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, run.IssueID)+ }+}+func TestWebhookHandler_DedupeViaGitHubDelivery(t *testing.T) {agentID := createWebhookTestAgent(t, "DeliveryGH Agent")apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")@@ -869,6 +903,131 @@ func TestWebhookDeliveryWorker_RepairsCreateIssueTaskCrashWindow(t *testing.T) {}}+func TestWebhookDeliveryWorker_RedeliveryRepairsCommittedIssue(t *testing.T) {+ for _, scenario := range []string{"initial enqueue", "reclaim repair"} {+ t.Run(scenario, func(t *testing.T) {+ ctx := context.Background()+ agent := createWebhookTestAgent(t, "Redelivery Agent")+ ap := createWebhookTestAutopilot(t, agent, "active", "create_issue")+ trigger := createWebhookTriggerViaHandler(t, ap)+ post := func() string {+ return requireAcceptedWebhookResponse(t, postWebhook(t, *trigger.WebhookToken,+ map[string]any{"event": "redelivery"}, map[string]string{"Idempotency-Key": "redelivery"}))+ }+ exec := func(query string, args ...any) {+ t.Helper()+ if _, err := testPool.Exec(ctx, query, args...); err != nil {+ t.Fatal(err)+ }+ }+ t.Cleanup(func() {+ exec(`DELETE FROM agent_task_queue WHERE issue_id IN (SELECT id FROM issue WHERE origin_id = $1)`, ap)+ exec(`DELETE FROM issue WHERE origin_id = $1`, ap)+ })+ delivery := post()+ if scenario == "reclaim repair" {+ first := processQueuedWebhookDelivery(t, delivery)+ exec(`DELETE FROM agent_task_queue WHERE issue_id = (SELECT issue_id FROM autopilot_run WHERE id = $1)`, first.AutopilotRunID)+ exec(`UPDATE autopilot_run SET task_id = NULL WHERE id = $1`, first.AutopilotRunID)+ exec(`UPDATE webhook_delivery SET status = 'queued' WHERE id = $1`, delivery)+ }++ // Fail only this agent's inserts, after the issue transaction commits.+ constraint := fmt.Sprintf("test_enqueue_%d", time.Now().UnixNano())+ exec(fmt.Sprintf("ALTER TABLE agent_task_queue ADD CONSTRAINT %s CHECK (agent_id <> '%s') NOT VALID", constraint, agent))+ drop := "ALTER TABLE agent_task_queue DROP CONSTRAINT IF EXISTS " + constraint+ t.Cleanup(func() { exec(drop) })+ failed := processQueuedWebhookDelivery(t, delivery)+ if failed.Status != "failed" {+ t.Fatalf("expected failed delivery, got %s", failed.Status)+ }+ before, err := testHandler.Queries.GetAutopilotRun(ctx, failed.AutopilotRunID)+ if err != nil || !before.IssueID.Valid {+ t.Fatalf("expected a committed issue, got run=%v err=%v", before, err)+ }+ exec(drop)+ retry := processQueuedWebhookDelivery(t, post())+ if retry.Status != "dispatched" || retry.AutopilotRunID != before.ID {+ t.Fatalf("redelivery should dispatch original run %v, got %v", before.ID, retry)+ }+ original, err := testHandler.Queries.GetAutopilotRunByWebhookDelivery(ctx, failed.ID)+ if err != nil || original.ID != before.ID || original.IssueID != before.IssueID || !original.TaskID.Valid {+ t.Fatalf("original delivery lost its repaired run: run=%v err=%v", original, err)+ }+ var issues, tasks int+ err = testPool.QueryRow(ctx, `SELECT+ (SELECT count(*) FROM issue WHERE origin_id = $1),+ (SELECT count(*) FROM agent_task_queue WHERE issue_id = $2)`, ap, before.IssueID).Scan(&issues, &tasks)+ if err != nil || issues != 1 || tasks != 1 {+ t.Fatalf("expected one issue with one task, got issues=%d tasks=%d err=%v", issues, tasks, err)+ }+ })+ }+}++func TestWebhookDeliveryWorker_OverlappingWorkersReuseIssue(t *testing.T) {+ ctx := context.Background()+ agentID := createWebhookTestAgent(t, "Worker overlap agent")+ apID := createWebhookTestAutopilot(t, agentID, "active", "create_issue")+ trig := createWebhookTriggerViaHandler(t, apID)+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "overlap"}, nil)+ deliveryID := parseUUID(requireAcceptedWebhookResponse(t, w))+ ap, err := testHandler.Queries.GetAutopilot(ctx, parseUUID(apID))+ if err != nil {+ t.Fatal(err)+ }++ admitted, err := testHandler.Queries.GetAutopilotRunByWebhookDelivery(ctx, deliveryID)+ if err != nil {+ t.Fatal(err)+ }+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ if _, err := tx.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, ap.WorkspaceID); err != nil {+ t.Fatal(err)+ }++ // The first worker holds the run lock while it waits for an issue number.+ // The second must wait for the first worker before reading the issue link.+ svc := *testHandler.AutopilotService+ svc.Bus = events.New()+ started := make(chan struct{}, 2)+ svc.Bus.Subscribe(protocol.EventAutopilotRunStart, func(events.Event) { started <- struct{}{} })+ done := make(chan error, 2)+ dispatch := func() {+ _, err := svc.DispatchAutopilotForWebhookDelivery(ctx, ap, parseUUID(trig.ID), nil, deliveryID)+ done <- err+ }+ go dispatch()+ waitForBlockedQuery(t, done, "IncrementIssueCounter")+ go dispatch()+ waitForBlockedQuery(t, done, "LockIssueDuplicateKey")+ if err := tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ for range 2 {+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ }+ run, err := testHandler.Queries.GetAutopilotRun(ctx, admitted.ID)+ if err != nil || !run.IssueID.Valid || run.Status != "issue_created" {+ t.Fatalf("reclaimed delivery: run=%+v err=%v", run, err)+ }+ if len(started) != 1 {+ t.Fatalf("got %d run start events, want 1", len(started))+ }+ var count int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE origin_type = 'autopilot' AND origin_id = $1`, ap.ID).Scan(&count); err != nil || count != 1 {+ t.Fatalf("reclaimed delivery: got %d issues, want 1, err=%v", count, err)+ }+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, run.IssueID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, run.IssueID)+}+func TestWebhookHandler_InvalidSignatureCountsAgainstRateLimit(t *testing.T) {// Only requests classified as bad credentials consume the shared-IP debt// budget; valid traffic behind the same NAT does not.diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 9ea5eeabaf..fc74643baa 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -227,6 +227,25 @@ func (s *AutopilotService) AdmitAutopilotWebhookDelivery(return run, nil}+ if autopilot.ExecutionMode == "create_issue" {+ run, err := s.Queries.ResumeFailedWebhookIssueDelivery(ctx, deliveryID)+ if err == nil {+ return &run, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return nil, fmt.Errorf("resume failed webhook delivery: %w", err)+ }+ // A concurrent admission may have moved the original run onto this+ // delivery while we were looking it up. Reuse it before reserving quota.+ existing, err := s.Queries.GetAutopilotRunByWebhookDelivery(ctx, deliveryID)+ if err == nil {+ return &existing, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return nil, fmt.Errorf("reload resumed webhook run: %w", err)+ }+ }+initialStatus := "issue_created"if autopilot.ExecutionMode == "run_only" {initialStatus = "running"@@ -290,10 +309,8 @@ func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(return nil, err}if isAutopilotRunComplete(*run) {- if autopilot.ExecutionMode == "create_issue" && run.IssueID.Valid {- if repairErr := s.ensureWebhookCreateIssueTask(ctx, autopilot, *run); repairErr != nil {- return run, repairErr- }+ if autopilot.ExecutionMode == "create_issue" {+ return run, s.ensureWebhookCreateIssueTask(ctx, autopilot, *run)}return run, nil}@@ -322,6 +339,9 @@ 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 {+ if !run.IssueID.Valid {+ return nil+ }hasTasks, err := s.Queries.HasTaskForIssue(ctx, run.IssueID)if err != nil {return fmt.Errorf("dispatch for webhook delivery: inspect issue tasks: %w", err)@@ -362,19 +382,22 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, autif !runnable {return nil}+ var task db.AgentTaskQueueif autopilot.AssigneeType == "squad" {- leader, _, err := s.resolveAutopilotLeader(ctx, autopilot)- if err != nil {- return fmt.Errorf("dispatch for webhook delivery: resolve squad leader: %w", err)+ leader, _, resolveErr := s.resolveAutopilotLeader(ctx, autopilot)+ if resolveErr != nil {+ return fmt.Errorf("dispatch for webhook delivery: resolve squad leader: %w", resolveErr)}- 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)+ if !s.autopilotAdmitInvoke(ctx, autopilot, leader, pgtype.UUID{}, run.TriggerID) {+ return fmt.Errorf("not allowed to invoke private squad leader")}- s.linkDispatchTask(ctx, &run, task)+ task, err = s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}, OriginDerived)+ } else {+ task, err = s.TaskSvc.EnqueueTaskForIssue(ctx, issue)+ }+ if errors.Is(err, ErrDuplicatePendingTask) {return nil}- task, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue)if err != nil {return fmt.Errorf("dispatch for webhook delivery: repair issue task: %w", err)}@@ -636,6 +659,12 @@ func (s *AutopilotService) dispatchAutopilotRun(if err != nil && healIssueCounterAfterCollision(ctx, s.Queries, autopilot.WorkspaceID, err) {err = s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone, actorUserID)}+ if errors.Is(err, errWebhookRunAlreadyDispatched) {+ return run, "", s.ensureWebhookCreateIssueTask(ctx, autopilot, *run)+ }+ if run.WebhookDeliveryID.Valid && errors.Is(err, ErrDuplicatePendingTask) {+ err = nil // The recovery worker already enqueued this issue's task.+ }if err != nil {if skipped, code := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {return skipped, code, nil@@ -767,7 +796,21 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi}projectID := currentAutopilot.ProjectID- if duplicate, found, err := issueguard.LockAndFindRecentAutopilotDuplicate(+ if run.WebhookDeliveryID.Valid {+ // A reclaimed delivery can overlap its previous worker. Serialize on+ // the run so both workers observe the same committed issue link.+ if err := qtx.LockIssueDuplicateKey(ctx, util.UUIDToString(run.ID)); err != nil {+ return fmt.Errorf("lock webhook run: %w", err)+ }+ current, err := qtx.GetAutopilotRun(ctx, run.ID)+ if err != nil {+ return fmt.Errorf("reload webhook run: %w", err)+ }+ if isAutopilotRunComplete(current) {+ *run = current+ return errWebhookRunAlreadyDispatched+ }+ } else if duplicate, found, err := issueguard.LockAndFindRecentAutopilotDuplicate(ctx, qtx, ap.WorkspaceID, ap.ID, projectID, title, autopilotRecentDuplicateWindow,); err != nil {return fmt.Errorf("recent duplicate guard: %w", err)@@ -986,6 +1029,8 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate(}}+var errWebhookRunAlreadyDispatched = errors.New("webhook run already dispatched")+// errDispatchSkipped wraps a readiness failure encountered after the// admission gate has already passed. dispatchRunOnly returns this when a// resolved leader has gone offline / been archived between admission anddiff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 2271b687b9..08c20f1855 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -909,6 +909,7 @@ func (q *Queries) GetAutopilotRunByTriggerAndPlanned(ctx context.Context, arg Geconst getAutopilotRunByWebhookDelivery = `-- name: GetAutopilotRunByWebhookDelivery :oneSELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at, webhook_delivery_id, quota_reservation_id, reason_code FROM autopilot_runWHERE webhook_delivery_id = $1+ OR id = (SELECT autopilot_run_id FROM webhook_delivery WHERE id = $1)LIMIT 1`@@ -1909,6 +1910,60 @@ func (q *Queries) RecoverPartialAutopilotRun(ctx context.Context, id pgtype.UUIDreturn column_1, err}+const resumeFailedWebhookIssueDelivery = `-- name: ResumeFailedWebhookIssueDelivery :one+WITH candidate AS (+ SELECT retry.id AS retry_id, prior.id AS prior_id,+ linked.status = 'failed' AND linked.task_id IS NULL AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue task WHERE task.issue_id = linked.issue_id+ ) AS reopen+ FROM webhook_delivery retry+ JOIN webhook_delivery prior ON prior.trigger_id = retry.trigger_id+ AND prior.workspace_id = retry.workspace_id AND prior.dedupe_key = retry.dedupe_key+ JOIN autopilot_run linked ON linked.webhook_delivery_id = prior.id+ WHERE retry.id = $1 AND retry.status = 'queued' AND prior.status = 'failed'+ AND linked.issue_id IS NOT NULL+ ORDER BY prior.created_at DESC, prior.id DESC+ LIMIT 1+)+UPDATE autopilot_run r+SET webhook_delivery_id = candidate.retry_id,+ status = CASE WHEN candidate.reopen THEN 'issue_created' ELSE r.status END,+ completed_at = CASE WHEN candidate.reopen THEN NULL ELSE r.completed_at END,+ failure_reason = CASE WHEN candidate.reopen THEN NULL ELSE r.failure_reason END,+ reason_code = CASE WHEN candidate.reopen THEN NULL ELSE r.reason_code END+FROM candidate+WHERE r.webhook_delivery_id = candidate.prior_id+RETURNING r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code+`++// Keep the original run, issue, and consumed quota. The old delivery retains+// its audit link to the run when the new delivery takes over dispatch.+func (q *Queries) ResumeFailedWebhookIssueDelivery(ctx context.Context, id pgtype.UUID) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, resumeFailedWebhookIssueDelivery, id)+ var i AutopilotRun+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.TriggerID,+ &i.Source,+ &i.Status,+ &i.IssueID,+ &i.TaskID,+ &i.TriggeredAt,+ &i.CompletedAt,+ &i.FailureReason,+ &i.TriggerPayload,+ &i.Result,+ &i.CreatedAt,+ &i.SquadID,+ &i.PlannedAt,+ &i.WebhookDeliveryID,+ &i.QuotaReservationID,+ &i.ReasonCode,+ )+ return i, err+}+const rotateAutopilotTriggerWebhookToken = `-- name: RotateAutopilotTriggerWebhookToken :oneUPDATE autopilot_triggerSET webhook_token = $2,diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 85e1f83240..db9df41649 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -356,8 +356,36 @@ LIMIT 1;-- name: GetAutopilotRunByWebhookDelivery :oneSELECT * FROM autopilot_runWHERE webhook_delivery_id = $1+ OR id = (SELECT autopilot_run_id FROM webhook_delivery WHERE id = $1)LIMIT 1;+-- name: ResumeFailedWebhookIssueDelivery :one+-- Keep the original run, issue, and consumed quota. The old delivery retains+-- its audit link to the run when the new delivery takes over dispatch.+WITH candidate AS (+ SELECT retry.id AS retry_id, prior.id AS prior_id,+ linked.status = 'failed' AND linked.task_id IS NULL AND NOT EXISTS (+ SELECT 1 FROM agent_task_queue task WHERE task.issue_id = linked.issue_id+ ) AS reopen+ FROM webhook_delivery retry+ JOIN webhook_delivery prior ON prior.trigger_id = retry.trigger_id+ AND prior.workspace_id = retry.workspace_id AND prior.dedupe_key = retry.dedupe_key+ JOIN autopilot_run linked ON linked.webhook_delivery_id = prior.id+ WHERE retry.id = $1 AND retry.status = 'queued' AND prior.status = 'failed'+ AND linked.issue_id IS NOT NULL+ ORDER BY prior.created_at DESC, prior.id DESC+ LIMIT 1+)+UPDATE autopilot_run r+SET webhook_delivery_id = candidate.retry_id,+ status = CASE WHEN candidate.reopen THEN 'issue_created' ELSE r.status END,+ completed_at = CASE WHEN candidate.reopen THEN NULL ELSE r.completed_at END,+ failure_reason = CASE WHEN candidate.reopen THEN NULL ELSE r.failure_reason END,+ reason_code = CASE WHEN candidate.reopen THEN NULL ELSE r.reason_code END+FROM candidate+WHERE r.webhook_delivery_id = candidate.prior_id+RETURNING r.*;+-- name: GetAutopilotRunByQuotaReservation :oneSELECT * FROM autopilot_runWHERE quota_reservation_id = $1