Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8829: fix CLI comment attachment binding (#10184)
xiao fanf68c891d3b73
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 60a5a51487..bee6215db9 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -2705,7 +2705,8 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {}var attachmentIDs []stringfor _, att := range pending {- id, uploadErr := client.UploadFile(ctx, att.data, att.path, issueID)+ // Comment attachments are linked by the comment request; upload them unbound first.+ id, uploadErr := client.UploadFile(ctx, att.data, att.path, "")if uploadErr != nil {return fmt.Errorf("upload attachment %s: %w", att.path, uploadErr)}diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 985f197933..4945257ef4 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -567,6 +567,56 @@ func newIssueCommentAddTestCmd() *cobra.Command {return cmd}+func TestRunIssueCommentAddUploadsAttachmentWithoutIssueID(t *testing.T) {+ const issueRef = "MUL-1"+ t.Chdir(t.TempDir())+ attachmentPath := "comment.txt"+ if err := os.WriteFile(attachmentPath, []byte("comment attachment"), 0o644); err != nil {+ t.Fatalf("write attachment: %v", err)+ }++ var uploadedIssueID string+ var commentBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+issueRef:+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": issueRef})+ case r.Method == http.MethodPost && r.URL.Path == "/api/upload-file":+ if err := r.ParseMultipartForm(1 << 20); err != nil {+ t.Fatalf("parse upload: %v", err)+ }+ uploadedIssueID = r.FormValue("issue_id")+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "attachment-1"})+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/issue-1/comments":+ if err := json.NewDecoder(r.Body).Decode(&commentBody); err != nil {+ t.Fatalf("decode comment body: %v", err)+ }+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "comment-1", "content": "with attachment"})+ 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")++ cmd := newIssueCommentAddTestCmd()+ _ = cmd.Flags().Set("content", "with attachment")+ _ = cmd.Flags().Set("attachment", attachmentPath)+ if err := runIssueCommentAdd(cmd, []string{issueRef}); err != nil {+ t.Fatalf("runIssueCommentAdd: %v", err)+ }+ if uploadedIssueID != "" {+ t.Fatalf("upload issue_id = %q, want empty for a comment attachment", uploadedIssueID)+ }+ attachmentIDs, ok := commentBody["attachment_ids"].([]any)+ if !ok || len(attachmentIDs) != 1 || attachmentIDs[0] != "attachment-1" {+ t.Fatalf("comment attachment_ids = %#v, want [attachment-1]", commentBody["attachment_ids"])+ }+}+func TestRunIssueCommentAddSteering(t *testing.T) {const (issueID = "11111111-1111-4111-8111-111111111111"diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 009eb9d91c..a600a019c7 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1868,15 +1868,11 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// a delete, so there is no window at all. Mirrors the attachment-set// edit in UpdateComment.//- // Owner first: the CreateComment statement takes the issue row, and only- // then are the attachments locked — the issue -> comment -> child order- // LockIssueForDelete, UpdateComment, LockLiveComment and DeleteAttachment- // all share. Taking the attachments first inverts it against issue- // teardown, which holds the issue and then reaches the same rows through- // the issue_id cascade, and Postgres aborts one side. Locking them at all- // still pins the requested set: an attachment deleted while this waited- // is refused before the comment is committed, rather than the comment- // committing without it.+ // Ownerless uploads are locked before the issue, matching issue updates.+ // Existing issue attachments are locked only after CreateComment takes+ // the issue: the issue -> comment -> child order shared with deletion.+ // Keeping those two sets separate avoids inverting either lock order.+ // Both sets stay pinned until the comment and its bindings commit.tx, beginErr := h.beginWakeupWrite(r.Context())if beginErr != nil {slog.Warn("create comment failed", append(logger.RequestAttrs(r), "error", beginErr, "issue_id", issueID)...)@@ -1885,10 +1881,17 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {}defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)- created, err = qtx.CreateComment(r.Context(), createParams)+ var unboundIDs []pgtype.UUID+ unboundIDs, err = qtx.LockUnboundAttachmentsForCommentLink(r.Context(), db.LockUnboundAttachmentsForCommentLinkParams{+ WorkspaceID: issue.WorkspaceID,+ AttachmentIds: attachmentIDs,+ })+ if err == nil {+ created, err = qtx.CreateComment(r.Context(), createParams)+ }if err == nil {var missing pgtype.UUID- missing, err = lockCommentAttachments(r.Context(), qtx, issue.WorkspaceID, issue.ID, attachmentIDs)+ missing, err = lockCommentAttachments(r.Context(), qtx, issue.WorkspaceID, issue.ID, attachmentIDs, unboundIDs)if err == nil && missing.Valid {writeError(w, http.StatusConflict, "attachment "+uuidToString(missing)+" is no longer available")return@@ -1896,9 +1899,10 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {}if err == nil {err = qtx.LinkAttachmentsToComment(r.Context(), db.LinkAttachmentsToCommentParams{- CommentID: created.ID,- IssueID: issue.ID,- Column3: attachmentIDs,+ CommentID: created.ID,+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ AttachmentIds: attachmentIDs,})}if err == nil {@@ -3738,12 +3742,10 @@ type commentDeletion struct {IssueRevision int64}-// lockCommentAttachments locks the unbound issue attachments a comment is-// being created with and reports the first requested id that is not among-// them: never eligible, or deleted while the lock waited. The caller must-// already hold the issue's row lock — these are its children, and taking them-// first is the inversion CreateComment documents.-func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, issueID pgtype.UUID, ids []pgtype.UUID) (missing pgtype.UUID, err error) {+// lockCommentAttachments validates and pins the full requested set, including+// existing issue attachments. The caller must already hold the issue's row+// lock and have locked ownerless uploads before it; see CreateComment.+func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, issueID pgtype.UUID, ids, unboundIDs []pgtype.UUID) (missing pgtype.UUID, err error) {locked, err := qtx.LockAttachmentsForCommentLink(ctx, db.LockAttachmentsForCommentLinkParams{WorkspaceID: workspaceID,IssueID: issueID,@@ -3752,7 +3754,10 @@ func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, iif err != nil {return pgtype.UUID{}, err}- have := make(map[pgtype.UUID]struct{}, len(locked))+ have := make(map[pgtype.UUID]struct{}, len(locked)+len(unboundIDs))+ for _, id := range unboundIDs {+ have[id] = struct{}{}+ }for _, id := range locked {have[id] = struct{}{}}diff --git a/server/internal/handler/comment_create_attachment_test.go b/server/internal/handler/comment_create_attachment_test.goindex f13042dde9..6e0fd42381 100644--- a/server/internal/handler/comment_create_attachment_test.go+++ b/server/internal/handler/comment_create_attachment_test.go@@ -3,6 +3,7 @@ package handlerimport ("context""errors"+ "fmt""net/http""strings""testing"@@ -10,6 +11,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype""github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/testutil"@@ -59,8 +61,12 @@ func createCommentWithAttachment(t *testing.T, h *Handler, issueID, attachmentIDfunc unlinkedIssueAttachment(t *testing.T, issueID string) string {t.Helper()+ var owner any+ if issueID != "" {+ owner = issueID+ }return dbfx.Insert(t, "attachment", testutil.Cols{- "workspace_id": testWorkspaceID, "issue_id": issueID,+ "workspace_id": testWorkspaceID, "issue_id": owner,"uploader_type": "member", "uploader_id": testUserID,"filename": "shot.png", "url": "https://example.test/shot.png","content_type": "image/png", "size_bytes": 1,@@ -71,16 +77,132 @@ func TestCreateCommentLinksItsAttachmentsInOneTransaction(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- issueID := dbfx.Issue(t, "comment with attachments")- attachmentID := unlinkedIssueAttachment(t, issueID)+ for _, unbound := range []bool{false, true} {+ t.Run(fmt.Sprintf("unbound=%t", unbound), func(t *testing.T) {+ issueID := dbfx.Issue(t, "comment with attachments")+ owner := issueID+ if unbound {+ owner = ""+ }+ attachmentID := unlinkedIssueAttachment(t, owner)+ var revision int64+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&revision)- var resp CommentResponse- createCommentWithAttachment(t, testHandler, issueID, attachmentID).Want(http.StatusCreated).JSON(&resp)- if len(resp.Attachments) != 1 || resp.Attachments[0].ID != attachmentID {- t.Fatalf("response attachments = %+v, want the posted one", resp.Attachments)+ var resp CommentResponse+ createCommentWithAttachment(t, testHandler, issueID, attachmentID).Want(http.StatusCreated).JSON(&resp)+ if len(resp.Attachments) != 1 || resp.Attachments[0].ID != attachmentID {+ t.Fatalf("response attachments = %+v, want the posted one", resp.Attachments)+ }+ att := resp.Attachments[0]+ if att.IssueID == nil || *att.IssueID != issueID || att.CommentID == nil || *att.CommentID != resp.ID {+ t.Fatalf("attachment owners = %+v, want issue %s and comment %s", att, issueID, resp.ID)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND issue_id = $2 AND comment_id = $3`, attachmentID, issueID, resp.ID); n != 1 {+ t.Fatalf("attachment linked rows = %d, want 1", n)+ }+ if resp.IssueRevision != revision+1 {+ t.Fatalf("issue revision = %d, want %d", resp.IssueRevision, revision+1)+ }+ })}- if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id = $2`, attachmentID, resp.ID); n != 1 {- t.Fatalf("attachment linked rows = %d, want 1", n)+}++func TestCreateCommentRejectedLeavesUploadUnbound(t *testing.T) {+ issueID := dbfx.Issue(t, "rejected comment with upload")+ attachmentID := unlinkedIssueAttachment(t, "")+ runtimeID := dbfx.Runtime(t, "comment admission runtime")+ agentID := dbfx.Agent(t, "comment admission agent", runtimeID)+ parentID := dbfx.Comment(t, issueID, "reply here")+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID, "trigger_comment_id": parentID, "runtime_id": runtimeID,+ })+ req := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": "missing required reply parent", "attachment_ids": []string{attachmentID},+ })+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", taskID)+ testutil.Call(t, testHandler.CreateComment, withURLParam(req, "id", issueID)).Want(http.StatusConflict)+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND issue_id IS NULL AND comment_id IS NULL`, attachmentID); n != 1 {+ t.Fatal("rejected comment bound its upload")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1 AND id <> $2`, issueID, parentID); n != 0 {+ t.Fatalf("rejected comment left %d comments", n)+ }+}++func TestCreateCommentRejectsUnavailableAttachmentsAtomically(t *testing.T) {+ for _, kind := range []string{"other workspace", "other issue", "existing comment", "source context", "chat session", "chat message", "task", "missing"} {+ t.Run(kind, func(t *testing.T) {+ issueID := dbfx.Issue(t, "attachment isolation")+ validID := unlinkedIssueAttachment(t, "")+ invalidID := unlinkedIssueAttachment(t, "")+ attachmentWorkspaceID := testWorkspaceID+ wantComments := 0+ switch kind {+ case "other workspace":+ ws := dbfx.Workspace(t, "other attachment workspace", "comment-att-"+invalidID)+ dbfx.Exec(t, `UPDATE attachment SET workspace_id = $2 WHERE id = $1`, invalidID, ws)+ attachmentWorkspaceID = ws+ case "other issue":+ other := dbfx.Issue(t, "other attachment issue")+ dbfx.Exec(t, `UPDATE attachment SET issue_id = $2 WHERE id = $1`, invalidID, other)+ case "existing comment":+ commentID := dbfx.Comment(t, issueID, "already owns upload")+ dbfx.Exec(t, `UPDATE attachment SET comment_id = $2 WHERE id = $1`, invalidID, commentID)+ wantComments = 1+ case "source context":+ dbfx.Exec(t, `UPDATE attachment SET source_context_id = $2 WHERE id = $1`, invalidID, issueID)+ case "chat session", "chat message":+ runtimeID := dbfx.Runtime(t, "private chat attachment runtime")+ agentID := dbfx.Agent(t, "private chat attachment agent", runtimeID)+ sessionID := dbfx.ChatSession(t, agentID)+ if kind == "chat session" {+ dbfx.Exec(t, `UPDATE attachment SET chat_session_id = $2 WHERE id = $1`, invalidID, sessionID)+ } else {+ messageID := dbfx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "role": "user", "content": "private file"})+ dbfx.Exec(t, `UPDATE attachment SET chat_message_id = $2 WHERE id = $1`, invalidID, messageID)+ }+ case "task":+ dbfx.Exec(t, `UPDATE attachment SET task_id = $2 WHERE id = $1`, invalidID, issueID)+ case "missing":+ dbfx.Exec(t, `DELETE FROM attachment WHERE id = $1`, invalidID)+ }+ var before db.Attachment+ if kind != "missing" {+ var err error+ before, err = testHandler.Queries.GetAttachment(context.Background(), db.GetAttachmentParams{+ ID: parseUUID(invalidID), WorkspaceID: parseUUID(attachmentWorkspaceID),+ })+ if err != nil {+ t.Fatal(err)+ }+ }+ var revision int64+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&revision)+ req := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": "all or nothing", "attachment_ids": []string{validID, invalidID},+ })+ testutil.Call(t, testHandler.CreateComment, withURLParam(req, "id", issueID)).Want(http.StatusConflict)+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != wantComments {+ t.Fatalf("refused attachment left %d comments, want %d", n, wantComments)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND issue_id IS NULL AND comment_id IS NULL`, validID); n != 1 {+ t.Fatal("refused batch bound its valid upload")+ }+ if kind != "missing" {+ after, err := testHandler.Queries.GetAttachment(context.Background(), db.GetAttachmentParams{+ ID: parseUUID(invalidID), WorkspaceID: parseUUID(attachmentWorkspaceID),+ })+ if err != nil || after != before {+ t.Fatalf("refused attachment changed: before=%+v after=%+v err=%v", before, after, err)+ }+ }+ var afterRevision int64+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&afterRevision)+ if afterRevision != revision {+ t.Fatalf("refused attachment bumped issue revision from %d to %d", revision, afterRevision)+ }+ })}}@@ -90,18 +212,98 @@ func TestCreateCommentRollsBackWhenAttachmentLinkFails(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- issueID := dbfx.Issue(t, "comment attachment link failure")- attachmentID := unlinkedIssueAttachment(t, issueID)+ for _, unbound := range []bool{false, true} {+ t.Run(fmt.Sprintf("unbound=%t", unbound), func(t *testing.T) {+ issueID := dbfx.Issue(t, "comment attachment link failure")+ owner := issueID+ if unbound {+ owner = ""+ }+ attachmentID := unlinkedIssueAttachment(t, owner)- h := *testHandler- h.TxStarter = &failLinkAttachmentsTxStarter{delegate: testPool}- createCommentWithAttachment(t, &h, issueID, attachmentID).Want(http.StatusInternalServerError)+ h := *testHandler+ h.TxStarter = &failLinkAttachmentsTxStarter{delegate: testPool}+ createCommentWithAttachment(t, &h, issueID, attachmentID).Want(http.StatusInternalServerError)- if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {- t.Fatalf("issue has %d comments after a failed link, want none", n)+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {+ t.Fatalf("issue has %d comments after a failed link, want none", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id IS NULL AND COALESCE(issue_id::text, '') = $2`, attachmentID, owner); n != 1 {+ t.Fatal("failed link changed attachment ownership")+ }+ })+ }+}++func TestCreateCommentUnboundAttachmentDoesNotDeadlockWithIssueLink(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ issueID := dbfx.Issue(t, "unbound attachment vs issue link")+ attachmentID := unlinkedIssueAttachment(t, "")+ holder, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer holder.Rollback(context.Background())+ qtx := testHandler.Queries.WithTx(holder)+ if _, err := qtx.LockAttachmentsForIssueLink(ctx, db.LockAttachmentsForIssueLinkParams{+ WorkspaceID: parseUUID(testWorkspaceID), AttachmentIds: []pgtype.UUID{parseUUID(attachmentID)},+ }); err != nil {+ t.Fatal(err)+ }++ var got *testutil.Response+ done := make(chan error, 1)+ go func() {+ got = createCommentWithAttachment(t, testHandler, issueID, attachmentID)+ done <- nil+ }()+ waitForBlockedQuery(t, done, "LockUnboundAttachmentsForCommentLink", "LockAttachmentsForCommentLink")++ // The issue update already holds the ownerless upload. It must be able to+ // take the issue next while comment creation waits without holding it.+ _, linkErr := qtx.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{+ IssueID: parseUUID(issueID), WorkspaceID: parseUUID(testWorkspaceID),+ AttachmentIds: []pgtype.UUID{parseUUID(attachmentID)}, BumpRevision: true,+ })+ if linkErr == nil {+ linkErr = holder.Commit(ctx)+ }+ <-done+ if linkErr != nil {+ t.Fatalf("issue link deadlocked or failed: %v", linkErr)+ }+ got.Want(http.StatusCreated)+}++func TestCreateCommentUnboundAttachmentCanOnlyBeClaimedOnce(t *testing.T) {+ attachmentID := unlinkedIssueAttachment(t, "")+ issues := []string{dbfx.Issue(t, "first claimant"), dbfx.Issue(t, "second claimant")}+ responses := make(chan *testutil.Response, len(issues))+ for _, issueID := range issues {+ go func() {+ responses <- createCommentWithAttachment(t, testHandler, issueID, attachmentID)+ }()+ }+ var winner CommentResponse+ codes := map[int]int{}+ for range issues {+ resp := <-responses+ codes[resp.Code]+++ if resp.Code == http.StatusCreated {+ resp.JSON(&winner)+ } else {+ resp.Want(http.StatusConflict)+ }+ }+ if codes[http.StatusCreated] != 1 || codes[http.StatusConflict] != 1 {+ t.Fatalf("competing comment statuses = %v, want one 201 and one 409", codes)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = ANY($1::uuid[])`, issues); n != 1 {+ t.Fatalf("competing claims left %d comments, want one", n)}- if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id IS NULL`, attachmentID); n != 1 {- t.Fatalf("attachment was left linked after the rollback")+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id = $2 AND issue_id = $3`, attachmentID, winner.ID, winner.IssueID); n != 1 {+ t.Fatal("attachment does not belong to winning comment")}}diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.goindex ad95d81795..d850e0d0ad 100644--- a/server/pkg/db/generated/attachment.sql.go+++ b/server/pkg/db/generated/attachment.sql.go@@ -564,21 +564,34 @@ func (q *Queries) LinkAttachmentsToChatMessage(ctx context.Context, arg LinkAttaconst linkAttachmentsToComment = `-- name: LinkAttachmentsToComment :execUPDATE attachment-SET comment_id = $1-WHERE issue_id = $2+SET comment_id = $1,+ issue_id = $2+WHERE workspace_id = $3+ AND (issue_id = $2 OR (+ issue_id IS NULL+ AND chat_session_id IS NULL+ AND chat_message_id IS NULL+ AND task_id IS NULL+ ))AND comment_id IS NULLAND source_context_id IS NULL- AND id = ANY($3::uuid[])+ AND id = ANY($4::uuid[])`type LinkAttachmentsToCommentParams struct {- CommentID pgtype.UUID `json:"comment_id"`- IssueID pgtype.UUID `json:"issue_id"`- Column3 []pgtype.UUID `json:"column_3"`+ CommentID pgtype.UUID `json:"comment_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`}func (q *Queries) LinkAttachmentsToComment(ctx context.Context, arg LinkAttachmentsToCommentParams) error {- _, err := q.db.Exec(ctx, linkAttachmentsToComment, arg.CommentID, arg.IssueID, arg.Column3)+ _, err := q.db.Exec(ctx, linkAttachmentsToComment,+ arg.CommentID,+ arg.IssueID,+ arg.WorkspaceID,+ arg.AttachmentIds,+ )return err}@@ -1224,6 +1237,7 @@ type LockAttachmentsForCommentLinkParams struct {// requested set under that lock and returns the ids still eligible, so the// caller can refuse before the comment is committed when a requested// attachment was deleted while the issue lock was contended.+// Ownerless uploads are already pinned by LockUnboundAttachmentsForCommentLink.func (q *Queries) LockAttachmentsForCommentLink(ctx context.Context, arg LockAttachmentsForCommentLinkParams) ([]pgtype.UUID, error) {rows, err := q.db.Query(ctx, lockAttachmentsForCommentLink, arg.WorkspaceID, arg.IssueID, arg.AttachmentIds)if err != nil {@@ -1285,6 +1299,48 @@ func (q *Queries) LockAttachmentsForIssueLink(ctx context.Context, arg LockAttacreturn items, nil}+const lockUnboundAttachmentsForCommentLink = `-- name: LockUnboundAttachmentsForCommentLink :many+SELECT id FROM attachment+WHERE workspace_id = $1+ AND issue_id IS NULL+ AND comment_id IS NULL+ AND chat_session_id IS NULL+ AND chat_message_id IS NULL+ AND task_id IS NULL+ AND source_context_id IS NULL+ AND id = ANY($2::uuid[])+ORDER BY id+FOR UPDATE+`++type LockUnboundAttachmentsForCommentLinkParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`+}++// Like issue updates, comment creation locks ownerless uploads before the+// issue row. Once it takes the issue, it locks existing issue children below.+// This keeps both upload adoption and owner-first deletion in the same order.+func (q *Queries) LockUnboundAttachmentsForCommentLink(ctx context.Context, arg LockUnboundAttachmentsForCommentLinkParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, lockUnboundAttachmentsForCommentLink, arg.WorkspaceID, arg.AttachmentIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const replaceCommentAttachments = `-- name: ReplaceCommentAttachments :execrowsUPDATE attachmentSET comment_id = CASEdiff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sqlindex b01483d297..6a2c931bc9 100644--- a/server/pkg/db/queries/attachment.sql+++ b/server/pkg/db/queries/attachment.sql@@ -95,11 +95,18 @@ RETURNING url;-- name: LinkAttachmentsToComment :execUPDATE attachment-SET comment_id = $1-WHERE issue_id = $2+SET comment_id = sqlc.arg(comment_id),+ issue_id = sqlc.arg(issue_id)+WHERE workspace_id = sqlc.arg(workspace_id)+ AND (issue_id = sqlc.arg(issue_id) OR (+ issue_id IS NULL+ AND chat_session_id IS NULL+ AND chat_message_id IS NULL+ AND task_id IS NULL+ ))AND comment_id IS NULLAND source_context_id IS NULL- AND id = ANY($3::uuid[]);+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[]);-- name: ReplaceCommentAttachments :execrowsUPDATE attachment@@ -197,6 +204,22 @@ WHERE workspace_id = sqlc.arg(workspace_id)ORDER BY idFOR UPDATE;+-- name: LockUnboundAttachmentsForCommentLink :many+-- Like issue updates, comment creation locks ownerless uploads before the+-- issue row. Once it takes the issue, it locks existing issue children below.+-- This keeps both upload adoption and owner-first deletion in the same order.+SELECT id FROM attachment+WHERE workspace_id = sqlc.arg(workspace_id)+ AND issue_id IS NULL+ AND comment_id IS NULL+ AND chat_session_id IS NULL+ AND chat_message_id IS NULL+ AND task_id IS NULL+ AND source_context_id IS NULL+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[])+ORDER BY id+FOR UPDATE;+-- name: LockAttachmentsForCommentLink :many-- CreateComment binds attachments in the transaction that created the comment,-- after the CreateComment statement has taken the issue row: issue -> comment@@ -204,6 +227,7 @@ FOR UPDATE;-- requested set under that lock and returns the ids still eligible, so the-- caller can refuse before the comment is committed when a requested-- attachment was deleted while the issue lock was contended.+-- Ownerless uploads are already pinned by LockUnboundAttachmentsForCommentLink.SELECT id FROM attachmentWHERE workspace_id = sqlc.arg(workspace_id)AND issue_id = sqlc.arg(issue_id)