Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): return the existing reaction when the same issue reaction is added twice at once (#11104)
pseudoyucf291f3829ea
diff --git a/server/internal/handler/comment_create_attachment_test.go b/server/internal/handler/comment_create_attachment_test.goindex 6e0fd42381..4eafc497dc 100644--- a/server/internal/handler/comment_create_attachment_test.go+++ b/server/internal/handler/comment_create_attachment_test.go@@ -396,7 +396,7 @@ func TestCreateCommentWithAttachmentFollowsOwnerFirstLockOrder(t *testing.T) {// issue, then the row. Taking the lock here by hand would let a// production mode too weak to serialize issue writers pass.qtx := testHandler.Queries.WithTx(holder)- if _, err := qtx.LockIssueForAttachmentWrite(ctx, db.LockIssueForAttachmentWriteParams{+ if _, err := qtx.LockIssueForWrite(ctx, db.LockIssueForWriteParams{ID: parseUUID(issueID),WorkspaceID: parseUUID(testWorkspaceID),}); err != nil {@@ -531,7 +531,7 @@ func TestDeleteAttachmentTakesTheIssueBeforeTheRow(t *testing.T) {got = testutil.Call(t, testHandler.DeleteAttachment, withURLParam(req, "id", attachmentID))done <- nil}()- waitForCommentMutationLock(t, "LockIssueForAttachmentWrite", done)+ waitForCommentMutationLock(t, "LockIssueForWrite", done)if err := holder.Commit(ctx); err != nil {t.Fatalf("release issue: %v", err)diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 5a2e9c44df..fc3941f062 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -1647,7 +1647,7 @@ func (h *Handler) attachmentOwnerLockAttempt(ctx context.Context, att db.Attachmif att.IssueID.Valid {// A missing issue is not an error here: its cascade took the attachment// with it, which the re-read below reports as pgx.ErrNoRows.- if _, err := qtx.LockIssueForAttachmentWrite(ctx, db.LockIssueForAttachmentWriteParams{+ if _, err := qtx.LockIssueForWrite(ctx, db.LockIssueForWriteParams{ID: att.IssueID,WorkspaceID: att.WorkspaceID,}); err != nil && !errors.Is(err, pgx.ErrNoRows) {diff --git a/server/internal/handler/issue_reaction.go b/server/internal/handler/issue_reaction.goindex cc5c115cea..e0f9bf9ed4 100644--- a/server/internal/handler/issue_reaction.go+++ b/server/internal/handler/issue_reaction.go@@ -2,10 +2,12 @@ package handlerimport ("encoding/json"+ "errors""log/slog""net/http""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -76,6 +78,12 @@ func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {actorType, actorID := h.resolveActor(r, userID, workspaceID)reaction, err := wakeupWrite(h, r, func(q *db.Queries) (db.AddIssueReactionRow, error) {+ if _, err := q.LockIssueForWrite(r.Context(), db.LockIssueForWriteParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ }); err != nil {+ return db.AddIssueReactionRow{}, err+ }return q.AddIssueReaction(r.Context(), db.AddIssueReactionParams{IssueID: issue.ID,WorkspaceID: issue.WorkspaceID,@@ -84,6 +92,11 @@ func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {Emoji: req.Emoji,})})+ if errors.Is(err, pgx.ErrNoRows) {+ // Deleted after the load above.+ writeError(w, http.StatusNotFound, "issue not found")+ return+ }if err != nil {slog.Warn("add issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)writeError(w, http.StatusInternalServerError, "failed to add reaction")@@ -134,6 +147,12 @@ func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {actorType, actorID := h.resolveActor(r, userID, workspaceID)removed, err := wakeupWrite(h, r, func(q *db.Queries) (db.RemoveIssueReactionRow, error) {+ if _, err := q.LockIssueForWrite(r.Context(), db.LockIssueForWriteParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ }); err != nil {+ return db.RemoveIssueReactionRow{}, err+ }return q.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{IssueID: issue.ID,ActorType: actorType,@@ -141,6 +160,11 @@ func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {Emoji: req.Emoji,})})+ if errors.Is(err, pgx.ErrNoRows) {+ // Deleted after the load above.+ writeError(w, http.StatusNotFound, "issue not found")+ return+ }if err != nil {slog.Warn("remove issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)writeError(w, http.StatusInternalServerError, "failed to remove reaction")diff --git a/server/internal/handler/issue_reaction_test.go b/server/internal/handler/issue_reaction_test.gonew file mode 100644index 0000000000..ed79a4077d--- /dev/null+++ b/server/internal/handler/issue_reaction_test.go@@ -0,0 +1,99 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Two clicks on the same emoji land at once. The second request queues behind+// the first one's uncommitted reaction and must return that reaction once the+// first commits, not fail because its own snapshot predates the row.+func TestAddIssueReactionQueuedBehindSameReactionReturnsIt(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ issueID := dbfx.Issue(t, "same reaction twice at once")++ first, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin first: %v", err)+ }+ defer first.Rollback(ctx)+ var firstPID int+ if err := first.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&firstPID); err != nil {+ t.Fatalf("first pid: %v", err)+ }+ added, err := testHandler.Queries.WithTx(first).AddIssueReaction(ctx, db.AddIssueReactionParams{+ IssueID: parseUUID(issueID),+ WorkspaceID: parseUUID(testWorkspaceID),+ ActorType: "member",+ ActorID: parseUUID(testUserID),+ Emoji: "π",+ })+ if err != nil {+ t.Fatalf("first add: %v", err)+ }++ w := httptest.NewRecorder()+ done := make(chan struct{})+ go func() {+ defer close(done)+ testHandler.AddIssueReaction(w, withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/reactions", map[string]any{+ "emoji": "π",+ }), "id", issueID))+ }()+ waitForBackendBlockedBy(t, firstPID, done)++ if err := first.Commit(ctx); err != nil {+ t.Fatalf("commit first: %v", err)+ }+ <-done++ if w.Code != http.StatusCreated {+ t.Fatalf("second add = %d %s, want 201", w.Code, w.Body.String())+ }+ var got IssueReactionResponse+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if got.ID != uuidToString(added.ID) {+ t.Fatalf("second add returned reaction %s, want the first one %s", got.ID, uuidToString(added.ID))+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_reaction WHERE issue_id = $1`, issueID); n != 1 {+ t.Fatalf("issue has %d reactions, want 1", n)+ }+}++func waitForBackendBlockedBy(t *testing.T, holderPID int, done <-chan struct{}) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ select {+ case <-done:+ t.Fatal("request finished before the competing transaction committed")+ default:+ }+ var blocked bool+ if err := testPool.QueryRow(context.Background(), `+ SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity+ WHERE datname = current_database()+ AND $1 = ANY(pg_blocking_pids(pid))+ )+ `, holderPID).Scan(&blocked); err != nil {+ t.Fatalf("observe blocked request: %v", err)+ }+ if blocked {+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatal("request did not queue behind the competing transaction")+}diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 5f6f0d192f..4927422311 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -1762,35 +1762,6 @@ func (q *Queries) LockIssueDuplicateKey(ctx context.Context, dollar_1 string) erreturn err}-const lockIssueForAttachmentWrite = `-- name: LockIssueForAttachmentWrite :one-SELECT id FROM issue-WHERE id = $1 AND workspace_id = $2-FOR NO KEY UPDATE-`--type LockIssueForAttachmentWriteParams struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`-}--// Owner-first guard for a write to one of an issue's attachments: take the-// issue before the attachment row, so a writer that reaches the same row-// through the issue β teardown's issue_id cascade, or the revision bump this-// write itself performs β either waits for this transaction or is waited on,-// never both.-//-// FOR NO KEY UPDATE, the mode of that revision bump, is the weakest mode that-// actually serializes issue writers. FOR KEY SHARE is NOT enough: it is-// compatible with FOR NO KEY UPDATE (see LockLiveComment), so a concurrent-// CreateComment would take the issue anyway, wait on the attachment this-// transaction holds, and deadlock with its bump.-func (q *Queries) LockIssueForAttachmentWrite(ctx context.Context, arg LockIssueForAttachmentWriteParams) (pgtype.UUID, error) {- row := q.db.QueryRow(ctx, lockIssueForAttachmentWrite, arg.ID, arg.WorkspaceID)- var id pgtype.UUID- err := row.Scan(&id)- return id, err-}-const lockIssueForChannelMediaBind = `-- name: LockIssueForChannelMediaBind :oneSELECT id FROM issueWHERE id = $1 AND workspace_id = $2@@ -1889,6 +1860,32 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIssreturn i, err}+const lockIssueForWrite = `-- name: LockIssueForWrite :one+SELECT id FROM issue+WHERE id = $1 AND workspace_id = $2+FOR NO KEY UPDATE+`++type LockIssueForWriteParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Lock the issue before writing an attachment or reaction row, matching the+// order used by issue teardown. This also lets concurrent duplicate reaction+// adds wait before AddIssueReaction takes its statement snapshot.+//+// FOR NO KEY UPDATE conflicts with issue revision bumps and still allows+// foreign-key checks. FOR KEY SHARE would let a concurrent CreateComment+// lock the issue while waiting for an attachment that this transaction+// holds, deadlocking when this transaction tries to bump the revision.+func (q *Queries) LockIssueForWrite(ctx context.Context, arg LockIssueForWriteParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockIssueForWrite, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}+const lockIssuesForDuplicateMark = `-- name: LockIssuesForDuplicateMark :manySELECT i.id,(i.status = 'cancelled' AND EXISTS (diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex abab4eb66c..3a104bc613 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -93,18 +93,15 @@ SELECT id FROM issueWHERE id = $1 AND workspace_id = $2FOR KEY SHARE;--- name: LockIssueForAttachmentWrite :one--- Owner-first guard for a write to one of an issue's attachments: take the--- issue before the attachment row, so a writer that reaches the same row--- through the issue β teardown's issue_id cascade, or the revision bump this--- write itself performs β either waits for this transaction or is waited on,--- never both.+-- name: LockIssueForWrite :one+-- Lock the issue before writing an attachment or reaction row, matching the+-- order used by issue teardown. This also lets concurrent duplicate reaction+-- adds wait before AddIssueReaction takes its statement snapshot.----- FOR NO KEY UPDATE, the mode of that revision bump, is the weakest mode that--- actually serializes issue writers. FOR KEY SHARE is NOT enough: it is--- compatible with FOR NO KEY UPDATE (see LockLiveComment), so a concurrent--- CreateComment would take the issue anyway, wait on the attachment this--- transaction holds, and deadlock with its bump.+-- FOR NO KEY UPDATE conflicts with issue revision bumps and still allows+-- foreign-key checks. FOR KEY SHARE would let a concurrent CreateComment+-- lock the issue while waiting for an attachment that this transaction+-- holds, deadlocking when this transaction tries to bump the revision.SELECT id FROM issueWHERE id = $1 AND workspace_id = $2FOR NO KEY UPDATE;