Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(handler,service): return 409/coalesced instead of 500 on duplicate-key violations (MUL-5285) (#5958)
Bohan Jiang49fd6cd08aaf
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 4afef93c3a..1f5fd2d3a8 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -1806,6 +1806,21 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {updated, err := h.Queries.UpdateAgent(r.Context(), params)if err != nil {+ // Unique constraint on (workspace_id, name) — mirror CreateAgent and+ // return a clear conflict instead of a 500 that leaks the raw+ // constraint name. The name can still be held by an *archived* agent+ // (the constraint does not exclude archived rows), so this is the only+ // signal the caller gets that a rename collided rather than the server+ // faulting.+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "agent_workspace_name_unique" {+ name := ""+ if req.Name != nil {+ name = *req.Name+ }+ writeError(w, http.StatusConflict, fmt.Sprintf("an agent named %q already exists in this workspace", name))+ return+ }slog.Warn("update agent failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)writeError(w, http.StatusInternalServerError, "failed to update agent: "+err.Error())returndiff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.goindex 0af64196a5..e8b0b944f5 100644--- a/server/internal/handler/agent_test.go+++ b/server/internal/handler/agent_test.go@@ -587,6 +587,41 @@ func TestCreateAgent_RejectsDuplicateName(t *testing.T) {}}+// TestUpdateAgent_RejectsRenameToArchivedName is the regression for #5914: the+// (workspace_id, name) unique constraint does not exclude archived agents, so a+// rename that collides with an *archived* agent's still-reserved name used to+// fall through UpdateAgent as a raw 500 that leaked the constraint name — while+// CreateAgent already mapped the same collision to a clean 409. This asserts the+// two entry points now agree: a structured 409, and no raw constraint in the body.+func TestUpdateAgent_RejectsRenameToArchivedName(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ // Agent A holds the name, then is archived — the name stays reserved.+ const heldName = "rename-collision-archived-name"+ idA := createHandlerTestAgent(t, heldName, nil)+ archiveReq := withURLParam(newRequest(http.MethodPost, "/api/agents/"+idA+"/archive", nil), "id", idA)+ archiveW := httptest.NewRecorder()+ testHandler.ArchiveAgent(archiveW, archiveReq)+ if archiveW.Code != http.StatusOK {+ t.Fatalf("ArchiveAgent: expected 200, got %d: %s", archiveW.Code, archiveW.Body.String())+ }++ // Agent B renames itself into the archived agent's name.+ idB := createHandlerTestAgent(t, "rename-collision-source", nil)+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(+ newRequest(http.MethodPatch, "/api/agents/"+idB, map[string]any{"name": heldName}), "id", idB))++ if w.Code != http.StatusConflict {+ t.Fatalf("rename to archived agent's name: expected 409, got %d: %s", w.Code, w.Body.String())+ }+ if strings.Contains(w.Body.String(), "agent_workspace_name_unique") {+ t.Fatalf("409 body leaked the raw constraint name: %s", w.Body.String())+ }+}+func TestCreateAgent_AssignsAvatarDefault(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 01c3057dd2..d13e594f9e 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1534,50 +1534,156 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issuresults[uuidToString(trigger.Agent.ID)] = commentEnqueueResult{status: status, reason: reason, execSquadID: execSquadID}}for _, trigger := range triggers {- if trigger.AlreadyPending {- // MUL-4195: a queued/dispatched task for this (issue, agent)- // already exists. Historically we DROPPED the comment here, losing- // the user's follow-up instruction. Instead try to fold it into the- // queued (not-yet-claimed) task so a single run still covers every- // comment, re-stamping the run's originator/overlay to the new- // comment (mergeCommentIntoPendingTask).- //- // The merge reports HOW it resolved: a real merge is coalesced, a- // fail-closed / failed merge is blocked (attribution_blocked /- // internal_error) — never mislabeled as success (MUL-4525 §2, Elon- // round 5). Only "no queued task to fold into" falls through to the- // active-task decision below.+ status, reason := h.resolveCommentTriggerEnqueue(ctx, issue, trigger, triggerCommentID, getEscalationDelay)+ record(trigger, status, reason)+ }+ return results+}++// resolveCommentTriggerEnqueue resolves ONE trigger into its final dispatch+// outcome, folding the comment into an existing pending task rather than+// dropping it (MUL-4195). It handles the two ways the (issue, agent) pair can+// already hold a pending task:+//+// - resolution pre-flagged AlreadyPending, or+// - a fresh enqueue LOST the race to a concurrent sibling and the+// idx_one_pending_task_per_issue_agent unique index rejected the insert+// (service.ErrDuplicatePendingTask, #5914).+//+// Both mean "a task now exists". INVARIANT: a success-shaped outcome (coalesced /+// deferred / queued) is returned only when the comment is provably attached to a+// run that will address it:+//+// - coalesced — an atomic head-scoped merge folded it into a queued task;+// - queued — a fresh task was created for it;+// - deferred — an active task's completion reconcile will replay it, either+// because a planned-id write landed on a claim-receipt task+// (lost-race path, where the comment may PREDATE the task) or+// because the comment is newer than that task and therefore+// inside reconcile's `created_at > since` window (AlreadyPending+// path, where the task existed before the comment).+//+// The deferral is not a one-shot prediction: if a replay is later blocked by a+// task that cannot cover the comment, reconcileCommentsOnCompletion hands the+// obligation on (propagateUncoveredCommentObligation) instead of discarding it,+// and that hand-off retries across the blocker's state changes (#5914, Elon+// rounds 8–9). It is best-effort in exactly one shape — a DIFFERENT-head QUEUED+// blocker, which can neither cover the comment nor accept it without violating+// TEN-356 — and that case is logged at error rather than hidden; closing it needs+// a durable obligation record, which is deliberately out of scope here.+// It never defers off a mere classification of the current active tasks — a+// snapshot cannot prove anything about state after it is read (round 7).+// A duplicate that cannot yet be resolved re-loops (bounded by maxAttempts); on+// genuine non-convergence it returns a truthful internal_error, never a fabricated+// deferred that would silently drop the comment.+func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, triggerCommentID pgtype.UUID, getEscalationDelay func() time.Duration) (DispatchStatus, DispatchReasonCode) {+ pending := trigger.AlreadyPending+ lostRace := false+ // Resolve the reviewed HEAD lazily and at most once — the common+ // non-pending path enqueues without ever needing it, so it stays off the+ // hot path. It keys both the head-scoped merge and the planned-comment+ // registration, matching the AlreadyPending pre-check's head (TEN-356).+ var headSha pgtype.Text+ headShaLoaded := false+ getHeadSha := func() pgtype.Text {+ if !headShaLoaded {+ headSha = h.TaskService.ResolveIssueReviewSHAParam(ctx, issue.ID)+ headShaLoaded = true+ }+ return headSha+ }+ // Bounded retry (#5914, Elon round 3). INVARIANT: never return a+ // success-shaped outcome (coalesced / deferred / queued) without a COMPLETED+ // merge, planned-id registration, fresh enqueue, or a confirmed different-head+ // deferral. A duplicate that cannot be durably resolved re-loops; on genuine+ // non-convergence we return a truthful internal_error below, never a+ // fabricated deferred that would silently drop the comment. maxAttempts is a+ // concurrent-churn backstop — each duplicate is followed by a merge/register+ // attempt, so the loop only spins while a sibling keeps flipping state.+ const maxAttempts = 4+ for attempt := 0; attempt < maxAttempts; attempt++ {+ if pending {+ // (a) Fold into a same-head QUEUED task. This is the ONLY path that+ // ATOMICALLY re-attributes the run (trigger / originator / accountable+ // / overlay / connected apps) to the folded comment, so a queued+ // winner must always come through here, never a bare planned append+ // (MUL-4302). HEAD-scoped so a DIFFERENT-head task is never folded+ // (TEN-356) — the merge misses and this falls through. The merge+ // reports HOW it resolved: coalesced on success; blocked on a+ // fail-closed / failed merge — never mislabeled as success (MUL-4525 §2).if status, reason, terminal := commentMergeTerminalOutcome(- h.mergeCommentIntoPendingTask(ctx, issue, trigger, triggerCommentID),+ h.mergeCommentIntoPendingTask(ctx, issue, trigger, triggerCommentID, getHeadSha()),); terminal {- record(trigger, status, reason)- continue+ return status, reason}- // The merge found no queued task to fold into: the existing task- // is already dispatched/running (its claim response is built), or- // the queued row was just claimed. We must NOT enqueue a- // fresh queued task in that case — a dispatched sibling would trip- // the idx_one_pending_task_per_issue_agent unique index (dropping- // the comment again) and even where the index allows it we'd risk a- // duplicate concurrent run. When an active task exists, its- // completion reconcile (reconcileCommentsOnCompletion) is what- // guarantees this comment earns a bounded follow-up. Only when NO- // active task exists is a fresh enqueue both safe and necessary. On a- // query failure we fail closed (no fresh enqueue) and report a- // non-success internal_error rather than a fabricated deferred.- active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID)- if status, reason, enqueueFresh := decidePostMergeMiss(active, activeErr); !enqueueFresh {- record(trigger, status, reason)- continue+ // No same-head QUEUED row to fold into (merge missed). The two paths+ // resolve differently.+ if !lostRace {+ // (b) AlreadyPending path: this comment arrived AFTER its task, so+ // it is newer than the task and completion reconcile covers it by+ // timestamp; MUL-4195 leaves the claimed task untouched. Defer to+ // the active task, or enqueue fresh if it has since finished.+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID)+ if status, reason, enqueueFresh := decidePostMergeMiss(active, activeErr); !enqueueFresh {+ return status, reason+ }+ // enqueueFresh → fall through to the enqueue below.+ } else {+ // (c) Lost INSERT race: the losing comment can PREDATE the winner,+ // which completion reconcile's `created_at > since` window cannot+ // see. Register it as a planned (undelivered) input on a same-head+ // CLAIM-RECEIPT task (dispatched/running/waiting; queued is excluded+ // — it must fold through the atomic merge above), turning the drop+ // into a bounded follow-up (#5914, Elon round 2).+ registered, err := h.registerPlannedCommentForActiveTask(ctx, issue, trigger.Agent.ID, triggerCommentID, getHeadSha())+ if err != nil {+ slog.Warn("register planned lost-race comment failed",+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID), "error", err)+ return DispatchBlocked, ReasonInternalError+ }+ if registered {+ return DispatchDeferred, ReasonDeferred+ }+ // (d) No same-head QUEUED task to fold (merge missed) and no+ // same-head CLAIM-RECEIPT task to register on. Do NOT try to defer+ // off a classification of the current active tasks: a snapshot only+ // proves state NOW, and a DIFFERENT-head task's reconcile covering+ // this comment can be defeated by a newer blocker that appears after+ // the snapshot but before that task completes (its replay collides+ // with the blocker and completion reconcile discards the failure —+ // Elon round 7). Every success-shaped outcome must be backed by a+ // COMPLETED write, never a prediction. So just fall through to a+ // fresh enqueue: if the unique slot is still occupied — necessarily+ // by a different-head task we can neither fold into nor durably cover+ // — the insert re-raises ErrDuplicatePendingTask and we re-loop,+ // converging to a truthful non-success; if the slot is free, the+ // enqueue creates the covering task. (The occupant's own completion+ // reconcile still replays this comment best-effort in the common+ // no-blocker case; we simply never PROMISE it.)}}if err := h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger, getEscalationDelay); err != nil {- record(trigger, DispatchBlocked, commentEnqueueFailureReason(err))- continue- }- record(trigger, DispatchQueued, ReasonQueued)- }- return results+ // Lost the enqueue race: a sibling task for this (issue, agent) now+ // exists. Re-resolve as pending so the next attempt folds this+ // comment into that sibling (queued) or durably registers it+ // (dispatched) instead of dropping it (#5914).+ if errors.Is(err, service.ErrDuplicatePendingTask) {+ pending = true+ lostRace = true+ continue+ }+ return DispatchBlocked, commentEnqueueFailureReason(err)+ }+ return DispatchQueued, ReasonQueued+ }+ // Non-convergence after the bounded retries (only reachable under sustained+ // concurrent churn where a sibling keeps flipping state under us): surface a+ // truthful non-success — NEVER a fabricated deferred/coalesced that would+ // report the comment covered when no task provably covers it (#5914, Elon+ // round 3). The comment row persists; a later trigger/edit can still cover it.+ slog.Warn("comment trigger enqueue did not converge; reporting non-success",+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID))+ return DispatchBlocked, ReasonInternalError}// commentTriggerOutcomes maps each explicit mention target to its final outcome@@ -1750,7 +1856,7 @@ func commentMergeTerminalOutcome(result commentMergeResult) (status DispatchStat// refreshed — so a different member's comment safely folds into a task another// member created, the coalescing run carrying the latest instruction's// originator and matching connected-app overlay.-func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, newTriggerCommentID pgtype.UUID) commentMergeResult {+func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, newTriggerCommentID pgtype.UUID, headSha pgtype.Text) commentMergeResult {// Re-attribute the coalescing run to the new comment's human atomically: the// whole attribution snapshot moves, not just the person columns (MUL-4302). An// issue-assignee reaction is comment_source; a mention / thread-parent /@@ -1788,6 +1894,7 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.IssuNewTriggerSummary: h.TaskService.BuildCommentTriggerSummary(ctx, issue.WorkspaceID, newTriggerCommentID),NewRuntimeMcpOverlay: overlay,NewRuntimeConnectedApps: connectedApps,+ HeadSha: headSha,})if err != nil {if isNotFound(err) {@@ -1814,6 +1921,113 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issureturn commentMergeSucceeded}+// registerPlannedCommentForActiveTask durably folds a lost-race comment into the+// same-head active task's planned (coalesced) set when the queued merge could no+// longer target it (the winner was already claimed → dispatched/running). It+// returns true when a same-head active task absorbed the comment; (false, nil)+// means no same-head active task exists (a DIFFERENT-head task holds the slot, or+// the task just terminated), so the caller falls back to the active-task+// decision. Delivered ids are untouched, so completion reconcile replays the+// comment as a single bounded follow-up (#5914). See the query doc.+func (h *Handler) registerPlannedCommentForActiveTask(ctx context.Context, issue db.Issue, agentID, commentID pgtype.UUID, headSha pgtype.Text) (bool, error) {+ row, err := h.Queries.RegisterPlannedCommentForActiveTask(ctx, db.RegisterPlannedCommentForActiveTaskParams{+ CommentID: commentID,+ IssueID: issue.ID,+ AgentID: agentID,+ HeadSha: headSha,+ })+ if err != nil {+ if isNotFound(err) {+ return false, nil+ }+ return false, err+ }+ slog.Info("registered lost-race comment as planned follow-up input",+ "task_id", uuidToString(row.ID),+ "issue_id", uuidToString(issue.ID),+ "agent_id", uuidToString(agentID),+ "comment_id", uuidToString(commentID),+ "coalesced_count", len(row.CoalescedCommentIds))+ return true, nil+}++// propagateUncoveredCommentObligation hands an UNCOVERED comment's replay+// obligation to whichever active task now occupies the (issue, agent) slot, so a+// blocked completion replay is never silently dropped (#5914, Elon round 8).+//+// Without this, a deferral is only ever consumed ONCE: task A's completion+// reconcile replays comment C, the enqueue collides with a newer blocker B, the+// failure is discarded, and B never sees C (C predates B and is not in its+// planned ids) — so C is lost even though the original response promised it would+// be handled. Propagating turns "consumed once" into "handed along" until some+// task provably covers C.+//+// Each attempt tries, in order, the three writes that can durably cover the+// comment, and RETRIES when the slot's occupant changes state under us — the+// hand-off is not one atomic statement, so a blocker that completes or gets+// claimed between two steps must be re-observed rather than lost (Elon round 9):+//+// 1. a CLAIM-RECEIPT task (dispatched/running/waiting), ANY head: a planned id+// added after the claim is never delivered to that run, so it cannot consume+// the comment under the wrong head — it purely schedules the comment for that+// task's own completion reconcile, which re-enqueues at the head current then;+// 2. a SAME-HEAD queued task: the atomic merge, which re-stamps trigger /+// originator / overlay (MUL-4302). This is HEAD-SCOPED on purpose: merging+// into a different-head queued task would make the comment that run's trigger+// and mark it delivered at claim time, so an old-head run would consume a+// new-head request and no new-head follow-up would ever be created — the+// TEN-356 violation (Elon round 9, must-fix 2);+// 3. a fresh enqueue: correct precisely when the blocker has finished and freed+// the unique slot, which is the state a mid-hand-off completion leaves behind.+//+// A duplicate-key error from (3) means the slot is still held, so the loop+// re-observes and tries again. Returns false only when every attempt found the+// slot held by a task that can neither cover nor accept the comment (a+// different-head QUEUED blocker); the caller logs that loudly — it is the one+// shape today's schema has no safe place to park, and closing it needs a durable+// obligation record rather than an in-request hand-off.+func (h *Handler) propagateUncoveredCommentObligation(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, commentID pgtype.UUID, headSha pgtype.Text) bool {+ noEscalation := func() time.Duration { return 0 }+ const maxAttempts = 3+ for attempt := 0; attempt < maxAttempts; attempt++ {+ registered, err := h.registerPlannedCommentForActiveTask(ctx, issue, trigger.Agent.ID, commentID, pgtype.Text{})+ if err != nil {+ slog.Warn("propagate comment obligation: register on active task failed",+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID),+ "comment_id", uuidToString(commentID), "error", err)+ } else if registered {+ return true+ }+ if h.mergeCommentIntoPendingTask(ctx, issue, trigger, commentID, headSha) == commentMergeSucceeded {+ return true+ }+ err = h.enqueueSingleCommentTrigger(ctx, issue, commentID, trigger, noEscalation)+ if err == nil {+ return true+ }+ if !errors.Is(err, service.ErrDuplicatePendingTask) {+ return false+ }+ // The slot is still occupied; its occupant may have changed state between+ // the steps above, so re-observe and try again.+ }+ return false+}++// logCommentEnqueueFailure logs a failed comment-trigger enqueue. A benign+// duplicate-pending-task race (service.ErrDuplicatePendingTask) is not a fault —+// resolveCommentTriggerEnqueue folds the comment into the winning task — so it+// is logged at debug and never surfaces as a warning, keeping the raw Postgres+// constraint name out of warn/error logs (#5914, Elon review). Any other error+// stays a warning with the error attached.+func logCommentEnqueueFailure(msg string, err error, attrs ...any) {+ if errors.Is(err, service.ErrDuplicatePendingTask) {+ slog.Debug(msg+": duplicate pending task, coalescing into the sibling run", attrs...)+ return+ }+ slog.Warn(msg, append(attrs, "error", err)...)+}+// enqueueSingleCommentTrigger creates a fresh task for one computed trigger.// Split out of enqueueCommentAgentTriggers so the merge-not-drop path// (MUL-4195) can fall back to it when a pending task vanished mid-flight.@@ -1826,11 +2040,10 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issucase commentTriggerSourceIssueAssignee:if trigger.Squad != nil {if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {- slog.Warn("enqueue squad leader task failed",+ logCommentEnqueueFailure("enqueue squad leader task failed", err,"issue_id", uuidToString(issue.ID),"squad_id", uuidToString(trigger.Squad.ID),- "leader_id", uuidToString(trigger.Agent.ID),- "error", err)+ "leader_id", uuidToString(trigger.Agent.ID))return err}return nil@@ -1841,18 +2054,16 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu}case commentTriggerSourceMentionSquadLeader:if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {- slog.Warn("enqueue squad leader mention task failed",+ logCommentEnqueueFailure("enqueue squad leader mention task failed", err,"issue_id", uuidToString(issue.ID),- "agent_id", uuidToString(trigger.Agent.ID),- "error", err)+ "agent_id", uuidToString(trigger.Agent.ID))return err}case commentTriggerSourceMentionAgent:if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {- slog.Warn("enqueue mention agent task failed",+ logCommentEnqueueFailure("enqueue mention agent task failed", err,"issue_id", uuidToString(issue.ID),- "agent_id", uuidToString(trigger.Agent.ID),- "error", err)+ "agent_id", uuidToString(trigger.Agent.ID))return err}case commentTriggerSourceThreadParent, commentTriggerSourceConversation:@@ -1864,11 +2075,10 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issutask, err = h.TaskService.EnqueueTaskForThreadParent(ctx, issue, trigger.Agent.ID, triggerCommentID)}if err != nil {- slog.Warn("enqueue routed comment agent task failed",+ logCommentEnqueueFailure("enqueue routed comment agent task failed", err,"issue_id", uuidToString(issue.ID),"agent_id", uuidToString(trigger.Agent.ID),- "source", trigger.Source,- "error", err)+ "source", trigger.Source)return err}if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {diff --git a/server/internal/handler/comment_duplicate_enqueue_race_test.go b/server/internal/handler/comment_duplicate_enqueue_race_test.gonew file mode 100644index 0000000000..bf487766a8--- /dev/null+++ b/server/internal/handler/comment_duplicate_enqueue_race_test.go@@ -0,0 +1,832 @@+package handler++import (+ "bytes"+ "context"+ "errors"+ "log/slog"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ dupRaceHeadA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ dupRaceHeadB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+)++// dupRaceFixture creates a workspace-invocable agent and an issue assigned to it.+func dupRaceFixture(t *testing.T, agentName string, issueNumber int) (agentID, issueID, runtimeID string) {+ t.Helper()+ ctx := context.Background()+ agentID = createHandlerTestAgent(t, agentName, nil)+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)+ VALUES ($1, 'dup-enqueue-race fixture', 'in_progress', 'none', $2, 'member', $3, 0, 'agent', $4)+ RETURNING id+ `, testWorkspaceID, testUserID, issueNumber, agentID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })+ return agentID, issueID, runtimeID+}++func insertDupRaceComment(t *testing.T, issueID, content, age string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', now() - $5::interval)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id); err != nil {+ t.Fatalf("insert comment %q: %v", content, err)+ }+ return id+}++func commentCovered(t *testing.T, issueID, agentID, commentID, statusFilter string) bool {+ t.Helper()+ var ok bool+ if err := testPool.QueryRow(context.Background(), `+ SELECT $3::uuid = trigger_comment_id OR $3::uuid = ANY(coalesced_comment_ids)+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status = $4+ `, issueID, agentID, commentID, statusFilter).Scan(&ok); err != nil {+ t.Fatalf("check covered %s: %v", commentID, err)+ }+ return ok+}++// TestCommentEnqueueRaceQueuedWinnerFoldsLoser: when the lost-race winner is+// still QUEUED and shares the reviewed head, the losing comment is folded into+// 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.+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())+ }+ }+}++// TestCommentEnqueueRaceDispatchedWinnerDurablyCoversLoser is the regression for+// Elon round-2 must-fix 1: the losing comment PRECEDES a winner that is already+// DISPATCHED before the merge retry, so completion reconcile's created_at window+// cannot see it. The race path must durably register it as a planned (but NOT+// delivered) input on the active winner, and a follow-up must actually cover it+// after the winner completes — never a bare coalesced success that drops it.+func TestCommentEnqueueRaceDispatchedWinnerDurablyCoversLoser(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-dispatched", 999312)+ 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)+ }++ // Losing comment PREDATES the winner task; winner is already dispatched with+ // its claim receipt (delivered = its own trigger only).+ loserCommentID := insertDupRaceComment(t, issueID, "losing instruction (predates winner)", "10 minutes")+ winnerCommentID := insertDupRaceComment(t, issueID, "winning instruction", "6 minutes")+ var winnerTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'dispatched', 0, now() - interval '5 minutes', now() - interval '4 minutes')+ RETURNING id+ `, agentID, runtimeID, issueID, winnerCommentID).Scan(&winnerTaskID); err != nil {+ t.Fatalf("insert dispatched winner: %v", err)+ }++ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}+ results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})++ // Truthful outcome: deferred (a follow-up will cover it), NOT coalesced.+ if res := results[agentID]; res.status != DispatchDeferred {+ t.Fatalf("dispatched-winner race: got status %q reason %q, want deferred", res.status, res.reason)+ }+ // Durably planned on the winner, but NOT faked as delivered.+ var plannedHasLoser, deliveredHasLoser bool+ if err := testPool.QueryRow(ctx, `+ SELECT $2::uuid = ANY(coalesced_comment_ids), $2::uuid = ANY(delivered_comment_ids)+ FROM agent_task_queue WHERE id = $1+ `, winnerTaskID, loserCommentID).Scan(&plannedHasLoser, &deliveredHasLoser); err != nil {+ t.Fatalf("read winner planned/delivered: %v", err)+ }+ if !plannedHasLoser {+ t.Fatal("losing comment was NOT registered as a planned input on the dispatched winner")+ }+ if deliveredHasLoser {+ t.Fatal("losing comment must NOT be faked as delivered on the dispatched winner")+ }+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("pending task count = %d, want exactly 1 (the dispatched winner)", n)+ }++ // The winner completes; reconcile must replay the planned-but-undelivered+ // loser as a bounded follow-up — proving the drop is actually closed.+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '1 minute' WHERE id = $1`, winnerTaskID); err != nil {+ t.Fatalf("advance winner to running: %v", err)+ }+ if w := completeTaskViaHandler(t, winnerTaskID, "done"); w.Code != 200 {+ t.Fatalf("complete winner: got %d: %s", w.Code, w.Body.String())+ }+ if n := queuedTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("expected exactly 1 follow-up covering the loser after completion, got %d", n)+ }+ if !commentCovered(t, issueID, agentID, loserCommentID, "queued") {+ t.Fatal("follow-up does not cover the losing comment — the instruction was dropped")+ }+}++// TestCommentEnqueueRaceDifferentHeadNotCoalesced is the regression for Elon+// round-2 must-fix 2 + round-7: a comment for a NEW head (PR updated A→B) collides+// with the still-pending head-A task. It must NOT be folded into the head-A run+// (TEN-356), and — per round 7 — it must NOT be reported as a fabricated deferred+// either, since a point-in-time "an older task exists" cannot durably promise+// coverage. The honest outcome is a non-success; the head-A task's completion+// reconcile still covers the head-B comment best-effort, earning head-B coverage.+func TestCommentEnqueueRaceDifferentHeadNotCoalesced(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-headshift", 999313)+ agentUUID := util.MustParseUUID(agentID)++ // Link a PR at head B so ResolveIssueReviewSHA returns B for new enqueues.+ var prID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO github_pull_request (workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, pr_created_at, pr_updated_at, head_sha)+ VALUES ($1, 1, 'multica-ai', 'multica', 999313, 'review PR', 'open', 'https://example.test/pr', now(), now(), $2)+ RETURNING id+ `, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {+ t.Fatalf("seed PR: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })+ if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {+ t.Fatalf("link PR: %v", err)+ }++ 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)+ }++ // Pending winner stamped for the OLD head A (queued), and a NEWER head-B comment.+ headAcommentID := insertDupRaceComment(t, issueID, "review head A", "6 minutes")+ var winnerTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'queued', 0, now() - interval '5 minutes', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, headAcommentID, dupRaceHeadA).Scan(&winnerTaskID); err != nil {+ t.Fatalf("insert head-A winner: %v", err)+ }+ headBcommentID := insertDupRaceComment(t, issueID, "please review head B", "1 minute")++ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}+ results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(headBcommentID), []commentAgentTrigger{trigger})++ // Not coalesced into the head-A run, and NOT a fabricated deferred either — a+ // snapshot cannot durably promise the head-A task's reconcile will still cover+ // this comment (Elon round 7). The honest outcome is a non-success; the head-A+ // reconcile still covers it best-effort below.+ if res := results[agentID]; res.status == DispatchDeferred || res.status == DispatchCoalesced || res.status == DispatchQueued {+ t.Fatalf("different-head race: got success-shaped %q/%q, want a truthful non-success", res.status, res.reason)+ }+ if res := results[agentID]; res.status != DispatchBlocked || res.reason != ReasonInternalError {+ t.Fatalf("different-head race: got %q/%q, want blocked/internal_error", res.status, res.reason)+ }+ // The head-A task is untouched: the head-B comment was NOT folded in, and the+ // task still carries head A.+ var headBinA bool+ var winnerHead string+ if err := testPool.QueryRow(ctx, `+ SELECT $2::uuid = ANY(coalesced_comment_ids), COALESCE(context->>'head_sha','')+ FROM agent_task_queue WHERE id = $1+ `, winnerTaskID, headBcommentID).Scan(&headBinA, &winnerHead); err != nil {+ t.Fatalf("read head-A winner: %v", err)+ }+ if headBinA {+ t.Fatal("head-B comment was wrongly folded into the head-A run (TEN-356 violation)")+ }+ if winnerHead != dupRaceHeadA {+ t.Fatalf("head-A winner head_sha changed to %q, want unchanged %q", winnerHead, dupRaceHeadA)+ }++ // After the head-A task completes, reconcile enqueues fresh coverage for the+ // newer head-B comment — and that follow-up is stamped for head B.+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '1 minute' WHERE id = $1`, winnerTaskID); err != nil {+ t.Fatalf("advance head-A winner to running: %v", err)+ }+ if w := completeTaskViaHandler(t, winnerTaskID, "done"); w.Code != 200 {+ t.Fatalf("complete head-A winner: got %d: %s", w.Code, w.Body.String())+ }+ var followupHead string+ if err := testPool.QueryRow(ctx, `+ SELECT COALESCE(context->>'head_sha','')+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'+ ORDER BY created_at DESC LIMIT 1+ `, issueID, agentID).Scan(&followupHead); err != nil {+ t.Fatalf("read follow-up head: %v", err)+ }+ if followupHead != dupRaceHeadB {+ t.Fatalf("follow-up head_sha = %q, want head B %q (head B must earn its own coverage)", followupHead, dupRaceHeadB)+ }+}++// TestRegisterPlannedCommentForActiveTaskExcludesQueued is the regression for+// Elon round-3 must-fix 2: a planned-only append must never target a QUEUED task+// (it has no claim receipt, so the append would be delivered at claim time and+// bypass the atomic re-attribution a queued fold requires — MUL-4302). Only+// claim-receipt statuses (dispatched/running/waiting_local_directory) are valid+// planned-id targets; a queued task must miss so the caller routes it to the+// atomic merge instead.+func TestRegisterPlannedCommentForActiveTaskExcludesQueued(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-register-scope", 999314)+ commentID := insertDupRaceComment(t, issueID, "planned candidate", "1 minute")+ triggerID := insertDupRaceComment(t, issueID, "winner trigger", "6 minutes")++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at)+ VALUES ($1, $2, $3, $4, 'queued', 0, now() - interval '5 minutes')+ RETURNING id+ `, agentID, runtimeID, issueID, triggerID).Scan(&taskID); err != nil {+ t.Fatalf("insert queued task: %v", err)+ }++ params := db.RegisterPlannedCommentForActiveTaskParams{+ CommentID: util.MustParseUUID(commentID),+ IssueID: util.MustParseUUID(issueID),+ AgentID: util.MustParseUUID(agentID),+ }++ // QUEUED target must MISS.+ if _, err := testHandler.Queries.RegisterPlannedCommentForActiveTask(ctx, params); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("register against a QUEUED task: err = %v, want pgx.ErrNoRows (queued excluded)", err)+ }++ // Flip to dispatched: now the claim receipt exists and the append is valid.+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`, taskID); err != nil {+ t.Fatalf("flip to dispatched: %v", err)+ }+ row, err := testHandler.Queries.RegisterPlannedCommentForActiveTask(ctx, params)+ if err != nil {+ t.Fatalf("register against a DISPATCHED task: %v", err)+ }+ var found bool+ for _, id := range row.CoalescedCommentIds {+ if uuidToString(id) == commentID {+ found = true+ }+ }+ if !found {+ t.Fatalf("dispatched register did not add the planned comment: %v", row.CoalescedCommentIds)+ }+}++// TestCommentEnqueueRaceQueuedWinnerReattributesOriginator is the regression for+// Elon round-3 must-fix 2: when the lost-race winner is a same-head QUEUED task,+// the losing comment must fold through the ATOMIC merge, which re-stamps the run+// to the NEW comment's originator — never a bare planned append that would leave+// a second member's comment executing under the first member's identity. Two+// different members: the winner is attributed to M1, the losing comment is M2's,+// and after the race the run must be re-attributed to M2.+func TestCommentEnqueueRaceQueuedWinnerReattributesOriginator(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, _ := dupRaceFixture(t, "dup-race-reattr", 999315)+ 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)+ }++ // A second member M2 authors the losing comment.+ var m2 string+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Race M2', '[email protected]') RETURNING id`).Scan(&m2); err != nil {+ t.Fatalf("create M2 user: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, m2) })+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, testWorkspaceID, m2); err != nil {+ t.Fatalf("create M2 member: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM member WHERE user_id = $1`, m2) })++ // Winner: a queued task attributed to M1 (testUserID) via its own comment.+ winnerCommentID := insertDupRaceComment(t, issueID, "M1 instruction", "6 minutes")+ if _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID)); err != nil {+ t.Fatalf("enqueue winning task: %v", err)+ }+ // Losing comment authored by M2.+ var loserCommentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, 'M2 instruction', 'comment', now() - interval '1 minute')+ RETURNING id+ `, issueID, testWorkspaceID, m2).Scan(&loserCommentID); err != nil {+ t.Fatalf("insert M2 loser comment: %v", err)+ }++ 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 reattribution race: got status %q reason %q, want coalesced", res.status, res.reason)+ }++ // The run is now attributed to M2 (the folded comment's author) and triggered+ // by M2's comment — proving the atomic merge ran, not a bare planned append.+ var trig, orig string+ if err := testPool.QueryRow(ctx, `+ SELECT COALESCE(trigger_comment_id::text,''), COALESCE(originator_user_id::text,'')+ FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'+ `, issueID, agentID).Scan(&trig, &orig); err != nil {+ t.Fatalf("read winner attribution: %v", err)+ }+ if trig != loserCommentID {+ t.Fatalf("trigger_comment_id = %s, want repointed to M2's comment %s", trig, loserCommentID)+ }+ if orig != m2 {+ t.Fatalf("originator_user_id = %s, want re-attributed to M2 %s (bare append would leave M1)", orig, m2)+ }+}+++// TestCommentEnqueueRaceNewerDifferentHeadNotDeferred is the regression for Elon+// round-5 must-fix: when the different-head task holding the slot is NEWER than+// the losing comment (and the comment is not in its planned ids), completion+// reconcile's `created_at > since` window never matches it — so the resolver must+// NOT fabricate a deferred off "head differs". It returns a truthful non-success+// (internal_error) instead, never a success-shaped outcome that drops the comment.+func TestCommentEnqueueRaceNewerDifferentHeadNotDeferred(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-newer-head", 999317)+ agentUUID := util.MustParseUUID(agentID)++ // Link a PR at head B so the request resolves head B.+ var prID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO github_pull_request (workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, pr_created_at, pr_updated_at, head_sha)+ VALUES ($1, 1, 'multica-ai', 'multica', 999317, 'review PR', 'open', 'https://example.test/pr', now(), now(), $2)+ RETURNING id+ `, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {+ t.Fatalf("seed PR: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })+ if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {+ t.Fatalf("link PR: %v", err)+ }++ 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)+ }++ // Losing comment C persisted first (older); a head-A winner is created LATER+ // (newer than C), so reconcile's created_at window can never replay C.+ loserCommentID := insertDupRaceComment(t, issueID, "older losing comment", "5 minutes")+ winnerCommentID := insertDupRaceComment(t, issueID, "head A trigger", "4 minutes")+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'queued', 0, now() - interval '1 minute', jsonb_build_object('head_sha', $5::text))+ `, agentID, runtimeID, issueID, winnerCommentID, dupRaceHeadA); err != nil {+ t.Fatalf("insert newer head-A winner: %v", err)+ }++ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}+ results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})++ // Must NOT be a fabricated deferred — the newer head-A task cannot cover C.+ res := results[agentID]+ if res.status == DispatchDeferred || res.status == DispatchCoalesced || res.status == DispatchQueued {+ t.Fatalf("newer different-head: got success-shaped %q/%q, want a truthful non-success (not deferred/coalesced/queued)", res.status, res.reason)+ }+ if res.status != DispatchBlocked || res.reason != ReasonInternalError {+ t.Fatalf("newer different-head: got %q/%q, want blocked/internal_error", res.status, res.reason)+ }+ // The head-A winner was not mutated to fake coverage.+ var folded bool+ if err := testPool.QueryRow(ctx, `+ SELECT $2::uuid = ANY(coalesced_comment_ids) FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $3 AND context->>'head_sha' = $4+ `, issueID, loserCommentID, agentID, dupRaceHeadA).Scan(&folded); err != nil {+ t.Fatalf("read winner coalesced: %v", err)+ }+ if folded {+ t.Fatal("losing comment was wrongly attached to the newer different-head task")+ }+}++// TestCommentEnqueueRaceMixedCoveringAndNewerNotDeferred covers Elon rounds 6+9:+// an OLDER different-head task and a NEWER one can coexist (running sits outside+// the unique index). At decision time nothing has attached the comment, so the+// resolver must return a truthful non-success rather than a fabricated deferred+// (round 6). Draining the chain then pins the boundary of the hand-off: the newer+// blocker is at a DIFFERENT head, so the obligation is NOT folded into it — that+// would let an old-head run consume a current-head request (TEN-356, round 9).+// This is the one documented best-effort shape; correctness rests on the fact+// that nothing ever promised coverage here.+func TestCommentEnqueueRaceMixedCoveringAndNewerNotDeferred(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-mixed", 999318)+ agentUUID := util.MustParseUUID(agentID)++ // PR at head B so the request resolves head B; both tasks are at head A.+ var prID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO github_pull_request (workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, pr_created_at, pr_updated_at, head_sha)+ VALUES ($1, 1, 'multica-ai', 'multica', 999318, 'review PR', 'open', 'https://example.test/pr', now(), now(), $2)+ RETURNING id+ `, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {+ t.Fatalf("seed PR: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })+ if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {+ t.Fatalf("link PR: %v", err)+ }++ 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)+ }++ // T0: A (head-A) running, OLDER than the comment. T1: comment C. T2: B+ // (head-A) queued, NEWER than C — it occupies the unique slot.+ aTrigger := insertDupRaceComment(t, issueID, "A trigger", "11 minutes")+ var taskA string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '9 minutes', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, aTrigger, dupRaceHeadA).Scan(&taskA); err != nil {+ t.Fatalf("insert running task A: %v", err)+ }+ loserCommentID := insertDupRaceComment(t, issueID, "losing comment C", "5 minutes")+ bTrigger := insertDupRaceComment(t, issueID, "B trigger", "2 minutes")+ var taskB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'queued', 0, now() - interval '1 minute', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, bTrigger, dupRaceHeadA).Scan(&taskB); err != nil {+ t.Fatalf("insert queued task B: %v", err)+ }++ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}+ results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})++ // Even though a covering (older) task exists, the newer one forbids deferral.+ res := results[agentID]+ if res.status == DispatchDeferred || res.status == DispatchCoalesced || res.status == DispatchQueued {+ t.Fatalf("mixed covering+newer: got success-shaped %q/%q, want a truthful non-success", res.status, res.reason)+ }+ if res.status != DispatchBlocked || res.reason != ReasonInternalError {+ t.Fatalf("mixed covering+newer: got %q/%q, want blocked/internal_error", res.status, res.reason)+ }++ // Draining the chain: A completes and its replay of C collides with the still-+ // queued newer B, which is at a DIFFERENT head. The hand-off correctly declines+ // to fold C there (that would let an old-head run consume it — TEN-356), so this+ // is the one documented best-effort shape: C stays uncovered and the failure is+ // logged at error. What matters for correctness is that the initial call never+ // PROMISED coverage — it returned a non-success above.+ if w := completeTaskViaHandler(t, taskA, "done"); w.Code != 200 {+ t.Fatalf("complete A: %d: %s", w.Code, w.Body.String())+ }+ if commentCovered(t, issueID, agentID, loserCommentID, "queued") {+ t.Fatal("C was folded into the different-head queued blocker (TEN-356 violation)")+ }+}++// commentCoveredByAnyActiveTask reports whether ANY active task for (issue, agent)+// has the comment as its trigger or in its planned (coalesced) batch.+func commentCoveredByAnyActiveTask(t *testing.T, issueID, agentID, commentID string) bool {+ t.Helper()+ var ok bool+ if err := testPool.QueryRow(context.Background(), `+ SELECT EXISTS (+ SELECT 1 FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued','dispatched','running','waiting_local_directory')+ AND ($3::uuid = trigger_comment_id OR $3::uuid = ANY(coalesced_comment_ids))+ )+ `, issueID, agentID, commentID).Scan(&ok); err != nil {+ t.Fatalf("check coverage: %v", err)+ }+ return ok+}++// coveringTaskHead returns the head_sha of the active task that covers the comment+// (empty when none does), so a test can assert WHICH head finally covers it.+func coveringTaskHead(t *testing.T, issueID, agentID, commentID string) string {+ t.Helper()+ var head string+ if err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(context->>'head_sha','')+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued','dispatched','running','waiting_local_directory')+ AND ($3::uuid = trigger_comment_id OR $3::uuid = ANY(coalesced_comment_ids))+ ORDER BY created_at DESC LIMIT 1+ `, issueID, agentID, commentID).Scan(&head); err != nil {+ t.Fatalf("read covering task head: %v", err)+ }+ return head+}++// seedDupRacePR links a PR at head B so the reviewed head resolves to head B.+func seedDupRacePR(t *testing.T, issueID string, prNumber int) {+ t.Helper()+ ctx := context.Background()+ var prID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO github_pull_request (workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, pr_created_at, pr_updated_at, head_sha)+ VALUES ($1, 1, 'multica-ai', 'multica', $2, 'review PR', 'open', 'https://example.test/pr', now(), now(), $3)+ RETURNING id+ `, testWorkspaceID, prNumber, dupRaceHeadB).Scan(&prID); err != nil {+ t.Fatalf("seed PR: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })+ if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {+ t.Fatalf("link PR: %v", err)+ }+}++// TestReconcileBlockedReplayPropagatesToClaimedBlocker is the regression for Elon+// round-8 must-fix 2 (planned-registration path): a planned-id obligation must not+// be consumed once. C is registered as a planned input on running task A; before A+// completes, a NEWER different-head task B is claimed and holds the unique slot. A's+// completion replay of C is therefore blocked — and must be HANDED to B rather than+// discarded, so completing B finally covers C.+func TestReconcileBlockedReplayPropagatesToClaimedBlocker(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-propagate-claimed", 999319)+ seedDupRacePR(t, issueID, 999319)++ aTrigger := insertDupRaceComment(t, issueID, "A trigger", "11 minutes")+ loserCommentID := insertDupRaceComment(t, issueID, "comment C needing coverage", "8 minutes")+ bTrigger := insertDupRaceComment(t, issueID, "B trigger", "6 minutes")++ // A: running (outside the unique index), head A, with C already registered as a+ // planned-but-NOT-delivered input — the exact state the lost-race path leaves.+ var taskA string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, coalesced_comment_ids, delivered_comment_ids, status, priority, created_at, started_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$5::uuid], ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '9 minutes', jsonb_build_object('head_sha', $6::text))+ RETURNING id+ `, agentID, runtimeID, issueID, aTrigger, loserCommentID, dupRaceHeadA).Scan(&taskA); err != nil {+ t.Fatalf("insert running task A: %v", err)+ }+ // B: a NEWER different-head task, already claimed (dispatched) — it holds the slot+ // and its own reconcile can never see the older C.+ var taskB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'dispatched', 0, now() - interval '5 minutes', now() - interval '4 minutes', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, bTrigger, dupRaceHeadA).Scan(&taskB); err != nil {+ t.Fatalf("insert dispatched blocker B: %v", err)+ }++ // A completes: its replay of C collides with B and must be handed to B.+ if w := completeTaskViaHandler(t, taskA, "done"); w.Code != 200 {+ t.Fatalf("complete A: %d: %s", w.Code, w.Body.String())+ }+ var plannedOnB, deliveredOnB bool+ if err := testPool.QueryRow(ctx, `+ SELECT $2::uuid = ANY(coalesced_comment_ids), $2::uuid = ANY(delivered_comment_ids)+ FROM agent_task_queue WHERE id = $1+ `, taskB, loserCommentID).Scan(&plannedOnB, &deliveredOnB); err != nil {+ t.Fatalf("read blocker B: %v", err)+ }+ if !plannedOnB {+ t.Fatal("blocked replay was discarded — C was not handed to the blocker, so it is lost")+ }+ if deliveredOnB {+ t.Fatal("C must not be faked as delivered on the already-claimed blocker")+ }++ // B completes: C is in its planned ids, so it is replayed and finally covered.+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskB); err != nil {+ t.Fatalf("advance B to running: %v", err)+ }+ if w := completeTaskViaHandler(t, taskB, "done"); w.Code != 200 {+ t.Fatalf("complete B: %d: %s", w.Code, w.Body.String())+ }+ if !commentCoveredByAnyActiveTask(t, issueID, agentID, loserCommentID) {+ t.Fatal("after the blocker chain drained, no task covers C — the deferral was not durable")+ }+ // The hand-off never let an old-head run consume C: the follow-up that finally+ // covers it is stamped for the CURRENT head (TEN-356).+ if head := coveringTaskHead(t, issueID, agentID, loserCommentID); head != dupRaceHeadB {+ t.Fatalf("covering task head_sha = %q, want the current head %q", head, dupRaceHeadB)+ }+}++// TestReconcileBlockedReplayPropagatesToQueuedBlocker is the regression for Elon+// round-8 must-fix 1 (AlreadyPending path): C arrives while A is running, so A's+// reconcile finds it by timestamp — but a NEWER task B is QUEUED when A completes,+// blocking the replay. When B is at the CURRENT head the obligation is handed to it+// through the ATOMIC merge (never a bare append), so C ends up covered at that head.+func TestReconcileBlockedReplayPropagatesToQueuedBlocker(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-propagate-queued", 999320)+ seedDupRacePR(t, issueID, 999320)++ aTrigger := insertDupRaceComment(t, issueID, "A trigger", "11 minutes")+ // C lands while A is running (newer than A) and is NOT in A's arrays — the+ // AlreadyPending shape, covered by reconcile's timestamp window alone.+ loserCommentID := insertDupRaceComment(t, issueID, "comment C posted during the run", "5 minutes")+ bTrigger := insertDupRaceComment(t, issueID, "B trigger", "2 minutes")++ var taskA string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '9 minutes', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, aTrigger, dupRaceHeadA).Scan(&taskA); err != nil {+ t.Fatalf("insert running task A: %v", err)+ }+ // B: NEWER than C, QUEUED, and at the CURRENT head — it occupies the unique slot+ // and its own reconcile can never see the older C.+ var taskB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, context)+ VALUES ($1, $2, $3, $4, 'queued', 0, now() - interval '1 minute', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, bTrigger, dupRaceHeadB).Scan(&taskB); err != nil {+ t.Fatalf("insert queued blocker B: %v", err)+ }++ if w := completeTaskViaHandler(t, taskA, "done"); w.Code != 200 {+ t.Fatalf("complete A: %d: %s", w.Code, w.Body.String())+ }+ // The obligation must have been folded into the queued blocker.+ if !commentCoveredByAnyActiveTask(t, issueID, agentID, loserCommentID) {+ t.Fatal("blocked replay was discarded — C is covered by no active task, so it is lost")+ }+ // The fold went through the ATOMIC merge, so B still covers its own trigger too,+ // and the covering run is at the current head.+ if !commentCoveredByAnyActiveTask(t, issueID, agentID, bTrigger) {+ t.Fatal("the blocker's own trigger comment lost coverage during the hand-off")+ }+ if head := coveringTaskHead(t, issueID, agentID, loserCommentID); head != dupRaceHeadB {+ t.Fatalf("covering task head_sha = %q, want the current head %q", head, dupRaceHeadB)+ }+}++// TestReconcileBlockedReplayNeverFoldsIntoDifferentHeadQueuedBlocker is the+// regression for Elon round-9 must-fix 2: the hand-off must NOT merge across heads.+// A different-head QUEUED blocker would make the comment that run's trigger and mark+// it delivered at claim time, so an old-head run would consume a new-head request and+// no new-head follow-up would ever exist (TEN-356). The hand-off must decline instead+// — leaving the blocker untouched — rather than "cover" the comment incorrectly.+func TestReconcileBlockedReplayNeverFoldsIntoDifferentHeadQueuedBlocker(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ agentID, issueID, runtimeID := dupRaceFixture(t, "dup-race-propagate-crosshead", 999321)+ seedDupRacePR(t, issueID, 999321) // current head = head B++ aTrigger := insertDupRaceComment(t, issueID, "A trigger", "11 minutes")+ loserCommentID := insertDupRaceComment(t, issueID, "comment C posted during the run", "5 minutes")+ bTrigger := insertDupRaceComment(t, issueID, "B trigger", "2 minutes")++ var taskA string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at, context)+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '9 minutes', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, aTrigger, dupRaceHeadA).Scan(&taskA); err != nil {+ t.Fatalf("insert running task A: %v", err)+ }+ // B: QUEUED at the OLD head — folding C into it would hand a current-head+ // request to an old-head run.+ var taskB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, context)+ VALUES ($1, $2, $3, $4, 'queued', 0, now() - interval '1 minute', jsonb_build_object('head_sha', $5::text))+ RETURNING id+ `, agentID, runtimeID, issueID, bTrigger, dupRaceHeadA).Scan(&taskB); err != nil {+ t.Fatalf("insert queued cross-head blocker B: %v", err)+ }++ if w := completeTaskViaHandler(t, taskA, "done"); w.Code != 200 {+ t.Fatalf("complete A: %d: %s", w.Code, w.Body.String())+ }++ // C must NOT have been consumed by the old-head run, and B's own trigger and+ // head must be untouched.+ var folded bool+ var bHead string+ if err := testPool.QueryRow(ctx, `+ SELECT $2::uuid = trigger_comment_id OR $2::uuid = ANY(coalesced_comment_ids), COALESCE(context->>'head_sha','')+ FROM agent_task_queue WHERE id = $1+ `, taskB, loserCommentID).Scan(&folded, &bHead); err != nil {+ t.Fatalf("read cross-head blocker: %v", err)+ }+ if folded {+ t.Fatal("C was folded into a DIFFERENT-head queued run — an old-head run would consume a current-head request (TEN-356)")+ }+ if bHead != dupRaceHeadA {+ t.Fatalf("blocker head_sha = %q, want unchanged %q", bHead, dupRaceHeadA)+ }+}diff --git a/server/internal/handler/comment_merge_failclosed_test.go b/server/internal/handler/comment_merge_failclosed_test.goindex e0ac4d4c47..acc9780546 100644--- a/server/internal/handler/comment_merge_failclosed_test.go+++ b/server/internal/handler/comment_merge_failclosed_test.go@@ -4,6 +4,7 @@ import ("context""testing"+ "github.com/jackc/pgx/v5/pgtype"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -95,7 +96,7 @@ func TestMergeCommentIntoPendingTask_FailClosedKeepsOriginalSnapshot(t *testing.}before := countTasks()- if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB)); result != commentMergeAttributionBlocked {+ if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB), pgtype.Text{}); result != commentMergeAttributionBlocked {t.Fatalf("fail-closed merge result = %d, want commentMergeAttributionBlocked (refused, non-success)", result)}if after := countTasks(); after != before {@@ -121,7 +122,7 @@ func TestMergeCommentIntoPendingTask_FailClosedKeepsOriginalSnapshot(t *testing.if _, err := testPool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = false WHERE id = $1`, testWorkspaceID); err != nil {t.Fatalf("clear fail-closed: %v", err)}- if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB)); result != commentMergeSucceeded {+ if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB), pgtype.Text{}); result != commentMergeSucceeded {t.Fatalf("fail-open merge result = %d, want commentMergeSucceeded", result)}tc2, orig2, _, src2 := readSnapshot()diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 0e3183d01c..4641678709 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3169,7 +3169,28 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag// The first qualifying comment enqueues the follow-up task; later ones// find it AlreadyPending and merge in, so all undelivered comments end// up covered by a single bounded run.- h.enqueueCommentAgentTriggers(ctx, issue, c.ID, scoped)+ //+ // A BLOCKED replay must not be discarded (#5914, Elon round 8): the slot+ // can be held by a task that will never see this comment (it predates that+ // task and is not in its planned ids), so dropping the failure here is+ // exactly how a promised follow-up is lost. Hand the obligation to that+ // blocker instead, keeping it alive until some run provably covers it.+ if res := h.enqueueCommentAgentTriggers(ctx, issue, c.ID, scoped)[agentID]; res.status == DispatchBlocked {+ headSha := h.TaskService.ResolveIssueReviewSHAParam(ctx, task.IssueID)+ if h.propagateUncoveredCommentObligation(ctx, issue, scoped[0], c.ID, headSha) {+ slog.Info("reconcile comments on completion: replay blocked, obligation handed to the active task",+ "issue_id", uuidToString(task.IssueID), "agent_id", agentID, "comment_id", uuidToString(c.ID))+ } else {+ // The slot is held by a DIFFERENT-head queued task: it can neither+ // cover this comment nor accept it (merging would let an old-head+ // run consume a new-head request — TEN-356). Today's schema has no+ // safe place to park the obligation, so surface it loudly rather+ // than let it disappear quietly.+ slog.Error("reconcile comments on completion: replay blocked and obligation could not be handed off; comment needs a durable obligation record",+ "issue_id", uuidToString(task.IssueID), "agent_id", agentID, "comment_id", uuidToString(c.ID),+ "reason", res.reason)+ }+ }scheduled++}if scheduled > 0 {diff --git a/server/internal/service/duplicate_pending_task_test.go b/server/internal/service/duplicate_pending_task_test.gonew file mode 100644index 0000000000..779a1d9450--- /dev/null+++ b/server/internal/service/duplicate_pending_task_test.go@@ -0,0 +1,92 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestIsDuplicatePendingTaskErr locks the driver-code detection (#5914): only a+// 23505 on the idx_one_pending_task_per_issue_agent index is a benign+// duplicate-pending-task race. A different unique constraint (e.g. the agent+// name) or a plain error must not be mistaken for it, and the wrapped sentinel+// must remain detectable via errors.Is by callers. This runs without a database.+func TestIsDuplicatePendingTaskErr(t *testing.T) {+ dup := &pgconn.PgError{Code: "23505", ConstraintName: "idx_one_pending_task_per_issue_agent"}+ if !isDuplicatePendingTaskErr(dup) {+ t.Fatal("expected the pending-task unique-index violation to be recognized")+ }+ if isDuplicatePendingTaskErr(&pgconn.PgError{Code: "23505", ConstraintName: "agent_workspace_name_unique"}) {+ t.Fatal("a different unique constraint must not be treated as a duplicate pending task")+ }+ if isDuplicatePendingTaskErr(errors.New("boom")) {+ t.Fatal("a non-pg error must not be treated as a duplicate pending task")+ }++ wrapped := fmt.Errorf("%w: %v", ErrDuplicatePendingTask, dup)+ if !errors.Is(wrapped, ErrDuplicatePendingTask) {+ t.Fatal("the wrapped sentinel must stay detectable via errors.Is")+ }+}++// TestEnqueueTaskForMentionCoalescesDuplicatePendingTask is the service-level+// regression for #5914: a second mention enqueue for the same (issue, agent)+// that loses the race to an existing pending task must return the typed+// ErrDuplicatePendingTask sentinel — not a raw create-task error carrying the+// Postgres constraint name — and must leave exactly one pending task behind.+func TestEnqueueTaskForMentionCoalescesDuplicatePendingTask(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 mention creates the pending task.+ if _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{}); err != nil {+ t.Fatalf("first EnqueueTaskForMention: %v", err)+ }++ // Second mention for the same (issue, agent) collides on the unique index.+ _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{})+ if !errors.Is(err, ErrDuplicatePendingTask) {+ t.Fatalf("second EnqueueTaskForMention: 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 df1ffdecff..9483b79db1 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -13,6 +13,7 @@ import ("unicode/utf8""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/attribution"@@ -554,6 +555,24 @@ func triggerOwnerAttribution(ctx context.Context, q *db.Queries, triggerID, work// run never starts.var ErrAttributionFailClosed = errors.New("attribution: no precise accountable human and enqueue refused (fail-closed policy, policy read failed, or no agent owner)")+// ErrDuplicatePendingTask means a fresh enqueue lost the race to a concurrent+// one: a queued/dispatched task for the same (issue, agent) already exists, so+// the idx_one_pending_task_per_issue_agent unique index rejected the insert+// (#5914). This is a benign outcome — a sibling run already covers this target+// — not a server fault. Enqueue paths return it so callers can report a+// success-shaped coalesced outcome / structured 409 instead of surfacing the+// raw Postgres constraint as a 500. It is returned BARE (the raw driver text,+// including the index name, is logged once at debug and never wrapped in) so no+// upper-layer log or response can leak the constraint name (#5914, Elon review).+var ErrDuplicatePendingTask = errors.New("a pending task for this issue and agent already exists")++// isDuplicatePendingTaskErr reports whether err is the unique-index violation on+// idx_one_pending_task_per_issue_agent (a concurrent enqueue won the race).+func isDuplicatePendingTaskErr(err error) bool {+ var pgErr *pgconn.PgError+ return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "idx_one_pending_task_per_issue_agent"+}+// applyAttributionFallback applies the workspace's degraded-attribution policy to a// resolved attribution whose source came back unattributed (no precise human). A// PRECISE attribution passes through untouched (no policy read at all). For an@@ -1154,6 +1173,15 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issHeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),})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).+ if isDuplicatePendingTaskErr(err) {+ slog.Debug("mention task enqueue coalesced: pending task already exists", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))+ return db.AgentTaskQueue{}, ErrDuplicatePendingTask+ }slog.Error("mention task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)return db.AgentTaskQueue{}, fmt.Errorf("create task: %w", err)}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 443b9be2ad..561455db9e 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4463,6 +4463,15 @@ WHERE id = (WHERE t.issue_id = $12AND t.agent_id = $13AND t.status = 'queued'+ -- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical+ -- unique index is only (issue_id, agent_id), so an insert-race loser can+ -- collide with a pending task stamped for a DIFFERENT head_sha; merging+ -- into it would give a new-HEAD comment old-HEAD review coverage. Empty/+ -- absent head_sha (no linked PR) matches any task, preserving coalescing.+ AND (+ COALESCE($14::text, '') = ''+ OR t.context->>'head_sha' = $14::text+ )ORDER BY t.created_at DESCLIMIT 1)@@ -4483,6 +4492,7 @@ type MergeCommentIntoPendingTaskParams struct {NewRuntimeConnectedApps []byte `json:"new_runtime_connected_apps"`IssueID pgtype.UUID `json:"issue_id"`AgentID pgtype.UUID `json:"agent_id"`+ HeadSha pgtype.Text `json:"head_sha"`}type MergeCommentIntoPendingTaskRow struct {@@ -4548,6 +4558,7 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommarg.NewRuntimeConnectedApps,arg.IssueID,arg.AgentID,+ arg.HeadSha,)var i MergeCommentIntoPendingTaskRowerr := row.Scan(&i.ID, &i.CoalescedCommentIds)@@ -5111,6 +5122,75 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUIreturn i, err}+const registerPlannedCommentForActiveTask = `-- name: RegisterPlannedCommentForActiveTask :one+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, $1::uuid)) AS e+ WHERE e IS NOT NULL+ )+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = $2+ AND t.agent_id = $3+ AND t.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND (+ COALESCE($4::text, '') = ''+ OR t.context->>'head_sha' = $4::text+ )+ ORDER BY t.created_at DESC+ LIMIT 1+)+RETURNING id, coalesced_comment_ids+`++type RegisterPlannedCommentForActiveTaskParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ HeadSha pgtype.Text `json:"head_sha"`+}++type RegisterPlannedCommentForActiveTaskRow struct {+ ID pgtype.UUID `json:"id"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`+}++// #5914: durably register a comment that lost an enqueue race as a PLANNED+// (undelivered) input on the same-(issue, agent) ACTIVE task whose queued row+// MergeCommentIntoPendingTask could no longer target (it was claimed →+// dispatched/running). The losing comment can predate that task's created_at,+// so completion reconciliation's `created_at > since` window cannot see it;+// appending it to coalesced_comment_ids (the planned set) WITHOUT touching+// delivered_comment_ids makes reconcileCommentsOnCompletion replay it as a+// single bounded follow-up (planned-but-not-delivered ⇒ follow-up).+//+// Head-scoped (TEN-356): only a task stamped with the SAME head_sha is a target,+// so a new-HEAD comment is never attached to an old-HEAD run. Returns+// pgx.ErrNoRows when no same-head active task exists (different HEAD, or the task+// just terminated) so the caller falls back to the active-task decision.+//+// 'queued' is DELIBERATELY EXCLUDED (#5914, Elon round 3): a not-yet-claimed+// task has no claim receipt, so a comment merged into it WILL be recorded as+// delivered at claim time and never earns a completion follow-up under its own+// attribution. A queued target must therefore go through the ATOMIC+// MergeCommentIntoPendingTask (which re-stamps trigger/originator/accountable/+// overlay), never a bare planned append — otherwise a second member's comment+// could execute under the first member's identity/connected-apps (MUL-4302).+// Only claim-receipt statuses (already-built delivered set) are safe planned-id+// targets.+func (q *Queries) RegisterPlannedCommentForActiveTask(ctx context.Context, arg RegisterPlannedCommentForActiveTaskParams) (RegisterPlannedCommentForActiveTaskRow, error) {+ row := q.db.QueryRow(ctx, registerPlannedCommentForActiveTask,+ arg.CommentID,+ arg.IssueID,+ arg.AgentID,+ arg.HeadSha,+ )+ var i RegisterPlannedCommentForActiveTaskRow+ err := row.Scan(&i.ID, &i.CoalescedCommentIds)+ return i, err+}+const requeueAgentTaskAfterClaimFailure = `-- name: RequeueAgentTaskAfterClaimFailure :oneUPDATE agent_task_queueSET status = 'queued',diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 79c30184b5..48f70e7004 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1122,6 +1122,59 @@ WHERE id = (WHERE t.issue_id = @issue_idAND t.agent_id = @agent_idAND t.status = 'queued'+ -- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical+ -- unique index is only (issue_id, agent_id), so an insert-race loser can+ -- collide with a pending task stamped for a DIFFERENT head_sha; merging+ -- into it would give a new-HEAD comment old-HEAD review coverage. Empty/+ -- absent head_sha (no linked PR) matches any task, preserving coalescing.+ AND (+ COALESCE(sqlc.narg('head_sha')::text, '') = ''+ OR t.context->>'head_sha' = sqlc.narg('head_sha')::text+ )+ ORDER BY t.created_at DESC+ LIMIT 1+)+RETURNING id, coalesced_comment_ids;++-- name: RegisterPlannedCommentForActiveTask :one+-- #5914: durably register a comment that lost an enqueue race as a PLANNED+-- (undelivered) input on the same-(issue, agent) ACTIVE task whose queued row+-- MergeCommentIntoPendingTask could no longer target (it was claimed →+-- dispatched/running). The losing comment can predate that task's created_at,+-- so completion reconciliation's `created_at > since` window cannot see it;+-- appending it to coalesced_comment_ids (the planned set) WITHOUT touching+-- delivered_comment_ids makes reconcileCommentsOnCompletion replay it as a+-- single bounded follow-up (planned-but-not-delivered ⇒ follow-up).+--+-- Head-scoped (TEN-356): only a task stamped with the SAME head_sha is a target,+-- so a new-HEAD comment is never attached to an old-HEAD run. Returns+-- pgx.ErrNoRows when no same-head active task exists (different HEAD, or the task+-- just terminated) so the caller falls back to the active-task decision.+--+-- 'queued' is DELIBERATELY EXCLUDED (#5914, Elon round 3): a not-yet-claimed+-- task has no claim receipt, so a comment merged into it WILL be recorded as+-- delivered at claim time and never earns a completion follow-up under its own+-- attribution. A queued target must therefore go through the ATOMIC+-- MergeCommentIntoPendingTask (which re-stamps trigger/originator/accountable/+-- overlay), never a bare planned append — otherwise a second member's comment+-- could execute under the first member's identity/connected-apps (MUL-4302).+-- Only claim-receipt statuses (already-built delivered set) are safe planned-id+-- targets.+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, @comment_id::uuid)) AS e+ WHERE e IS NOT NULL+ )+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = @issue_id+ AND t.agent_id = @agent_id+ AND t.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND (+ COALESCE(sqlc.narg('head_sha')::text, '') = ''+ OR t.context->>'head_sha' = sqlc.narg('head_sha')::text+ )ORDER BY t.created_at DESCLIMIT 1)