Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7326 fix(service): coalesce duplicate EnqueueTaskForIssue on the assignee path (#5914) (#6304)
Rusty Ravenb8d03bc3f498
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex d4d79c82e0..49a0723cb9 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -2598,7 +2598,13 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issureturn nil}if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, triggerCommentID); err != nil {- slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)+ // EnqueueTaskForIssue now returns ErrDuplicatePendingTask on the+ // benign duplicate-pending-task race, so use the shared helper that+ // downgrades that case to debug — matching the squad-leader and+ // mention cases and letting resolveCommentTriggerEnqueue coalesce+ // instead of surfacing a warning (#5914).+ logCommentEnqueueFailure("enqueue agent task on comment failed", err,+ "issue_id", uuidToString(issue.ID))return err}case commentTriggerSourceMentionSquadLeader:diff --git a/server/internal/handler/comment_duplicate_enqueue_race_test.go b/server/internal/handler/comment_duplicate_enqueue_race_test.goindex ea467a486e..6e93f9fa37 100644--- a/server/internal/handler/comment_duplicate_enqueue_race_test.go+++ b/server/internal/handler/comment_duplicate_enqueue_race_test.go@@ -9,6 +9,7 @@ import ("testing""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype""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"@@ -70,52 +71,97 @@ func commentCovered(t *testing.T, issueID, agentID, commentID, statusFilter stri// it (the merge makes the newer comment the trigger and pushes the prior trigger// into coalesced), so the single run covers both. Coalesced outcome, one pending// task, and no warning / constraint-name leak.+//+// Run once per trigger source that can lose this race on an issue whose agent is+// the assignee. The mention source has been covered since #5958; the+// ISSUE-ASSIGNEE source is the half #5914 left behind, and it is not redundant:+// its enqueue surfaced the RAW unique violation, so the loser came back+// blocked/internal_error instead of coalescing. That dropped the comment's+// instruction outright — the comment-creation path has no obligation hand-off+// (unlike completion reconcile), and a losing comment usually PREDATES the+// winning task row, so completion reconcile's created_at window cannot pick it+// up either.func TestCommentEnqueueRaceQueuedWinnerFoldsLoser(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- ctx := context.Background()- agentID, issueID, _ := dupRaceFixture(t, "dup-race-queued", 999311)- agentUUID := util.MustParseUUID(agentID)- issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))- if err != nil {- t.Fatalf("load issue: %v", err)- }- agent, err := testHandler.Queries.GetAgent(ctx, agentUUID)- if err != nil {- t.Fatalf("load agent: %v", err)- }-- winnerCommentID := insertDupRaceComment(t, issueID, "first instruction", "6 minutes")- if _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID)); err != nil {- t.Fatalf("enqueue winning task: %v", err)- }- loserCommentID := insertDupRaceComment(t, issueID, "second distinct instruction", "1 minute")-- var logs bytes.Buffer- prev := slog.Default()- slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))- t.Cleanup(func() { slog.SetDefault(prev) })-- trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}- results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})-- if res := results[agentID]; res.status != DispatchCoalesced {- t.Fatalf("queued-winner race: got status %q reason %q, want coalesced", res.status, res.reason)- }- if !commentCovered(t, issueID, agentID, loserCommentID, "queued") {- t.Fatal("losing comment was NOT folded into the queued winner — its instruction would be dropped")- }- if !commentCovered(t, issueID, agentID, winnerCommentID, "queued") {- t.Fatal("winner comment is no longer covered after the fold")- }- if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {- t.Fatalf("pending task count = %d, want exactly 1", n)- }- for _, leak := range []string{"idx_one_pending_task_per_issue_agent", "level=WARN", "level=ERROR"} {- if strings.Contains(logs.String(), leak) {- t.Fatalf("benign enqueue race leaked %q into logs:\n%s", leak, logs.String())- }+ cases := []struct {+ name string+ agentName string+ issueNumber int+ source commentAgentTriggerSource+ enqueueWinner func(ctx context.Context, issue db.Issue, agentID, commentID pgtype.UUID) error+ }{+ {+ name: "mention",+ agentName: "dup-race-queued",+ issueNumber: 999311,+ source: commentTriggerSourceMentionAgent,+ enqueueWinner: func(ctx context.Context, issue db.Issue, agentID, commentID pgtype.UUID) error {+ _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentID, commentID)+ return err+ },+ },+ {+ name: "issue_assignee",+ agentName: "dup-race-assignee",+ issueNumber: 999316,+ source: commentTriggerSourceIssueAssignee,+ enqueueWinner: func(ctx context.Context, issue db.Issue, _, commentID pgtype.UUID) error {+ _, err := testHandler.TaskService.EnqueueTaskForIssue(ctx, issue, commentID)+ return err+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ agentID, issueID, _ := dupRaceFixture(t, tc.agentName, tc.issueNumber)+ agentUUID := util.MustParseUUID(agentID)+ issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatalf("load issue: %v", err)+ }+ agent, err := testHandler.Queries.GetAgent(ctx, agentUUID)+ if err != nil {+ t.Fatalf("load agent: %v", err)+ }++ winnerCommentID := insertDupRaceComment(t, issueID, "first instruction", "6 minutes")+ if err := tc.enqueueWinner(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID)); err != nil {+ t.Fatalf("enqueue winning task: %v", err)+ }+ loserCommentID := insertDupRaceComment(t, issueID, "second distinct instruction", "1 minute")++ var logs bytes.Buffer+ prev := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))+ t.Cleanup(func() { slog.SetDefault(prev) })++ trigger := commentAgentTrigger{Agent: agent, Source: tc.source}+ results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})++ // Guards the service hunk: the lost race must coalesce, not block.+ if res := results[agentID]; res.status != DispatchCoalesced {+ t.Fatalf("queued-winner race: got status %q reason %q, want coalesced", res.status, res.reason)+ }+ if !commentCovered(t, issueID, agentID, loserCommentID, "queued") {+ t.Fatal("losing comment was NOT folded into the queued winner — its instruction would be dropped")+ }+ if !commentCovered(t, issueID, agentID, winnerCommentID, "queued") {+ t.Fatal("winner comment is no longer covered after the fold")+ }+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("pending task count = %d, want exactly 1", n)+ }+ // Guards the handler hunk: a benign race must not surface as WARN/ERROR.+ for _, leak := range []string{"idx_one_pending_task_per_issue_agent", "level=WARN", "level=ERROR"} {+ if strings.Contains(logs.String(), leak) {+ t.Fatalf("benign enqueue race leaked %q into logs:\n%s", leak, logs.String())+ }+ }+ })}}diff --git a/server/internal/service/duplicate_pending_task_test.go b/server/internal/service/duplicate_pending_task_test.goindex 4663f413f3..8af01914a5 100644--- a/server/internal/service/duplicate_pending_task_test.go+++ b/server/internal/service/duplicate_pending_task_test.go@@ -99,3 +99,60 @@ func TestEnqueueTaskForMentionCoalescesDuplicatePendingTask(t *testing.T) {t.Fatalf("pending task count = %d, want exactly 1", n)}}++// TestEnqueueTaskForIssueCoalescesDuplicatePendingTask is the service-level+// regression for the issue-assignee enqueue path (#5914). EnqueueTaskForIssue+// routes through enqueueIssueTaskWithCommentPlan, the second write point of the+// idx_one_pending_task_per_issue_agent unique index. A concurrent duplicate on+// this path used to surface as a raw create-task error (HTTP 500 with the+// leaked constraint name); it must now return the same typed+// ErrDuplicatePendingTask sentinel as the mention path and leave exactly one+// pending task behind.+func TestEnqueueTaskForIssueCoalescesDuplicatePendingTask(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)+ t.Cleanup(func() {+ pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ })++ issueStruct := db.Issue{+ ID: util.MustParseUUID(issueID),+ AssigneeID: util.MustParseUUID(agentID),+ Priority: "medium",+ CreatorType: "member",+ CreatorID: util.MustParseUUID(userID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ }+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}++ // First assignee enqueue creates the pending task.+ if _, err := svc.EnqueueTaskForIssue(ctx, issueStruct); err != nil {+ t.Fatalf("first EnqueueTaskForIssue: %v", err)+ }++ // Second enqueue for the same (issue, agent) collides on the unique index.+ _, err := svc.EnqueueTaskForIssue(ctx, issueStruct)+ if !errors.Is(err, ErrDuplicatePendingTask) {+ t.Fatalf("second EnqueueTaskForIssue: err = %v, want ErrDuplicatePendingTask", err)+ }+ // The returned error must NOT carry the raw Postgres constraint name or+ // SQLSTATE — those used to leak into upper-layer warning logs (#5914).+ for _, leak := range []string{"idx_one_pending_task_per_issue_agent", "23505", "SQLSTATE", "duplicate key"} {+ if strings.Contains(err.Error(), leak) {+ t.Fatalf("duplicate error leaked %q: %v", leak, err)+ }+ }++ var n int+ if err := pool.QueryRow(ctx,+ `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued','dispatched')`,+ issueID, agentID).Scan(&n); err != nil {+ t.Fatalf("count pending tasks: %v", err)+ }+ if n != 1 {+ t.Fatalf("pending task count = %d, want exactly 1", n)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 14d9fcec4a..bd94ddf533 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -738,13 +738,19 @@ 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.+// Both paths behind RerunIssue now normalize the unique violation into the bare+// ErrDuplicatePendingTask sentinel: enqueueMentionTaskWithCommentPlan since+// #5958, and enqueueIssueTaskWithCommentPlan as of #5914 above. The sentinel+// half is therefore what matches in practice, and it has to be here — the+// mention path is the one 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), and 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.+//+// The raw-violation half is kept deliberately, as a cheap defensive net: one+// errors.As, and it keeps this predicate honest for any caller that reaches it+// without passing through one of those two normalizing paths.func pendingSlotTakenErr(err error) bool {return isDuplicatePendingTaskErr(err) || errors.Is(err, ErrDuplicatePendingTask)}@@ -1336,6 +1342,16 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issuetask, err = s.Queries.CreateAgentTask(ctx, createParams)}if err != nil {+ // A concurrent enqueue for the same (issue, agent) won the race and the+ // unique index rejected this insert. That is benign — a sibling run+ // already covers this target — so log it at debug and return a typed+ // sentinel the caller maps to a coalesced outcome / 409 rather than a+ // 500 that leaks the raw constraint name (#5914). Mirrors the mention+ // path in enqueueMentionTaskWithCommentPlan.+ if isDuplicatePendingTaskErr(err) {+ slog.Debug("task enqueue coalesced: pending task already exists", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(issue.AssigneeID))+ return db.AgentTaskQueue{}, ErrDuplicatePendingTask+ }slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", err)return db.AgentTaskQueue{}, fmt.Errorf("create task: %w", err)}