Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
WS-1465 fix autopilot duplicate issue dispatch (#4936)
tangyuanjc3f17c2717b67
diff --git a/server/cmd/server/autopilot_dispatch_for_plan_test.go b/server/cmd/server/autopilot_dispatch_for_plan_test.goindex 040b4f7c35..131088495c 100644--- a/server/cmd/server/autopilot_dispatch_for_plan_test.go+++ b/server/cmd/server/autopilot_dispatch_for_plan_test.go@@ -149,6 +149,74 @@ func TestDispatchAutopilotForPlanIsIdempotent(t *testing.T) {}}+func TestDispatchAutopilotSuppressesRecentDuplicateIssue(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ bus := events.New()+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)+ autopilotSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)++ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ title := "Autopilot recent duplicate issue " + time.Now().UTC().Format("20060102150405.000000000")+ ap, err := queries.CreateAutopilot(ctx, db.CreateAutopilotParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ Title: "Recent duplicate issue guard",+ Description: pgtype.Text{String: "Recent duplicate issue guard test", Valid: true},+ AssigneeType: "agent",+ AssigneeID: parseUUID(agentID),+ Status: "active",+ ExecutionMode: "create_issue",+ IssueTitleTemplate: pgtype.Text{String: title, Valid: true},+ CreatedByType: "member",+ CreatedByID: parseUUID(testUserID),+ })+ if err != nil {+ t.Fatalf("CreateAutopilot: %v", err)+ }+ t.Cleanup(func() {+ bg := context.Background()+ _, _ = testPool.Exec(bg, `DELETE FROM autopilot WHERE id = $1`, ap.ID)+ _, _ = testPool.Exec(bg, `DELETE FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title)+ })++ first, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ if err != nil {+ t.Fatalf("first DispatchAutopilot: %v", err)+ }+ if first == nil || first.Status != "issue_created" || !first.IssueID.Valid {+ t.Fatalf("first dispatch = %+v, want issue_created with issue_id", first)+ }++ second, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ if err != nil {+ t.Fatalf("second DispatchAutopilot: %v", err)+ }+ if second == nil || second.Status != "skipped" {+ t.Fatalf("second dispatch = %+v, want skipped duplicate run", second)+ }+ if second.IssueID.Valid {+ t.Fatalf("duplicate run linked issue_id=%s, want no new issue", util.UUIDToString(second.IssueID))+ }++ var count int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`,+ testWorkspaceID, title,+ ).Scan(&count); err != nil {+ t.Fatalf("count issues: %v", err)+ }+ if count != 1 {+ t.Fatalf("recent duplicate autopilot dispatch should leave 1 matching issue, got %d", count)+ }+}+// TestDispatchAutopilotForPlanRejectsZeroArgs locks in the// fail-loud contract: a caller that forgets to set trigger_id or// planned_at would silently disable the idempotency guard, and thediff --git a/server/cmd/server/autopilot_schedule_job_test.go b/server/cmd/server/autopilot_schedule_job_test.goindex 6a3a04dacf..2f9d012e13 100644--- a/server/cmd/server/autopilot_schedule_job_test.go+++ b/server/cmd/server/autopilot_schedule_job_test.go@@ -501,11 +501,11 @@ func TestAutopilotScheduleJobPausedAutopilotSkipsAtHandler(t *testing.T) {// and returns a SUCCESS no-op WITHOUT calling DispatchAutopilotForPlan.planTime := time.Now().UTC().Truncate(time.Minute)result, err := job.Handler(ctx, scheduler.HandlerInput{- Job: &job,- Scope: scheduler.Scope{Kind: scheduler.ScopeKindAutopilotTrigger, ID: util.UUIDToString(trigger.ID)},- PlanTime: planTime,- Attempt: 1,- RunnerID: "handler-guard-test",+ Job: &job,+ Scope: scheduler.Scope{Kind: scheduler.ScopeKindAutopilotTrigger, ID: util.UUIDToString(trigger.ID)},+ PlanTime: planTime,+ Attempt: 1,+ RunnerID: "handler-guard-test",Heartbeat: func(ctx context.Context) error { return nil },})if err != nil {@@ -736,8 +736,8 @@ func TestAutopilotScheduleJobColdStartBrandNewTriggerStillFires(t *testing.T) {ctx := context.Background()trigger, queries, autopilotSvc := seedColdStartTrigger(t, "0 12 * * *")- createdAt := time.Date(2026, 6, 23, 11, 50, 0, 0, time.UTC) // 10 min before the fire- pinnedNow := time.Date(2026, 6, 23, 12, 5, 0, 0, time.UTC) // 5 min after the fire+ createdAt := time.Date(2026, 6, 23, 11, 50, 0, 0, time.UTC) // 10 min before the fire+ pinnedNow := time.Date(2026, 6, 23, 12, 5, 0, 0, time.UTC) // 5 min after the fireexpectedFire := time.Date(2026, 6, 23, 12, 0, 0, 0, time.UTC) // the daily noon UTC fireif _, err := testPool.Exec(ctx, `@@ -771,3 +771,42 @@ func TestAutopilotScheduleJobColdStartBrandNewTriggerStillFires(t *testing.T) {plans[0].Format(time.RFC3339), expectedFire.Format(time.RFC3339))}}++// TestAutopilotScheduleJobColdStartSkipsStaleMissedOccurrence covers the+// activation-after-window case from WS-1465: a trigger with no scheduler+// history must not immediately fire an hours-old occurrence just because it+// became schedulable after the configured time had already passed.+func TestAutopilotScheduleJobColdStartSkipsStaleMissedOccurrence(t *testing.T) {+ ctx := context.Background()+ trigger, queries, autopilotSvc := seedColdStartTrigger(t, "7 9 * * *")++ createdAt := time.Date(2026, 7, 2, 15, 54, 0, 0, time.UTC)+ pinnedNow := time.Date(2026, 7, 4, 13, 4, 27, 0, time.UTC)++ if _, err := testPool.Exec(ctx, `+ UPDATE autopilot_trigger+ SET created_at = $2,+ last_fired_at = NULL+ WHERE id = $1+ `, trigger.ID, createdAt); err != nil {+ t.Fatalf("seed deterministic timestamps: %v", err)+ }++ job := scheduler.AutopilotScheduleDispatchJob(testPool, queries, autopilotSvc)+ if _, err := job.Scopes(ctx, pinnedNow); err != nil {+ t.Fatalf("populate scope cache: %v", err)+ }++ scope := scheduler.Scope{+ Kind: scheduler.ScopeKindAutopilotTrigger,+ ID: util.UUIDToString(trigger.ID),+ }++ plans, err := job.PlansForScope(ctx, scope, pinnedNow, scheduler.LatestPlanInfo{Found: false})+ if err != nil {+ t.Fatalf("planner hook: %v", err)+ }+ if len(plans) != 0 {+ t.Fatalf("stale cold-start occurrence must be skipped; got plans %v", plans)+ }+}diff --git a/server/internal/issueguard/duplicate.go b/server/internal/issueguard/duplicate.goindex 5a7bc315af..23085c129e 100644--- a/server/internal/issueguard/duplicate.go+++ b/server/internal/issueguard/duplicate.go@@ -5,6 +5,7 @@ import ("errors""fmt""strings"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"@@ -75,6 +76,39 @@ func LockAndFindActiveDuplicate(return duplicate, true, nil}+func LockAndFindRecentAutopilotDuplicate(+ ctx context.Context,+ q *db.Queries,+ workspaceID pgtype.UUID,+ autopilotID pgtype.UUID,+ projectID pgtype.UUID,+ title string,+ window time.Duration,+) (db.Issue, bool, error) {+ normalizedTitle := NormalizeTitle(title)+ if normalizedTitle == "" || !autopilotID.Valid || window <= 0 {+ return db.Issue{}, false, nil+ }+ if err := q.LockIssueDuplicateKey(ctx, recentAutopilotLockKey(workspaceID, autopilotID, projectID, normalizedTitle)); err != nil {+ return db.Issue{}, false, err+ }++ duplicate, err := q.FindRecentAutopilotDuplicateIssue(ctx, db.FindRecentAutopilotDuplicateIssueParams{+ WorkspaceID: workspaceID,+ OriginID: autopilotID,+ ProjectID: projectID,+ NormalizedTitle: normalizedTitle,+ CreatedAfter: pgtype.Timestamptz{Time: time.Now().UTC().Add(-window), Valid: true},+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return db.Issue{}, false, nil+ }+ return db.Issue{}, false, err+ }+ return duplicate, true, nil+}+func lockKey(workspaceID, projectID, parentIssueID pgtype.UUID, normalizedTitle string) string {return strings.Join([]string{"issue-active-duplicate",@@ -84,3 +118,13 @@ func lockKey(workspaceID, projectID, parentIssueID pgtype.UUID, normalizedTitlenormalizedTitle,}, "|")}++func recentAutopilotLockKey(workspaceID, autopilotID, projectID pgtype.UUID, normalizedTitle string) string {+ return strings.Join([]string{+ "autopilot-recent-duplicate",+ util.UUIDToString(workspaceID),+ util.UUIDToString(autopilotID),+ util.UUIDToString(projectID),+ normalizedTitle,+ }, "|")+}diff --git a/server/internal/scheduler/jobs_autopilot.go b/server/internal/scheduler/jobs_autopilot.goindex 199e70a06b..85fa5205dc 100644--- a/server/internal/scheduler/jobs_autopilot.go+++ b/server/internal/scheduler/jobs_autopilot.go@@ -30,6 +30,13 @@ const ScopeKindAutopilotTrigger = "autopilot_trigger"// service.DefaultAutopilotTriggerTimezone.const DefaultAutopilotScheduleTimezone = "UTC"+// maxAutopilotScheduleLateness is the acceptance window for dispatching a+// cron occurrence after its configured plan_time. Normal scheduler jitter is+// tens of seconds; anything beyond this is a stale catch-up and should wait+// for the next configured slot instead of firing at an arbitrary activation+// time.+const maxAutopilotScheduleLateness = 5 * time.Minute+// AutopilotScheduleDispatcher is the narrow contract this job needs// from service.AutopilotService. Defined here so unit tests in this// package (and the cmd/server integration tests) can stub it without@@ -211,10 +218,11 @@ func autopilotScopes(}// autopilotPlansForScope returns the PlansForScope hook that computes-// every cron occurrence in (lastPlan, dbNow] and keeps only the most-// recent one. This matches the legacy goroutine's "collapse missed-// fires" semantics; a future per-trigger catch_up_mode column can flip-// the policy without touching scheduler internals.+// every cron occurrence in (lastPlan, dbNow], keeps only the most recent+// one, and rejects it if it is outside the dispatch-lateness window.+// The latest-only collapse prevents a long outage from replaying every+// missed slot; the lateness guard prevents a paused / newly eligible+// trigger from firing hours after its configured time.//// Retry-eligible state is handled specially: when the most recent// stored plan_time is a FAILED row with attempts remaining and@@ -300,10 +308,18 @@ func autopilotPlansForScope(cache *autopilotScheduleCache) func(return nil, nil}// CatchUpLatestOnly: collapse missed fires to the most recent.- return occs[len(occs)-1:], nil+ latestDue := occs[len(occs)-1]+ if isAutopilotSchedulePlanStale(now, latestDue) {+ return nil, nil+ }+ return []time.Time{latestDue}, nil}}+func isAutopilotSchedulePlanStale(now, planTime time.Time) bool {+ return now.Sub(planTime) > maxAutopilotScheduleLateness+}+// autopilotHandler dispatches one (trigger, planTime) attempt and// returns the lease-affecting outcome. It re-loads the trigger +// autopilot inside the handler so a between-tick state change (e.g.diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 9d022a3c0f..49dac019ad 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"@@ -39,6 +40,8 @@ type AutopilotService struct {// when computing next run times.const DefaultAutopilotTriggerTimezone = "UTC"+const autopilotRecentDuplicateWindow = 60 * time.Second+func NewAutopilotService(q *db.Queries, tx TxStarter, bus *events.Bus, taskSvc *TaskService) *AutopilotService {return &AutopilotService{Queries: q, TxStarter: tx, Bus: bus, TaskSvc: taskSvc}}@@ -299,6 +302,14 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopititle := s.interpolateTemplate(ap, *run, triggerTimezone)description := s.buildIssueDescription(ap, *run, triggerTimezone)+ if duplicate, found, err := issueguard.LockAndFindRecentAutopilotDuplicate(+ ctx, qtx, ap.WorkspaceID, ap.ID, ap.ProjectID, title, autopilotRecentDuplicateWindow,+ ); err != nil {+ return fmt.Errorf("recent duplicate guard: %w", err)+ } else if found {+ return &errDispatchSkipped{reason: "recent duplicate autopilot issue: " + util.UUIDToString(duplicate.ID)}+ }+issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)if err != nil {return fmt.Errorf("increment issue counter: %w", err)@@ -356,12 +367,11 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi}}- if err := tx.Commit(ctx); err != nil {- return fmt.Errorf("commit tx: %w", err)- }-- // Update run with the linked issue.- updatedRun, err := s.Queries.UpdateAutopilotRunIssueCreated(ctx, db.UpdateAutopilotRunIssueCreatedParams{+ // Link the run inside the same tx as the issue insert. This makes the+ // recent-duplicate guard count only fully observable autopilot issues and+ // avoids a crash window where recovery would see an orphan issue but no+ // linked run.+ updatedRun, err := qtx.UpdateAutopilotRunIssueCreated(ctx, db.UpdateAutopilotRunIssueCreatedParams{ID: run.ID,IssueID: issue.ID,})@@ -370,6 +380,10 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi}*run = updatedRun+ if err := tx.Commit(ctx); err != nil {+ return fmt.Errorf("commit tx: %w", err)+ }+// Publish issue:created so the existing event chain fires// (subscriber listeners, activity listeners, notification listeners). For// squad autopilots, this is what triggers shouldEnqueueSquadLeaderOnAssign@@ -1381,6 +1395,7 @@ func (s *AutopilotService) getIssuePrefix(workspaceID pgtype.UUID) string {// - public_to agent -> workspace target admits any workspace-member creator// (and agent-created autopilots as workspace principals); member target// admits the matching creator; team targets are inert.+//// Fail-closed on any lookup error.func (s *AutopilotService) canCreatorInvokeAgent(ctx context.Context, ap db.Autopilot, agent db.Agent) bool {creatorID := util.UUIDToString(ap.CreatedByID)diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 31a1a1a603..71ae4b8460 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -460,6 +460,73 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDureturn i, err}+const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage FROM issue i+WHERE i.workspace_id = $1+ AND i.status NOT IN ('done', 'cancelled')+ AND i.origin_type = 'autopilot'+ AND i.origin_id = $2+ AND i.project_id IS NOT DISTINCT FROM $3::uuid+ AND lower(btrim(regexp_replace(i.title, '[[:space:]]+', ' ', 'g'))) = $4+ AND i.created_at >= $5::timestamptz+ AND EXISTS (+ SELECT 1+ FROM autopilot_run r+ WHERE r.issue_id = i.id+ AND r.autopilot_id = i.origin_id+ AND r.status IN ('issue_created', 'running', 'completed')+ )+ORDER BY i.created_at ASC+LIMIT 1+`++type FindRecentAutopilotDuplicateIssueParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OriginID pgtype.UUID `json:"origin_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ NormalizedTitle string `json:"normalized_title"`+ CreatedAfter pgtype.Timestamptz `json:"created_after"`+}++func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg FindRecentAutopilotDuplicateIssueParams) (Issue, error) {+ row := q.db.QueryRow(ctx, findRecentAutopilotDuplicateIssue,+ arg.WorkspaceID,+ arg.OriginID,+ arg.ProjectID,+ arg.NormalizedTitle,+ arg.CreatedAfter,+ )+ var i Issue+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ &i.Stage,+ )+ return i, err+}+const getIssue = `-- name: GetIssue :oneSELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issueWHERE id = $1diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 5e2146bac5..1ae6c1c4be 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -134,6 +134,25 @@ WHERE workspace_id = $1ORDER BY created_at ASCLIMIT 1;+-- name: FindRecentAutopilotDuplicateIssue :one+SELECT i.* FROM issue i+WHERE i.workspace_id = $1+ AND i.status NOT IN ('done', 'cancelled')+ AND i.origin_type = 'autopilot'+ AND i.origin_id = $2+ AND i.project_id IS NOT DISTINCT FROM sqlc.arg('project_id')::uuid+ AND lower(btrim(regexp_replace(i.title, '[[:space:]]+', ' ', 'g'))) = sqlc.arg('normalized_title')+ AND i.created_at >= sqlc.arg('created_after')::timestamptz+ AND EXISTS (+ SELECT 1+ FROM autopilot_run r+ WHERE r.issue_id = i.id+ AND r.autopilot_id = i.origin_id+ AND r.status IN ('issue_created', 'running', 'completed')+ )+ORDER BY i.created_at ASC+LIMIT 1;+-- name: DeleteIssue :exec-- Defense-in-depth: the workspace_id predicate makes the tenant invariant a-- SQL-layer guarantee rather than a handler-layer one. Handler loaders