Skip to content

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

Go

fix(comments): make comment creation idempotent so a lost response is safe to resend (#11244)

Bohan Jiangac81a2733262
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdx
index 80cff4f8e5..7e35352cd1 100644
--- a/apps/docs/content/docs/cli.fr.mdx
+++ b/apps/docs/content/docs/cli.fr.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+Si `issue comment add` expire ou perd sa connexion, le commentaire est peut-être déjà enregistré. Dans une exécution d'agent, relancer la même commande est sans risque : la CLI envoie une clé d'idempotence dérivée de l'exécution, du ticket, du commentaire parent, du contenu et des pièces jointes, et le serveur renvoie le commentaire enregistré au lieu de le publier une seconde fois. Ailleurs, passez la même `--idempotency-key <key>` à chaque tentative pour obtenir la même protection. Les serveurs plus anciens ignorent la clé.
+
Si une tâche ouverte portant le même titre (sans tenir compte de la casse ni des espaces en trop) existe déjà sous le même projet et le même parent, `issue create` refuse et indique cette tâche. Pour en créer une autre malgré tout, ajoutez `--allow-duplicate`. Pour marquer une tâche comme doublon d'une autre, utilisez `multica issue status MUL-124 cancelled --duplicate-of MUL-123`.
Pour livrer plusieurs PR successives, utilisez `issue create --title "..." --pr-auto-complete off` ou `issue update <id> --pr-auto-complete off` pour conserver le statut de cette tâche après fusion. `--pr-auto-complete on` rétablit la règle de l'espace de travail au prochain événement PR. `issue pull-requests <id>` affiche le réglage de la tâche, celui de l'espace de travail, le statut cible et la décision, même sans PR liée. Les serveurs compatibles enregistrent le réglage dans la transaction de création ; les anciens reçoivent un PUT supplémentaire. En cas d'échec, le CLI indique l'ID créé et la commande update à réessayer : ne répétez pas create.
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdx
index 2279facf46..88d5ef93d3 100644
--- a/apps/docs/content/docs/cli.ja.mdx
+++ b/apps/docs/content/docs/cli.ja.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+`issue comment add` がタイムアウトしたり接続が切れたりした場合でも、コメントはすでに保存されている可能性があります。エージェントの実行中であれば、同じコマンドをそのまま再実行して問題ありません。CLI は実行、issue、親コメント、内容、添付ファイルから冪等キーを生成し、サーバーは保存済みのコメントを返して二重に投稿しません。それ以外の場面では、毎回同じ `--idempotency-key <key>` を渡すと同じ保護が得られます。古いサーバーはこのキーを無視します。
+
同じプロジェクト・同じ親タスクの下に、タイトルが同じ(大文字小文字と余分な空白は区別しない)未完了のタスクがすでにあると、`issue create` は作成を拒否してそのタスクを示します。それでも作る場合は `--allow-duplicate` を付けます。あるタスクを別のタスクの重複にするには `multica issue status MUL-124 cancelled --duplicate-of MUL-123` を使います。
複数の PR を順番に作成するタスクでは、`issue create --title "..." --pr-auto-complete off` または `issue update <id> --pr-auto-complete off` で、マージ時も状態を維持できます。`--pr-auto-complete on` はワークスペースのルールを復元し、次の PR イベントから有効になります。`issue pull-requests <id>` は、PR が未関連付けでもタスクとワークスペースの設定、移行先の状態、判定結果を表示します。対応サーバーは作成トランザクション内で設定を保存し、旧サーバーには追加の PUT を送ります。失敗時は作成済み ID と再試行用の update コマンドが表示されるため、create を繰り返さないでください。
diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdx
index ce68ae9466..7c42faca3e 100644
--- a/apps/docs/content/docs/cli.ko.mdx
+++ b/apps/docs/content/docs/cli.ko.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+`issue comment add`가 시간 초과되거나 연결이 끊겨도 댓글은 이미 저장되었을 수 있습니다. 에이전트 실행 안에서는 같은 명령을 그대로 다시 실행해도 안전합니다. CLI가 실행, 이슈, 상위 댓글, 내용, 첨부 파일로 멱등 키를 만들고, 서버는 저장된 댓글을 돌려줄 뿐 다시 게시하지 않습니다. 그 밖의 경우에는 시도할 때마다 같은 `--idempotency-key <key>`를 넘기면 같은 보호를 받습니다. 이전 버전 서버는 이 키를 무시합니다.
+
같은 프로젝트, 같은 상위 태스크 아래에 제목이 같은(대소문자와 여분의 공백은 구분하지 않음) 닫히지 않은 태스크가 이미 있으면 `issue create`는 생성을 거부하고 그 태스크를 알려 줍니다. 그래도 만들려면 `--allow-duplicate`를 붙이세요. 한 태스크를 다른 태스크의 중복으로 표시하려면 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`을 실행합니다.
여러 PR을 순서대로 만드는 태스크는 `issue create --title "..." --pr-auto-complete off` 또는 `issue update <id> --pr-auto-complete off`로 병합 후에도 상태를 유지할 수 있습니다. `--pr-auto-complete on`으로 워크스페이스 규칙을 복원하면 다음 PR 이벤트부터 적용됩니다. `issue pull-requests <id>`는 연결된 PR이 없어도 태스크 설정, 워크스페이스 설정, 대상 상태와 판단 결과를 표시합니다. 지원 서버는 생성 트랜잭션 안에서 설정을 저장하고, 이전 서버에는 추가 PUT을 보냅니다. 실패하면 생성된 태스크 ID와 재시도할 update 명령이 표시되므로 create를 반복하지 마세요.
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index 25afa563ef..8655875350 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+If `issue comment add` times out or loses its connection, the comment may already be saved. Inside an agent run, rerunning the same command is safe: the CLI sends an idempotency key derived from the run, issue, parent, content and attachments, and the server returns the saved comment instead of posting it again. Elsewhere, pass the same `--idempotency-key <key>` on each attempt to get the same protection. Older servers ignore the key.
+
If an open issue with the same title (case-insensitive, extra spaces ignored) already exists under the same project and parent, `issue create` refuses and points to that issue. To create another one anyway, add `--allow-duplicate`. To mark an issue as a duplicate of another, run `multica issue status MUL-124 cancelled --duplicate-of MUL-123`.
For sequential PR delivery, use `issue create --title "..." --pr-auto-complete off` or `issue update <id> --pr-auto-complete off` to keep that issue's status when PRs merge. Use `--pr-auto-complete on` to restore the workspace rule; this takes effect at the next PR event. `issue pull-requests <id>` shows the issue override, workspace setting, target status, and decision state, even with no linked PRs. Supported servers save the creation override atomically; older servers receive a follow-up PUT. If that fails, the CLI reports the created issue ID and an update command to retry, so do not repeat the create.
diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdx
index c8a319f606..644087d53f 100644
--- a/apps/docs/content/docs/cli.zh-Hant.mdx
+++ b/apps/docs/content/docs/cli.zh-Hant.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+如果 `issue comment add` 逾時或連線中斷,留言可能已經儲存。在智慧體執行中,直接重新執行同一條指令是安全的:CLI 會根據執行、任務、父留言、內容和附件產生冪等鍵,伺服器會回傳已儲存的留言,不會再發一則。在其他情境下,每次嘗試都傳同一個 `--idempotency-key <key>` 即可獲得同樣的保護。舊版伺服器會忽略這個鍵。
+
同一專案、同一父任務下已有標題相同(不區分大小寫,忽略多餘空格)且未關閉的任務時,`issue create` 會拒絕建立並給出那個任務。確實要再建一個,加 `--allow-duplicate`;要把一個任務標為另一個的重複,用 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`。
一個任務要依次提交多個 PR 時,用 `issue create --title "..." --pr-auto-complete off` 或 `issue update <id> --pr-auto-complete off`,讓這個任務在 PR 合併後保持原狀態。用 `--pr-auto-complete on` 恢復工作區規則,從下一次 PR 事件起生效。`issue pull-requests <id>` 會顯示任務開關、工作區開關、目標狀態和判斷結果,沒有關聯 PR 時也會顯示。支援該欄位的伺服器會在建立交易內儲存開關;舊伺服器會補呼叫一次 PUT,失敗時 CLI 會提供已建立的任務 ID 和重試用的 update 命令,請勿重複建立。
diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdx
index 3d61969a23..a6f4ce5d37 100644
--- a/apps/docs/content/docs/cli.zh.mdx
+++ b/apps/docs/content/docs/cli.zh.mdx
@@ -141,6 +141,8 @@ multica issue comment add MUL-123 --content-file note.md --steer <task-id>
multica issue comment add MUL-123 --content-file note.md --steer-active
```
+如果 `issue comment add` 超时或连接中断,评论可能已经保存。在智能体运行中,直接重新执行同一条命令是安全的:CLI 会根据运行、任务、父评论、内容和附件生成幂等键,服务器会返回已保存的评论,不会再发一条。在其他场景下,每次尝试都传同一个 `--idempotency-key <key>` 即可获得同样的保护。旧版服务器会忽略这个键。
+
同一项目、同一父任务下已有标题相同(不区分大小写,忽略多余空格)且未关闭的任务时,`issue create` 会拒绝创建并给出那个任务。确实要再建一个,加 `--allow-duplicate`;要把一个任务标为另一个的重复,用 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`。
一个任务要依次提交多个 PR 时,用 `issue create --title "..." --pr-auto-complete off` 或 `issue update <id> --pr-auto-complete off`,让这个任务在 PR 合并后保持原状态。用 `--pr-auto-complete on` 恢复工作区规则,从下一次 PR 事件起生效。`issue pull-requests <id>` 会显示任务开关、工作区开关、目标状态和判断结果,没有关联 PR 时也会显示。支持该字段的服务端会在创建事务内保存开关;旧服务端会补调一次 PUT,失败时 CLI 会给出已创建的任务 ID 和重试用的 update 命令,请勿重复创建。
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b7d3840a6f..cf56340bfc 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "733_comment_idempotency_receipt_key": "uq_comment_idempotency_receipt_key",
+ "734_comment_idempotency_receipt_created": "idx_comment_idempotency_receipt_created",
"729_remote_app_connection_workspace_idx": "uq_remote_app_connection_owner_ws",
"720_remote_app_oauth_client_idx": "uq_remote_app_oauth_client_app_redirect",
"721_remote_app_connection_owner_idx": "uq_remote_app_connection_owner",
diff --git a/server/cmd/multica/attachment_link_rewrite_test.go b/server/cmd/multica/attachment_link_rewrite_test.go
index f5e1335e11..06d580a62b 100644
--- a/server/cmd/multica/attachment_link_rewrite_test.go
+++ b/server/cmd/multica/attachment_link_rewrite_test.go
@@ -219,6 +219,9 @@ func TestRunIssueCommentAddRewritesInlineAttachmentLinks(t *testing.T) {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "att-1", "filename": "a.png", "content_type": "image/png", "markdown_url": markdownURL,
})
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/issue-1/comments/idempotent":
+ // Asked before uploading; an older server has no such route.
+ http.NotFound(w, r)
case r.Method == http.MethodPost && r.URL.Path == "/api/issues/issue-1/comments":
posts++
if err := json.NewDecoder(r.Body).Decode(&posted); err != nil {
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 186e68374b..60fe3d6747 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -2,6 +2,8 @@ package main
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -818,6 +820,7 @@ func init() {
issueCommentAddCmd.Flags().StringArray("attachment", nil, "File path to attach (one literal path per flag; repeat --attachment for multiple files). To show an image at a specific spot, reference the same path in the content (e.g. ![shot](./a.png)); that link is rewritten to the uploaded file before posting. Non-image files, HTML included, show as file cards that open in the viewer; to render a chart inside the comment, put a ```html or ```mermaid block in the content instead")
issueCommentAddCmd.Flags().StringSlice("steer", nil, "Run ID (full UUID or short prefix) whose in-progress turn should receive this comment instead of a follow-up run (repeatable)")
issueCommentAddCmd.Flags().Bool("steer-active", false, "Add this comment to the running turn of every agent on this issue you may steer, and of any other recipient that is running")
+ issueCommentAddCmd.Flags().String("idempotency-key", "", "Key that makes resending this comment safe: a retry with the same key returns the comment already posted instead of posting it again. Inside an agent run the CLI derives one from the run, issue, parent, content and attachments")
issueCommentAddCmd.Flags().String("output", "json", "Output format: table or json")
// issue comment update
@@ -3003,6 +3006,22 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
+ parentID, _ := cmd.Flags().GetString("parent")
+ idempotencyKey, _ := cmd.Flags().GetString("idempotency-key")
+ idempotencyKey = strings.TrimSpace(idempotencyKey)
+ if idempotencyKey == "" && client.TaskID != "" {
+ idempotencyKey = deriveCommentIdempotencyKey(client.TaskID, issueID, parentID, content, steerInputs, steerActive, pending)
+ }
+ if idempotencyKey != "" && len(pending) > 0 {
+ // Ask before uploading: on a rerun whose comment already landed, the
+ // POST would replay and the fresh uploads would be bound to nothing.
+ // Any answer other than a replay (no receipt yet, an older server
+ // without this route, a network error) falls through to the keyed
+ // POST, which is still safe.
+ if saved, ok := lookupIdempotentComment(ctx, client, issueID, parentID, idempotencyKey); ok {
+ return finishIssueCommentAdd(cmd, issueRef.Display, steerTargets, saved, true)
+ }
+ }
var attachmentIDs []string
uploaded := make([]cli.AttachmentResponse, 0, len(pending))
for _, att := range pending {
@@ -3031,19 +3050,40 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
// listing above.
body["steer"] = true
}
- if parentID, _ := cmd.Flags().GetString("parent"); parentID != "" {
+ if parentID != "" {
body["parent_id"] = parentID
}
if len(attachmentIDs) > 0 {
body["attachment_ids"] = attachmentIDs
}
+ var headers map[string]string
+ if idempotencyKey != "" {
+ headers = map[string]string{"Idempotency-Key": idempotencyKey}
+ }
var result map[string]any
- if err := client.PostJSON(ctx, "/api/issues/"+issueID+"/comments", body, &result); err != nil {
+ respHeaders, err := client.PostJSONWithHeaders(ctx, "/api/issues/"+issueID+"/comments", body, headers, &result)
+ if err != nil {
+ if idempotencyKey != "" && commentAddDeliveryUncertain(err) {
+ // Without this line an agent only sees the generic transport
+ // error, checks the thread, and gives up when that check times
+ // out too: the comment is lost although resending was safe
+ // (GH #8221).
+ fmt.Fprintln(os.Stderr, commentAddRerunSafeHint(cmd))
+ }
return fmt.Errorf("add comment: %w", err)
}
+ return finishIssueCommentAdd(cmd, issueRef.Display, steerTargets, result, respHeaders.Get("Idempotent-Replayed") == "true")
+}
- fmt.Fprintf(os.Stderr, "Comment added to issue %s.\n", issueRef.Display)
- reportSteerOutcomes(os.Stderr, steerTargets, result)
+func finishIssueCommentAdd(cmd *cobra.Command, issueDisplay string, steerTargets []steerTarget, result map[string]any, replayed bool) error {
+ if replayed {
+ // An earlier attempt of this command already posted the comment; the
+ // server returned it without posting again or re-triggering anyone.
+ fmt.Fprintf(os.Stderr, "Comment was already posted to issue %s by an earlier attempt; not posted again.\n", issueDisplay)
+ } else {
+ fmt.Fprintf(os.Stderr, "Comment added to issue %s.\n", issueDisplay)
+ reportSteerOutcomes(os.Stderr, steerTargets, result)
+ }
output, _ := cmd.Flags().GetString("output")
if output == "table" {
@@ -3052,6 +3092,80 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
return cli.PrintJSON(os.Stdout, result)
}
+// lookupIdempotentComment reports the comment already saved under key, if the
+// server has one and supports the lookup.
+func lookupIdempotentComment(ctx context.Context, client *cli.APIClient, issueID, parentID, key string) (map[string]any, bool) {
+ path := "/api/issues/" + url.PathEscape(issueID) + "/comments/idempotent"
+ if parentID != "" {
+ path += "?parent_id=" + url.QueryEscape(parentID)
+ }
+ var saved map[string]any
+ headers, err := client.GetJSONWithRequestHeaders(ctx, path, map[string]string{"Idempotency-Key": key}, &saved)
+ if err != nil || headers.Get("Idempotent-Replayed") != "true" {
+ return nil, false
+ }
+ return saved, true
+}
+
+// commentAddDeliveryUncertain reports whether err leaves it unknown whether
+// the server saved the comment: the request may have reached the server and
+// only the response was lost. Failures that happen before the request is sent
+// (DNS, refused connection, TLS) and definite rejections are excluded.
+func commentAddDeliveryUncertain(err error) bool {
+ var networkErr *cli.NetworkError
+ if errors.As(err, &networkErr) {
+ switch networkErr.Kind {
+ case cli.KindNetworkTimeout, cli.KindNetworkStalled, cli.KindNetworkIncompleteResponse, cli.KindNetworkOffline:
+ return true
+ }
+ }
+ var httpErr *cli.HTTPError
+ return errors.As(err, &httpErr) && httpErr.Kind() == cli.KindServerError
+}
+
+func commentAddRerunSafeHint(cmd *cobra.Command) string {
+ rerun := "Rerunning this exact command"
+ if explicit, _ := cmd.Flags().GetString("idempotency-key"); strings.TrimSpace(explicit) != "" {
+ rerun = "Rerunning with the same --idempotency-key"
+ }
+ return "The comment may have been posted. " + rerun + " is safe: the server returns the comment already posted instead of posting it twice (servers that do not support Idempotency-Key ignore it)."
+}
+
+// deriveCommentIdempotencyKey names one logical comment inside one agent run.
+// An agent whose comment add timed out typically reruns the same command; the
+// same run, target and input produce the same key, so the server returns the
+// comment it already saved instead of posting a duplicate (GH #8221).
+//
+// The key is built from the inputs as given, before attachments are uploaded:
+// a rerun uploads the files again and rewrites the body's links to the new
+// uploads, so the request body itself differs between attempts. Attachments
+// count by content, so a rerun with an edited file is a different comment.
+func deriveCommentIdempotencyKey(taskID, issueID, parentID, content string, steer []string, steerActive bool, attachments []pendingAttachment) string {
+ type attachmentInput struct {
+ Path string `json:"path"`
+ SHA256 string `json:"sha256"`
+ }
+ files := make([]attachmentInput, 0, len(attachments))
+ for _, att := range attachments {
+ sum := sha256.Sum256(att.data)
+ files = append(files, attachmentInput{Path: att.path, SHA256: hex.EncodeToString(sum[:])})
+ }
+ steerSorted := append([]string(nil), steer...)
+ sort.Strings(steerSorted)
+ // A structured encoding keeps field boundaries unambiguous.
+ payload, _ := json.Marshal(struct {
+ TaskID string `json:"task_id"`
+ IssueID string `json:"issue_id"`
+ ParentID string `json:"parent_id"`
+ Content string `json:"content"`
+ Steer []string `json:"steer"`
+ SteerActive bool `json:"steer_active"`
+ Attachments []attachmentInput `json:"attachments"`
+ }{taskID, issueID, parentID, content, steerSorted, steerActive, files})
+ sum := sha256.Sum256(payload)
+ return "cli-task-v1:" + hex.EncodeToString(sum[:])
+}
+
func runIssueCommentUpdate(cmd *cobra.Command, args []string) error {
expectedRevision, _ := cmd.Flags().GetInt64("expected-revision")
if !cmd.Flags().Changed("expected-revision") || expectedRevision < 1 {
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 1b6c8d4647..6cb30504dd 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -14,6 +14,7 @@ import (
"slices"
"strconv"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -563,10 +564,217 @@ func newIssueCommentAddTestCmd() *cobra.Command {
cmd.Flags().String("parent", "", "")
cmd.Flags().StringSlice("steer", nil, "")
cmd.Flags().Bool("steer-active", false, "")
+ cmd.Flags().String("idempotency-key", "", "")
cmd.Flags().String("output", "json", "")
return cmd
}
+// GH #8221: an agent that reruns `comment add` after a lost response must send
+// the same Idempotency-Key, so the server returns the saved comment instead of
+// posting a duplicate.
+func TestRunIssueCommentAddIdempotencyKey(t *testing.T) {
+ const (
+ issueID = "11111111-1111-4111-8111-111111111111"
+ taskID = "22222222-2222-4222-8222-222222222222"
+ )
+ t.Chdir(t.TempDir())
+ if err := os.WriteFile("shot.png", []byte("png-v1"), 0o644); err != nil {
+ t.Fatalf("write attachment: %v", err)
+ }
+
+ var keys []string
+ replay := false
+ uploads, lookups := 0, 0
+ var lookupKey, lookupParent string
+ last := func() string {
+ if len(keys) == 0 {
+ return ""
+ }
+ return keys[len(keys)-1]
+ }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+issueID:
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": issueID, "identifier": "TST-1"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":
+ uploads++
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": fmt.Sprintf("attachment-%d", uploads), "url": fmt.Sprintf("https://files.test/%d.png", uploads)})
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+issueID+"/comments/idempotent":
+ lookups++
+ lookupKey, lookupParent = r.Header.Get("Idempotency-Key"), r.URL.Query().Get("parent_id")
+ if !replay {
+ http.Error(w, `{"error":"no comment"}`, http.StatusNotFound)
+ return
+ }
+ w.Header().Set("Idempotent-Replayed", "true")
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "comment-1"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/"+issueID+"/comments":
+ keys = append(keys, r.Header.Get("Idempotency-Key"))
+ if replay {
+ w.Header().Set("Idempotent-Replayed", "true")
+ w.WriteHeader(http.StatusOK)
+ } else {
+ w.WriteHeader(http.StatusCreated)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "comment-1"})
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ run := func(flags map[string]string, attachments ...string) string {
+ t.Helper()
+ cmd := newIssueCommentAddTestCmd()
+ _ = cmd.Flags().Set("output", "table")
+ for name, value := range flags {
+ _ = cmd.Flags().Set(name, value)
+ }
+ for _, path := range attachments {
+ _ = cmd.Flags().Set("attachment", path)
+ }
+ stderr := captureStderr(t)
+ defer stderr.restore()
+ if err := runIssueCommentAdd(cmd, []string{issueID}); err != nil {
+ t.Fatalf("runIssueCommentAdd: %v", err)
+ }
+ return stderr.read()
+ }
+
+ // Outside an agent run, no key unless one is passed.
+ run(map[string]string{"content": "verdict"})
+ if last() != "" {
+ t.Fatalf("key outside an agent run = %q, want none", last())
+ }
+ run(map[string]string{"content": "verdict", "idempotency-key": "my-key"})
+ if last() != "my-key" {
+ t.Fatalf("explicit key = %q, want my-key", last())
+ }
+
+ t.Setenv("MULTICA_TASK_ID", taskID)
+ body := map[string]string{"content": "verdict ![shot](shot.png)", "parent": "33333333-3333-4333-8333-333333333333"}
+ run(body, "shot.png")
+ first := last()
+ if !strings.HasPrefix(first, "cli-task-v1:") {
+ t.Fatalf("derived key = %q", first)
+ }
+ if lookups != 1 || uploads != 1 {
+ t.Fatalf("first attempt lookups = %d, uploads = %d, want 1 and 1", lookups, uploads)
+ }
+ // The rerun finds the saved comment before uploading anything, so it
+ // neither re-uploads the file nor posts again.
+ replay = true
+ posts := len(keys)
+ report := run(body, "shot.png")
+ if lookups != 2 || uploads != 1 || len(keys) != posts {
+ t.Fatalf("rerun lookups = %d, uploads = %d, posts = %d, want 2, 1, %d", lookups, uploads, len(keys), posts)
+ }
+ if lookupKey != first || lookupParent != body["parent"] {
+ t.Fatalf("lookup key %q parent %q, want %q %q", lookupKey, lookupParent, first, body["parent"])
+ }
+ if !strings.Contains(report, "already posted") || strings.Contains(report, "Comment added") {
+ t.Fatalf("replay stderr = %q, want the already-posted notice", report)
+ }
+ // Without attachments there is nothing to save by asking first: the POST
+ // itself replays.
+ run(map[string]string{"content": "no files", "parent": body["parent"]})
+ run(map[string]string{"content": "no files", "parent": body["parent"]})
+ if lookups != 2 || keys[len(keys)-1] != keys[len(keys)-2] {
+ t.Fatalf("attachment-free rerun lookups = %d, keys %q / %q", lookups, keys[len(keys)-2], keys[len(keys)-1])
+ }
+ replay = false
+
+ for name, change := range map[string]func(){
+ "content": func() { run(map[string]string{"content": "other", "parent": body["parent"]}, "shot.png") },
+ "parent": func() { run(map[string]string{"content": body["content"]}, "shot.png") },
+ "attachment": func() { _ = os.WriteFile("shot.png", []byte("png-v2"), 0o644); run(body, "shot.png") },
+ } {
+ change()
+ if last() == first {
+ t.Fatalf("changing %s kept the key %q", name, first)
+ }
+ }
+ t.Setenv("MULTICA_TASK_ID", "44444444-4444-4444-8444-444444444444")
+ _ = os.WriteFile("shot.png", []byte("png-v1"), 0o644)
+ run(body, "shot.png")
+ if last() == first {
+ t.Fatalf("another run reused the key %q", first)
+ }
+}
+
+// When a keyed POST ends without a response, stderr must say that rerunning
+// is safe; otherwise an agent falls back to checking the thread and drops the
+// comment when that check also times out (GH #8221).
+func TestRunIssueCommentAddTimeoutSaysRerunIsSafe(t *testing.T) {
+ const issueID = "11111111-1111-4111-8111-111111111111"
+ const hint = "is safe: the server returns the comment already posted"
+ var responseStatus atomic.Int32
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+issueID:
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": issueID, "identifier": "TST-1"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/"+issueID+"/comments":
+ status := int(responseStatus.Load())
+ _, _ = io.ReadAll(r.Body)
+ if status != 0 {
+ http.Error(w, `{"error":"rejected"}`, status)
+ return
+ }
+ // The server got the comment; the response never arrives.
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ default:
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ defer close(release)
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "300ms")
+
+ run := func(flags map[string]string) string {
+ t.Helper()
+ cmd := newIssueCommentAddTestCmd()
+ _ = cmd.Flags().Set("content", "verdict")
+ for name, value := range flags {
+ _ = cmd.Flags().Set(name, value)
+ }
+ stderr := captureStderr(t)
+ defer stderr.restore()
+ if err := runIssueCommentAdd(cmd, []string{issueID}); err == nil {
+ t.Fatalf("runIssueCommentAdd succeeded, want an error")
+ }
+ return stderr.read()
+ }
+
+ if report := run(nil); strings.Contains(report, hint) {
+ t.Fatalf("unkeyed timeout stderr = %q, want no rerun hint", report)
+ }
+ if report := run(map[string]string{"idempotency-key": "k1"}); !strings.Contains(report, "Rerunning with the same --idempotency-key "+hint) {
+ t.Fatalf("explicit-key timeout stderr = %q", report)
+ }
+ t.Setenv("MULTICA_TASK_ID", "22222222-2222-4222-8222-222222222222")
+ if report := run(nil); !strings.Contains(report, "Rerunning this exact command "+hint) {
+ t.Fatalf("agent timeout stderr = %q", report)
+ }
+ responseStatus.Store(http.StatusBadGateway)
+ if report := run(nil); !strings.Contains(report, hint) {
+ t.Fatalf("5xx stderr = %q, want the rerun hint", report)
+ }
+ responseStatus.Store(http.StatusUnprocessableEntity)
+ if report := run(nil); strings.Contains(report, hint) {
+ t.Fatalf("422 stderr = %q, want no rerun hint", report)
+ }
+}
+
func TestRunIssueCommentAddUploadsAttachmentWithoutIssueID(t *testing.T) {
const issueRef = "MUL-1"
t.Chdir(t.TempDir())
diff --git a/server/cmd/server/comment_idempotency_sweeper.go b/server/cmd/server/comment_idempotency_sweeper.go
new file mode 100644
index 0000000000..c429a8f56a
--- /dev/null
+++ b/server/cmd/server/comment_idempotency_sweeper.go
@@ -0,0 +1,34 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/handler"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const commentIdempotencySweepInterval = time.Hour
+
+// runCommentIdempotencySweeper deletes comment idempotency receipts once they
+// are past the retry window. Every replica may run it; the delete is safe to
+// repeat.
+func runCommentIdempotencySweeper(ctx context.Context, queries *db.Queries) {
+ ticker := time.NewTicker(commentIdempotencySweepInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ sweepCtx, cancel := context.WithTimeout(ctx, time.Minute)
+ if n, err := handler.SweepCommentIdempotencyReceipts(sweepCtx, queries, time.Now()); err != nil {
+ slog.Warn("comment idempotency sweep failed", "error", err)
+ } else if n > 0 {
+ slog.Debug("comment idempotency sweep removed receipts", "count", n)
+ }
+ cancel()
+ }
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 4e28a7ba97..b8d791d417 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -775,6 +775,7 @@ func main() {
go runSourceContextSweeper(sweepCtx, taskSvc)
go inboxTrimmer.Run(sweepCtx)
go runEnvironmentLogSweeper(sweepCtx, queries)
+ go runCommentIdempotencySweeper(sweepCtx, queries)
if h.ConnectedApps != nil {
go h.ConnectedApps.RunSweeper(sweepCtx)
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 425d2c2336..fd9e8eaa98 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2292,6 +2292,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Delete("/", h.DeleteIssue)
r.Post("/comments/trigger-preview", h.PreviewCommentTriggers)
r.Post("/comments", h.CreateComment)
+ r.Get("/comments/idempotent", h.LookupIdempotentComment)
r.Get("/comments", h.ListComments)
r.Get("/timeline", h.ListTimeline)
r.Get("/workflow-handoff", h.PreviewWorkflowHandoff)
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index 0df32cc5fc..8629548955 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -319,6 +319,34 @@ func (c *APIClient) GetJSONWithHeaders(ctx context.Context, path string, out any
return resp.Header, nil
}
+// GetJSONWithRequestHeaders performs a GET request with extra request headers
+// (for example Idempotency-Key) and returns the response headers on success.
+func (c *APIClient) GetJSONWithRequestHeaders(ctx context.Context, path string, headers map[string]string, out any) (http.Header, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+path, nil)
+ if err != nil {
+ return nil, err
+ }
+ c.setHeaders(req)
+ for name, value := range headers {
+ req.Header.Set(name, value)
+ }
+
+ resp, err := c.HTTPClient.Do(req)
+ err = wrapTransport(req, err)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ return nil, newHTTPError(http.MethodGet, path, resp)
+ }
+ if out == nil {
+ return resp.Header, nil
+ }
+ return resp.Header, wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
+}
+
// DeleteJSON performs a DELETE request.
func (c *APIClient) DeleteJSON(ctx context.Context, path string) error {
return c.DeleteJSONResponse(ctx, path, nil)
@@ -390,32 +418,42 @@ func (c *APIClient) DeleteJSONWithBody(ctx context.Context, path string, body an
// PostJSON performs a POST request with a JSON body.
func (c *APIClient) PostJSON(ctx context.Context, path string, body any, out any) error {
+ _, err := c.PostJSONWithHeaders(ctx, path, body, nil, out)
+ return err
+}
+
+// PostJSONWithHeaders performs a POST request with extra request headers (for
+// example Idempotency-Key) and returns the response headers on success.
+func (c *APIClient) PostJSONWithHeaders(ctx context.Context, path string, body any, headers map[string]string, out any) (http.Header, error) {
data, err := json.Marshal(body)
if err != nil {
- return err
+ return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(data))
if err != nil {
- return err
+ return nil, err
}
req.Header.Set("Content-Type", "application/json")
c.setHeaders(req)
+ for name, value := range headers {
+ req.Header.Set(name, value)
+ }
resp, err := c.HTTPClient.Do(req)
err = wrapTransport(req, err)
if err != nil {
- return err
+ return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
- return newHTTPError(http.MethodPost, path, resp)
+ return nil, newHTTPError(http.MethodPost, path, resp)
}
if out == nil {
- return nil
+ return resp.Header, nil
}
- return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
+ return resp.Header, wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// PutJSON performs a PUT request with a JSON body.
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 0bdcc66e8a..dc7f3d3f83 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1847,6 +1847,16 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
}
+ // Idempotency is checked after every guard above, so a replay is only
+ // served to a request that would itself be allowed to post the comment.
+ idem, ok := commentIdempotencyFromRequest(w, r, issue, parentID, req.Type, authorType, authorID)
+ if !ok {
+ return
+ }
+ if h.replayIdempotentComment(w, r, idem) {
+ return
+ }
+
createParams := db.CreateCommentParams{
ID: dbid.NewV7(),
IssueID: issue.ID,
@@ -1886,13 +1896,18 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // The receipt is claimed before anything else is locked, so a
+ // same-key retry waits here holding nothing.
+ err = idem.claim(r.Context(), qtx, createParams.ID)
var unboundIDs []pgtype.UUID
- unboundIDs, err = qtx.LockUnboundAttachmentsForCommentLink(r.Context(), db.LockUnboundAttachmentsForCommentLinkParams{
- WorkspaceID: issue.WorkspaceID,
- AttachmentIds: attachmentIDs,
- UploaderType: authorType,
- UploaderID: parseUUID(authorID),
- })
+ if err == nil {
+ unboundIDs, err = qtx.LockUnboundAttachmentsForCommentLink(r.Context(), db.LockUnboundAttachmentsForCommentLinkParams{
+ WorkspaceID: issue.WorkspaceID,
+ AttachmentIds: attachmentIDs,
+ UploaderType: authorType,
+ UploaderID: parseUUID(authorID),
+ })
+ }
if err == nil {
created, err = qtx.CreateComment(r.Context(), createParams)
}
@@ -1919,9 +1934,20 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
} else {
created, err = wakeupWrite(h, r, func(q *db.Queries) (db.CreateCommentRow, error) {
+ if err := idem.claim(r.Context(), q, createParams.ID); err != nil {
+ return db.CreateCommentRow{}, err
+ }
return q.CreateComment(r.Context(), createParams)
})
}
+ if errors.Is(err, errCommentIdempotencyClaimed) {
+ // A concurrent request with the same key committed first. Its
+ // transaction has finished, so its receipt is readable now.
+ if !h.replayIdempotentComment(w, r, idem) {
+ writeError(w, http.StatusConflict, "a request with this Idempotency-Key is still being processed; retry")
+ }
+ return
+ }
if errors.Is(err, pgx.ErrNoRows) {
// The issue was deleted, possibly while this waited for its row lock.
writeError(w, http.StatusNotFound, "issue not found")
diff --git a/server/internal/handler/comment_idempotency.go b/server/internal/handler/comment_idempotency.go
new file mode 100644
index 0000000000..87559e7492
--- /dev/null
+++ b/server/internal/handler/comment_idempotency.go
@@ -0,0 +1,210 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Comment creation honours an optional Idempotency-Key header (GH #8221).
+//
+// A client whose POST timed out cannot tell whether the comment was saved: the
+// request may have died on the way in, or the server may have committed the
+// comment and lost the response on the way out. Without a key, resending in
+// the second case posts the comment twice and re-fires its mentions. With a
+// key, the server records a receipt in the comment's own transaction, and a
+// retry with the same key from the same author gets the saved comment back
+// (200, Idempotent-Replayed: true) with no new row and no new side effects.
+const (
+ commentIdempotencyKeyHeader = "Idempotency-Key"
+ commentIdempotencyReplayedHeader = "Idempotent-Replayed"
+ commentIdempotencyMaxKeyLength = 255
+ // Receipts only need to outlive a client's retry window. A week covers a
+ // long network outage plus a human rerunning the command the next day.
+ commentIdempotencyRetention = 7 * 24 * time.Hour
+ commentIdempotencySweepBatch = 1000
+)
+
+var errCommentIdempotencyClaimed = errors.New("comment idempotency key already claimed")
+
+type commentIdempotency struct {
+ key db.GetCommentIdempotencyReceiptParams
+ issueID pgtype.UUID
+ fingerprint []byte
+ // issueRevision is the issue's revision as this request read it. A replay
+ // does not write the issue, so it reports this as its issue_revision.
+ issueRevision int64
+}
+
+// commentIdempotencyFromRequest returns nil when the request carries no key.
+// Keys are scoped to the author, so two authors can never collide and a key
+// can never reveal another author's comment.
+//
+// The fingerprint covers where the comment goes (issue, parent, type) but not
+// its content: the CLI uploads attachments again on every rerun and rewrites
+// the body's file links to the new uploads, so the same logical comment can
+// arrive with a different body. A key reused for a different target is still
+// refused.
+func commentIdempotencyFromRequest(w http.ResponseWriter, r *http.Request, issue db.Issue, parentID pgtype.UUID, commentType, authorType, authorID string) (*commentIdempotency, bool) {
+ key := strings.TrimSpace(r.Header.Get(commentIdempotencyKeyHeader))
+ if key == "" {
+ return nil, true
+ }
+ if len(key) > commentIdempotencyMaxKeyLength {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key is too long")
+ return nil, false
+ }
+ payload, _ := json.Marshal(struct {
+ IssueID string `json:"issue_id"`
+ ParentID string `json:"parent_id"`
+ Type string `json:"type"`
+ }{uuidToString(issue.ID), uuidToString(parentID), commentType})
+ sum := sha256.Sum256(payload)
+ return &commentIdempotency{
+ key: db.GetCommentIdempotencyReceiptParams{
+ WorkspaceID: issue.WorkspaceID,
+ ActorType: authorType,
+ ActorID: parseUUID(authorID),
+ IdempotencyKey: key,
+ },
+ issueID: issue.ID,
+ fingerprint: sum[:],
+ issueRevision: issue.Revision,
+ }, true
+}
+
+// claim records the receipt inside the comment's transaction. It must run
+// before the comment insert so a concurrent request with the same key waits
+// on the unique index instead of inserting a second comment.
+func (c *commentIdempotency) claim(ctx context.Context, q *db.Queries, commentID pgtype.UUID) error {
+ if c == nil {
+ return nil
+ }
+ n, err := q.ClaimCommentIdempotencyReceipt(ctx, db.ClaimCommentIdempotencyReceiptParams{
+ WorkspaceID: c.key.WorkspaceID,
+ ActorType: c.key.ActorType,
+ ActorID: c.key.ActorID,
+ IdempotencyKey: c.key.IdempotencyKey,
+ IssueID: c.issueID,
+ CommentID: commentID,
+ RequestFingerprint: c.fingerprint,
+ })
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return errCommentIdempotencyClaimed
+ }
+ return nil
+}
+
+// replayIdempotentComment answers a request whose key already has a receipt.
+// It reports false when no receipt exists and the caller should create the
+// comment. Every other outcome has been written to w.
+func (h *Handler) replayIdempotentComment(w http.ResponseWriter, r *http.Request, c *commentIdempotency) bool {
+ if c == nil {
+ return false
+ }
+ receipt, err := h.Queries.GetCommentIdempotencyReceipt(r.Context(), c.key)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false
+ }
+ if err != nil {
+ slog.Warn("read comment idempotency receipt failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create comment")
+ return true
+ }
+ if !bytes.Equal(receipt.RequestFingerprint, c.fingerprint) || uuidToString(receipt.IssueID) != uuidToString(c.issueID) {
+ writeError(w, http.StatusUnprocessableEntity, "Idempotency-Key was already used for a comment on a different issue, thread or type")
+ return true
+ }
+ comment, err := h.Queries.GetComment(r.Context(), receipt.CommentID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("load idempotent comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", uuidToString(receipt.CommentID))...)
+ writeError(w, http.StatusInternalServerError, "failed to create comment")
+ return true
+ }
+ if errors.Is(err, pgx.ErrNoRows) || comment.DeletedAt.Valid || uuidToString(comment.WorkspaceID) != uuidToString(c.key.WorkspaceID) {
+ // The original request succeeded and the comment was deleted since.
+ // Posting it again would undo that deletion.
+ writeError(w, http.StatusConflict, "the comment created with this Idempotency-Key has been deleted")
+ return true
+ }
+ grouped := h.groupAttachments(r, []pgtype.UUID{comment.ID})
+ resp := commentToResponse(comment, nil, grouped[uuidToString(comment.ID)])
+ resp.IssueRevision = c.issueRevision
+ slog.Info("comment create replayed", append(logger.RequestAttrs(r), "comment_id", uuidToString(comment.ID), "issue_id", uuidToString(comment.IssueID))...)
+ w.Header().Set(commentIdempotencyReplayedHeader, "true")
+ writeJSON(w, http.StatusOK, resp)
+ return true
+}
+
+// LookupIdempotentComment answers GET /api/issues/{id}/comments/idempotent:
+// "did a comment with this Idempotency-Key already land?". It is read-only and
+// returns exactly what a replayed POST would (200 with the saved comment, 422,
+// 409), or 404 when no comment has the key yet.
+//
+// The CLI asks before it uploads attachments for a keyed comment. A rerun
+// would otherwise upload every file again only for the POST to replay, leaving
+// the new uploads bound to nothing.
+func (h *Handler) LookupIdempotentComment(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ if strings.TrimSpace(r.Header.Get(commentIdempotencyKeyHeader)) == "" {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key header is required")
+ return
+ }
+ var parentID pgtype.UUID
+ if raw := r.URL.Query().Get("parent_id"); raw != "" {
+ if parentID, ok = parseUUIDOrBadRequest(w, raw, "parent_id"); !ok {
+ return
+ }
+ }
+ commentType := r.URL.Query().Get("type")
+ if commentType == "" {
+ commentType = "comment"
+ }
+ authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
+ idem, ok := commentIdempotencyFromRequest(w, r, issue, parentID, commentType, authorType, authorID)
+ if !ok {
+ return
+ }
+ if !h.replayIdempotentComment(w, r, idem) {
+ writeError(w, http.StatusNotFound, "no comment has been posted with this Idempotency-Key")
+ }
+}
+
+// SweepCommentIdempotencyReceipts deletes receipts older than the retention
+// window in bounded batches. It returns the number of rows removed.
+func SweepCommentIdempotencyReceipts(ctx context.Context, queries *db.Queries, now time.Time) (int64, error) {
+ before := pgtype.Timestamptz{Time: now.Add(-commentIdempotencyRetention), Valid: true}
+ var total int64
+ for {
+ n, err := queries.DeleteCommentIdempotencyReceiptsBefore(ctx, db.DeleteCommentIdempotencyReceiptsBeforeParams{
+ Before: before,
+ BatchSize: commentIdempotencySweepBatch,
+ })
+ total += n
+ if err != nil || n < commentIdempotencySweepBatch {
+ return total, err
+ }
+ }
+}
diff --git a/server/internal/handler/comment_idempotency_test.go b/server/internal/handler/comment_idempotency_test.go
new file mode 100644
index 0000000000..f0710177f1
--- /dev/null
+++ b/server/internal/handler/comment_idempotency_test.go
@@ -0,0 +1,277 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// GH #8221: a comment POST whose response was lost must be safe to resend.
+
+func idempotentCommentRequest(issueID, key string, body map[string]any) *http.Request {
+ req := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body)
+ if key != "" {
+ req.Header.Set(commentIdempotencyKeyHeader, key)
+ }
+ return withURLParam(req, "id", issueID)
+}
+
+func newCommentIdempotencyKey(t *testing.T) string {
+ t.Helper()
+ key := "test-" + uuid.NewString()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM comment_idempotency_receipt WHERE idempotency_key = $1`, key)
+ })
+ return key
+}
+
+func TestCreateCommentIdempotencyKeyReplaysSavedComment(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment")
+ key := newCommentIdempotencyKey(t)
+ var revision int64
+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&revision)
+
+ var first CommentResponse
+ created := testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "verdict"}))
+ created.Want(http.StatusCreated).JSON(&first)
+ if got := created.Header().Get(commentIdempotencyReplayedHeader); got != "" {
+ t.Fatalf("first request %s = %q, want unset", commentIdempotencyReplayedHeader, got)
+ }
+
+ // The retry may carry a different body: the CLI re-uploads attachments and
+ // rewrites their links on every attempt.
+ var second CommentResponse
+ replayed := testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "verdict, re-rendered"}))
+ replayed.Want(http.StatusOK).JSON(&second)
+ if got := replayed.Header().Get(commentIdempotencyReplayedHeader); got != "true" {
+ t.Fatalf("replay %s = %q, want true", commentIdempotencyReplayedHeader, got)
+ }
+ if second.IssueRevision != first.IssueRevision {
+ t.Fatalf("replay issue_revision = %d, want %d", second.IssueRevision, first.IssueRevision)
+ }
+ if second.ID != first.ID || second.Content != "verdict" {
+ t.Fatalf("replay = %s %q, want the saved comment %s %q", second.ID, second.Content, first.ID, first.Content)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 1 {
+ t.Fatalf("comments on issue = %d, want 1", n)
+ }
+ var after int64
+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&after)
+ if after != revision+1 {
+ t.Fatalf("issue revision = %d, want %d (the replay must not touch the issue)", after, revision+1)
+ }
+
+ // A different key is a different comment.
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, newCommentIdempotencyKey(t), map[string]any{"content": "verdict"})).Want(http.StatusCreated)
+ // No key keeps the old behaviour.
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, "", map[string]any{"content": "verdict"})).Want(http.StatusCreated)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 3 {
+ t.Fatalf("comments on issue = %d, want 3", n)
+ }
+}
+
+func TestCreateCommentIdempotencyKeyRejectsDifferentTarget(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment target")
+ otherIssueID := dbfx.Issue(t, "idempotent comment other target")
+ key := newCommentIdempotencyKey(t)
+
+ var root CommentResponse
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "root"})).Want(http.StatusCreated).JSON(&root)
+
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "root", "parent_id": root.ID})).Want(http.StatusUnprocessableEntity)
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(otherIssueID, key, map[string]any{"content": "root"})).Want(http.StatusUnprocessableEntity)
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "root", "type": "progress_update"})).Want(http.StatusUnprocessableEntity)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id IN ($1, $2)`, issueID, otherIssueID); n != 1 {
+ t.Fatalf("comments = %d, want 1", n)
+ }
+}
+
+func TestCreateCommentIdempotencyKeyDoesNotRepostDeletedComment(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment deleted")
+ key := newCommentIdempotencyKey(t)
+ var first CommentResponse
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "gone"})).Want(http.StatusCreated).JSON(&first)
+ dbfx.Exec(t, `DELETE FROM comment WHERE id = $1`, first.ID)
+
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "gone"})).Want(http.StatusConflict)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("comments = %d, want 0", n)
+ }
+}
+
+func TestCreateCommentIdempotencyKeyTooLong(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment long key")
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, strings.Repeat("k", commentIdempotencyMaxKeyLength+1), map[string]any{"content": "x"})).Want(http.StatusBadRequest)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("comments = %d, want 0", n)
+ }
+}
+
+// Two attempts racing with one key (the first still in flight when the client
+// gives up and resends) must leave one comment, and both must be told about it.
+func TestCreateCommentIdempotencyKeyConcurrentRequestsPostOnce(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment race")
+ key := newCommentIdempotencyKey(t)
+
+ const attempts = 4
+ recorders := make([]*httptest.ResponseRecorder, attempts)
+ var wg sync.WaitGroup
+ start := make(chan struct{})
+ for i := range recorders {
+ recorders[i] = httptest.NewRecorder()
+ req := idempotentCommentRequest(issueID, key, map[string]any{"content": "once"})
+ wg.Add(1)
+ go func(rec *httptest.ResponseRecorder) {
+ defer wg.Done()
+ <-start
+ testHandler.CreateComment(rec, req)
+ }(recorders[i])
+ }
+ close(start)
+ wg.Wait()
+
+ created := 0
+ ids := map[string]bool{}
+ for _, rec := range recorders {
+ switch rec.Code {
+ case http.StatusCreated:
+ created++
+ case http.StatusOK:
+ default:
+ t.Fatalf("attempt status = %d: %s", rec.Code, rec.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v: %s", err, rec.Body.String())
+ }
+ ids[resp.ID] = true
+ }
+ if created != 1 || len(ids) != 1 {
+ t.Fatalf("created = %d, distinct ids = %d, want 1 and 1", created, len(ids))
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 1 {
+ t.Fatalf("comments = %d, want 1", n)
+ }
+}
+
+// The attachment path runs its own transaction; the receipt must be part of it.
+func TestCreateCommentIdempotencyKeyWithAttachments(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment attachment")
+ key := newCommentIdempotencyKey(t)
+ firstAttachment := unlinkedIssueAttachment(t, "")
+ var first CommentResponse
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{
+ "content": "see file", "attachment_ids": []string{firstAttachment},
+ })).Want(http.StatusCreated).JSON(&first)
+
+ // A rerun uploads the file again; the replay must not bind the new upload.
+ secondAttachment := unlinkedIssueAttachment(t, "")
+ var second CommentResponse
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{
+ "content": "see file", "attachment_ids": []string{secondAttachment},
+ })).Want(http.StatusOK).JSON(&second)
+ if second.ID != first.ID || len(second.Attachments) != 1 || second.Attachments[0].ID != firstAttachment {
+ t.Fatalf("replay = %s %+v, want comment %s with attachment %s", second.ID, second.Attachments, first.ID, firstAttachment)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id IS NULL`, secondAttachment); n != 1 {
+ t.Fatalf("second upload bound = %d unbound rows, want 1", n)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 1 {
+ t.Fatalf("comments = %d, want 1", n)
+ }
+}
+
+func TestSweepCommentIdempotencyReceipts(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ oldKey := newCommentIdempotencyKey(t)
+ freshKey := newCommentIdempotencyKey(t)
+ now := time.Now()
+ for _, row := range []struct {
+ key string
+ at time.Time
+ }{{oldKey, now.Add(-commentIdempotencyRetention - time.Hour)}, {freshKey, now.Add(-time.Hour)}} {
+ dbfx.Exec(t, `INSERT INTO comment_idempotency_receipt
+ (workspace_id, actor_type, actor_id, idempotency_key, issue_id, comment_id, request_fingerprint, created_at)
+ VALUES ($1, 'member', $2, $3, gen_random_uuid(), gen_random_uuid(), '\x00', $4)`,
+ testWorkspaceID, testUserID, row.key, pgtype.Timestamptz{Time: row.at, Valid: true})
+ }
+ if _, err := SweepCommentIdempotencyReceipts(context.Background(), testHandler.Queries, now); err != nil {
+ t.Fatalf("sweep: %v", err)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment_idempotency_receipt WHERE idempotency_key = $1`, oldKey); n != 0 {
+ t.Fatalf("expired receipt kept")
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment_idempotency_receipt WHERE idempotency_key = $1`, freshKey); n != 1 {
+ t.Fatalf("fresh receipt removed")
+ }
+}
+
+func lookupIdempotentCommentRequest(issueID, key, query string) *http.Request {
+ req := newRequest(http.MethodGet, "/api/issues/"+issueID+"/comments/idempotent"+query, nil)
+ if key != "" {
+ req.Header.Set(commentIdempotencyKeyHeader, key)
+ }
+ return withURLParam(req, "id", issueID)
+}
+
+// The CLI asks before uploading attachments, so a rerun whose comment already
+// landed does not leave fresh uploads bound to nothing.
+func TestLookupIdempotentComment(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "idempotent comment lookup")
+ rootID := dbfx.Comment(t, issueID, "root")
+ key := newCommentIdempotencyKey(t)
+ query := "?parent_id=" + rootID
+
+ testutil.Call(t, testHandler.LookupIdempotentComment, lookupIdempotentCommentRequest(issueID, "", query)).Want(http.StatusBadRequest)
+ testutil.Call(t, testHandler.LookupIdempotentComment, lookupIdempotentCommentRequest(issueID, key, query)).Want(http.StatusNotFound)
+
+ var created CommentResponse
+ testutil.Call(t, testHandler.CreateComment, idempotentCommentRequest(issueID, key, map[string]any{"content": "reply", "parent_id": rootID})).Want(http.StatusCreated).JSON(&created)
+
+ var found CommentResponse
+ resp := testutil.Call(t, testHandler.LookupIdempotentComment, lookupIdempotentCommentRequest(issueID, key, query))
+ resp.Want(http.StatusOK).JSON(&found)
+ if resp.Header().Get(commentIdempotencyReplayedHeader) != "true" || found.ID != created.ID || found.IssueRevision != created.IssueRevision {
+ t.Fatalf("lookup = %s rev %d (replayed %q), want %s rev %d", found.ID, found.IssueRevision, resp.Header().Get(commentIdempotencyReplayedHeader), created.ID, created.IssueRevision)
+ }
+ // Same rules as a replayed POST: another thread is a different comment.
+ testutil.Call(t, testHandler.LookupIdempotentComment, lookupIdempotentCommentRequest(issueID, key, "")).Want(http.StatusUnprocessableEntity)
+ testutil.Call(t, testHandler.LookupIdempotentComment, lookupIdempotentCommentRequest(issueID, key, "?parent_id=nope")).Want(http.StatusBadRequest)
+ // The lookup only reads.
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 2 {
+ t.Fatalf("comments = %d, want 2", n)
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 1ff6ccfd60..999bd733c6 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -58,6 +58,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"chat_wakeup": workspaceDelete,
"client_usage_daily": workspaceDeleteDetach,
"comment": workspaceDelete,
+ "comment_idempotency_receipt": workspaceDelete,
"comment_reaction": workspaceDelete,
"contact_sales_inquiry": workspaceDeleteKeep,
"daemon_connection": workspaceDelete,
diff --git a/server/migrations/732_comment_idempotency_receipt.down.sql b/server/migrations/732_comment_idempotency_receipt.down.sql
new file mode 100644
index 0000000000..94ce14b20f
--- /dev/null
+++ b/server/migrations/732_comment_idempotency_receipt.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS comment_idempotency_receipt;
diff --git a/server/migrations/732_comment_idempotency_receipt.up.sql b/server/migrations/732_comment_idempotency_receipt.up.sql
new file mode 100644
index 0000000000..443c32153f
--- /dev/null
+++ b/server/migrations/732_comment_idempotency_receipt.up.sql
@@ -0,0 +1,21 @@
+-- Receipts that make POST /api/issues/{id}/comments idempotent (GH #8221).
+--
+-- A client that sends an Idempotency-Key gets one row here, written in the
+-- same transaction as the comment. A retry with the same key from the same
+-- author returns the saved comment instead of posting it again, so a client
+-- that lost the response can resend safely.
+--
+-- The comment table itself is not touched: no new column or index on a hot
+-- table. No foreign keys: rows are removed by the retention sweeper and by
+-- workspace deletion in application code. A receipt whose comment was later
+-- deleted is still honoured; the retry is refused instead of re-posting.
+CREATE TABLE IF NOT EXISTS comment_idempotency_receipt (
+ workspace_id UUID NOT NULL,
+ actor_type TEXT NOT NULL,
+ actor_id UUID NOT NULL,
+ idempotency_key TEXT NOT NULL CHECK (char_length(idempotency_key) BETWEEN 1 AND 255),
+ issue_id UUID NOT NULL,
+ comment_id UUID NOT NULL,
+ request_fingerprint BYTEA NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/733_comment_idempotency_receipt_key.down.sql b/server/migrations/733_comment_idempotency_receipt_key.down.sql
new file mode 100644
index 0000000000..fedb04e3de
--- /dev/null
+++ b/server/migrations/733_comment_idempotency_receipt_key.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_comment_idempotency_receipt_key;
diff --git a/server/migrations/733_comment_idempotency_receipt_key.up.sql b/server/migrations/733_comment_idempotency_receipt_key.up.sql
new file mode 100644
index 0000000000..ff4102a8c8
--- /dev/null
+++ b/server/migrations/733_comment_idempotency_receipt_key.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_comment_idempotency_receipt_key ON comment_idempotency_receipt (workspace_id, actor_type, actor_id, idempotency_key);
diff --git a/server/migrations/734_comment_idempotency_receipt_created.down.sql b/server/migrations/734_comment_idempotency_receipt_created.down.sql
new file mode 100644
index 0000000000..3b1944c69f
--- /dev/null
+++ b/server/migrations/734_comment_idempotency_receipt_created.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_idempotency_receipt_created;
diff --git a/server/migrations/734_comment_idempotency_receipt_created.up.sql b/server/migrations/734_comment_idempotency_receipt_created.up.sql
new file mode 100644
index 0000000000..bc18b677d2
--- /dev/null
+++ b/server/migrations/734_comment_idempotency_receipt_created.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_idempotency_receipt_created ON comment_idempotency_receipt (created_at);
diff --git a/server/pkg/db/generated/comment_idempotency.sql.go b/server/pkg/db/generated/comment_idempotency.sql.go
new file mode 100644
index 0000000000..31ceadc913
--- /dev/null
+++ b/server/pkg/db/generated/comment_idempotency.sql.go
@@ -0,0 +1,104 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: comment_idempotency.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const claimCommentIdempotencyReceipt = `-- name: ClaimCommentIdempotencyReceipt :execrows
+INSERT INTO comment_idempotency_receipt (
+ workspace_id, actor_type, actor_id, idempotency_key, issue_id, comment_id, request_fingerprint
+) VALUES ($1, $2, $3, $4, $5, $6, $7)
+ON CONFLICT (workspace_id, actor_type, actor_id, idempotency_key) DO NOTHING
+`
+
+type ClaimCommentIdempotencyReceiptParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ IdempotencyKey string `json:"idempotency_key"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ RequestFingerprint []byte `json:"request_fingerprint"`
+}
+
+// Runs first in the comment's own transaction. A concurrent request with the
+// same key waits on the unique index until the first one commits or rolls
+// back; it then claims nothing (0 rows) and replays the first comment, or
+// claims the key itself if the first request rolled back.
+func (q *Queries) ClaimCommentIdempotencyReceipt(ctx context.Context, arg ClaimCommentIdempotencyReceiptParams) (int64, error) {
+ result, err := q.db.Exec(ctx, claimCommentIdempotencyReceipt,
+ arg.WorkspaceID,
+ arg.ActorType,
+ arg.ActorID,
+ arg.IdempotencyKey,
+ arg.IssueID,
+ arg.CommentID,
+ arg.RequestFingerprint,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const deleteCommentIdempotencyReceiptsBefore = `-- name: DeleteCommentIdempotencyReceiptsBefore :execrows
+DELETE FROM comment_idempotency_receipt
+WHERE ctid = ANY(ARRAY(
+ SELECT r.ctid FROM comment_idempotency_receipt r
+ WHERE r.created_at < $1::timestamptz
+ ORDER BY r.created_at
+ LIMIT $2::int
+))
+`
+
+type DeleteCommentIdempotencyReceiptsBeforeParams struct {
+ Before pgtype.Timestamptz `json:"before"`
+ BatchSize int32 `json:"batch_size"`
+}
+
+// Bounded retention sweep. Receipts only need to outlive a client's retry
+// window, so old rows are deleted in batches instead of kept forever.
+func (q *Queries) DeleteCommentIdempotencyReceiptsBefore(ctx context.Context, arg DeleteCommentIdempotencyReceiptsBeforeParams) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteCommentIdempotencyReceiptsBefore, arg.Before, arg.BatchSize)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const getCommentIdempotencyReceipt = `-- name: GetCommentIdempotencyReceipt :one
+SELECT issue_id, comment_id, request_fingerprint FROM comment_idempotency_receipt
+WHERE workspace_id = $1 AND actor_type = $2 AND actor_id = $3 AND idempotency_key = $4
+`
+
+type GetCommentIdempotencyReceiptParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ IdempotencyKey string `json:"idempotency_key"`
+}
+
+type GetCommentIdempotencyReceiptRow struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ RequestFingerprint []byte `json:"request_fingerprint"`
+}
+
+func (q *Queries) GetCommentIdempotencyReceipt(ctx context.Context, arg GetCommentIdempotencyReceiptParams) (GetCommentIdempotencyReceiptRow, error) {
+ row := q.db.QueryRow(ctx, getCommentIdempotencyReceipt,
+ arg.WorkspaceID,
+ arg.ActorType,
+ arg.ActorID,
+ arg.IdempotencyKey,
+ )
+ var i GetCommentIdempotencyReceiptRow
+ err := row.Scan(&i.IssueID, &i.CommentID, &i.RequestFingerprint)
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index ff27b0c709..dce415a920 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -762,6 +762,17 @@ type Comment struct {
SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`
}
+type CommentIdempotencyReceipt struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ IdempotencyKey string `json:"idempotency_key"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ RequestFingerprint []byte `json:"request_fingerprint"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type CommentReaction struct {
ID pgtype.UUID `json:"id"`
CommentID pgtype.UUID `json:"comment_id"`
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index cb13d9afc0..ae67fcb8ae 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -99,6 +99,9 @@ cleared_outbound_cards AS (
cleared_chat_submission_receipts AS (
DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
),
+cleared_comment_idempotency_receipts AS (
+ DELETE FROM comment_idempotency_receipt WHERE comment_idempotency_receipt.workspace_id = $1
+),
cleared_draft_restores AS (
-- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
-- no reaper, while its chat_session rows cascade away with the workspace. Reach
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 0ddfbfa646..dc46007ac0 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -391,6 +391,9 @@ deleted_agent_builder_drafts AS (
deleted_comment_reactions AS (
DELETE FROM comment_reaction WHERE workspace_id = $1
),
+deleted_comment_idempotency_receipts AS (
+ DELETE FROM comment_idempotency_receipt WHERE comment_idempotency_receipt.workspace_id = $1
+),
deleted_issue_reactions AS (
DELETE FROM issue_reaction WHERE workspace_id = $1
),
diff --git a/server/pkg/db/queries/comment_idempotency.sql b/server/pkg/db/queries/comment_idempotency.sql
new file mode 100644
index 0000000000..fddd14433b
--- /dev/null
+++ b/server/pkg/db/queries/comment_idempotency.sql
@@ -0,0 +1,24 @@
+-- name: GetCommentIdempotencyReceipt :one
+SELECT issue_id, comment_id, request_fingerprint FROM comment_idempotency_receipt
+WHERE workspace_id = $1 AND actor_type = $2 AND actor_id = $3 AND idempotency_key = $4;
+
+-- name: ClaimCommentIdempotencyReceipt :execrows
+-- Runs first in the comment's own transaction. A concurrent request with the
+-- same key waits on the unique index until the first one commits or rolls
+-- back; it then claims nothing (0 rows) and replays the first comment, or
+-- claims the key itself if the first request rolled back.
+INSERT INTO comment_idempotency_receipt (
+ workspace_id, actor_type, actor_id, idempotency_key, issue_id, comment_id, request_fingerprint
+) VALUES ($1, $2, $3, $4, $5, $6, $7)
+ON CONFLICT (workspace_id, actor_type, actor_id, idempotency_key) DO NOTHING;
+
+-- name: DeleteCommentIdempotencyReceiptsBefore :execrows
+-- Bounded retention sweep. Receipts only need to outlive a client's retry
+-- window, so old rows are deleted in batches instead of kept forever.
+DELETE FROM comment_idempotency_receipt
+WHERE ctid = ANY(ARRAY(
+ SELECT r.ctid FROM comment_idempotency_receipt r
+ WHERE r.created_at < sqlc.arg(before)::timestamptz
+ ORDER BY r.created_at
+ LIMIT sqlc.arg(batch_size)::int
+));
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index 3ec2d8f814..81bdb7f0cc 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -174,6 +174,9 @@ cleared_outbound_cards AS (
cleared_chat_submission_receipts AS (
DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
),
+cleared_comment_idempotency_receipts AS (
+ DELETE FROM comment_idempotency_receipt WHERE comment_idempotency_receipt.workspace_id = $1
+),
cleared_draft_restores AS (
-- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
-- no reaper, while its chat_session rows cascade away with the workspace. Reach
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index eaddf5226b..110306bd9c 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -365,6 +365,9 @@ deleted_agent_builder_drafts AS (
deleted_comment_reactions AS (
DELETE FROM comment_reaction WHERE workspace_id = $1
),
+deleted_comment_idempotency_receipts AS (
+ DELETE FROM comment_idempotency_receipt WHERE comment_idempotency_receipt.workspace_id = $1
+),
deleted_issue_reactions AS (
DELETE FROM issue_reaction WHERE workspace_id = $1
),