Skip to content

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

Go

fix(issues): keep fields a concurrent update set when changing others (#11492)

pseudoyube60962fe400
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index c65ae9faf1..d569881c08 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -262,15 +262,11 @@ func assertIssueStatusStillActive(ctx context.Context, qtx *db.Queries, workspac
return nil
}
-// runWithIssueStatusGuard runs an issue write that lands on a custom status
-// inside a transaction that re-verifies the status under the shared catalog
-// lock (see assertIssueStatusStillActive). Request writes also carry trusted
-// wakeup actor identity in transaction-local settings, including built-in targets.
+// runWithIssueStatusGuard runs an issue write inside a transaction that
+// re-verifies a custom status under the shared catalog lock (see
+// assertIssueStatusStillActive). Request writes also carry trusted wakeup actor
+// identity in transaction-local settings.
func (h *Handler) runWithIssueStatusGuard(ctx context.Context, workspaceID pgtype.UUID, statusKey string, fn func(q *db.Queries) error) error {
- _, hasActor := ctx.Value(wakeupActorKey{}).(wakeupActor)
- if !hasActor && (statusKey == "" || issuestatus.IsBuiltIn(statusKey)) {
- return fn(h.Queries)
- }
tx, err := h.beginWakeupWrite(ctx)
if err != nil {
return err
@@ -287,9 +283,11 @@ func (h *Handler) runWithIssueStatusGuard(ctx context.Context, workspaceID pgtyp
return tx.Commit(ctx)
}
-// updateIssueWithStatusGuard writes params under the status-archive guard.
-func (h *Handler) updateIssueWithStatusGuard(ctx context.Context, workspaceID pgtype.UUID, statusKey string, params db.UpdateIssueParams) (db.Issue, error) {
- var issue db.Issue
+// updateIssueWithStatusGuard writes params under the status-archive guard,
+// leaving fields rawFields does not name as the locked row has them. It returns
+// the written issue and the row it replaced.
+func (h *Handler) updateIssueWithStatusGuard(ctx context.Context, workspaceID pgtype.UUID, statusKey string, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, workflowAssignee bool) (db.Issue, db.Issue, error) {
+ var issue, current db.Issue
var cancelledWakeups []db.AgentTaskQueue
err := h.runWithIssueStatusGuard(ctx, workspaceID, statusKey, func(q *db.Queries) error {
if params.DuplicateOfIssueID.Valid {
@@ -298,14 +296,33 @@ func (h *Handler) updateIssueWithStatusGuard(ctx context.Context, workspaceID pg
}
}
var innerErr error
+ current, innerErr = lockIssueForFieldUpdate(ctx, q, workspaceID, &params, rawFields, workflowAssignee)
+ if innerErr != nil {
+ return innerErr
+ }
issue, cancelledWakeups, innerErr = updateIssueStoppingWakeups(ctx, q, params)
return innerErr
})
if err != nil {
- return issue, err
+ return issue, current, err
}
h.broadcastCancelledWakeups(ctx, workspaceID, cancelledWakeups)
- return issue, nil
+ return issue, current, nil
+}
+
+// lockIssueForFieldUpdate locks the issue row for the rest of the transaction
+// and takes the nullable fields rawFields does not name from it, so a write
+// that waited behind another one does not put that one's fields back.
+func lockIssueForFieldUpdate(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, params *db.UpdateIssueParams, rawFields map[string]json.RawMessage, workflowAssignee bool) (db.Issue, error) {
+ current, err := q.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
+ ID: params.ID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return db.Issue{}, fmt.Errorf("lock issue for update: %w", err)
+ }
+ refreshUntouchedNullableIssueParams(params, current, rawFields, workflowAssignee)
+ return current, nil
}
// updateIssueStoppingWakeups writes params and, when the write moves the issue
@@ -4398,7 +4415,11 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
prevIssue = lockedPrev
}
} else {
- issue, err = h.updateIssueWithStatusGuard(writeCtx, prevIssue.WorkspaceID, statusKeyForGuard, params)
+ var lockedPrev db.Issue
+ issue, lockedPrev, err = h.updateIssueWithStatusGuard(writeCtx, prevIssue.WorkspaceID, statusKeyForGuard, params, rawFields, handoff != nil)
+ if lockedPrev.ID.Valid {
+ prevIssue = lockedPrev
+ }
}
if err != nil {
if writeIssueBlockerError(w, err) {
@@ -5322,7 +5343,11 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
prevIssue = lockedPrev
}
case labelPlan == nil && propertyPlan == nil:
- issue, err = h.updateIssueWithStatusGuard(writeCtx, wsUUID, issueStatusGuard, params)
+ var lockedPrev db.Issue
+ issue, lockedPrev, err = h.updateIssueWithStatusGuard(writeCtx, wsUUID, issueStatusGuard, params, rawUpdates, handoff != nil)
+ if err == nil {
+ prevIssue = lockedPrev
+ }
default:
var fieldParams *db.UpdateIssueParams
if hasFieldUpdate {
@@ -5331,7 +5356,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
issueStatusGuard = ""
}
var written batchIssueWrite
- written, err = h.writeBatchIssue(writeCtx, wsUUID, prevIssue, fieldParams, issueStatusGuard, labelPlan, propertyPlan)
+ written, err = h.writeBatchIssue(writeCtx, wsUUID, prevIssue, fieldParams, rawUpdates, handoff != nil, issueStatusGuard, labelPlan, propertyPlan)
+ if err == nil {
+ prevIssue = written.prev
+ }
issue, labelsChanged, propertiesChanged = written.issue, written.labelsChanged, written.propertiesChanged
}
if err != nil {
diff --git a/server/internal/handler/issue_batch.go b/server/internal/handler/issue_batch.go
index 754104e638..2db3d9350f 100644
--- a/server/internal/handler/issue_batch.go
+++ b/server/internal/handler/issue_batch.go
@@ -242,6 +242,7 @@ func (h *Handler) resolveBatchPropertyPlan(w http.ResponseWriter, r *http.Reques
type batchIssueWrite struct {
issue db.Issue
+ prev db.Issue
labelsChanged bool
propertiesChanged bool
}
@@ -249,8 +250,8 @@ type batchIssueWrite struct {
// writeBatchIssue applies one issue's field update, label operations and
// property operations in a single transaction, so an issue is either written
// in full or skipped in full. params is nil when the batch changes no field.
-func (h *Handler) writeBatchIssue(ctx context.Context, workspaceID pgtype.UUID, prev db.Issue, params *db.UpdateIssueParams, statusKey string, labels *batchLabelPlan, properties *batchPropertyPlan) (batchIssueWrite, error) {
- out := batchIssueWrite{issue: prev}
+func (h *Handler) writeBatchIssue(ctx context.Context, workspaceID pgtype.UUID, prev db.Issue, params *db.UpdateIssueParams, rawFields map[string]json.RawMessage, workflowAssignee bool, statusKey string, labels *batchLabelPlan, properties *batchPropertyPlan) (batchIssueWrite, error) {
+ out := batchIssueWrite{issue: prev, prev: prev}
tx, err := h.beginWakeupWrite(ctx)
if err != nil {
return out, err
@@ -273,6 +274,10 @@ func (h *Handler) writeBatchIssue(ctx context.Context, workspaceID pgtype.UUID,
var cancelled []db.AgentTaskQueue
if params != nil {
+ out.prev, err = lockIssueForFieldUpdate(ctx, q, workspaceID, params, rawFields, workflowAssignee)
+ if err != nil {
+ return out, err
+ }
out.issue, cancelled, err = updateIssueStoppingWakeups(ctx, q, *params)
if err != nil {
return out, err
diff --git a/server/internal/handler/issue_concurrent_update_test.go b/server/internal/handler/issue_concurrent_update_test.go
new file mode 100644
index 0000000000..1233d285cc
--- /dev/null
+++ b/server/internal/handler/issue_concurrent_update_test.go
@@ -0,0 +1,145 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// A write that names only some fields must leave the others as a concurrent
+// write left them. The update statement takes nullable fields as bare values,
+// so a write that filled them in before waiting on the row would put the old
+// assignee, dates, parent, project and stage back.
+func TestConcurrentUpdateKeepsFieldsItDoesNotName(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ batch := func(updates map[string]any, extra map[string]any) func(string) *httptest.ResponseRecorder {
+ return func(issueID string) *httptest.ResponseRecorder {
+ body := map[string]any{"issue_ids": []string{issueID}, "updates": updates}
+ for k, v := range extra {
+ body[k] = v
+ }
+ w := httptest.NewRecorder()
+ testHandler.BatchUpdateIssues(w, newRequest("POST", "/api/issues/batch-update", body))
+ return w
+ }
+ }
+ label := dbfx.Insert(t, "issue_label", testutil.Cols{
+ "workspace_id": testWorkspaceID, "name": "concurrent-update", "color": "#ff0000",
+ })
+ for name, write := range map[string]func(issueID string) *httptest.ResponseRecorder{
+ "single": func(issueID string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ testHandler.UpdateIssue(w, updateIssueRequest(issueID, map[string]any{"priority": "high"}))
+ return w
+ },
+ "batch": batch(map[string]any{"priority": "high"}, nil),
+ "batch with labels": batch(map[string]any{"priority": "high"}, map[string]any{
+ "labels": map[string]any{"add": []string{label}},
+ }),
+ "public api content": func(issueID string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ issue, err := testHandler.Queries.GetIssue(context.Background(), parseUUID(issueID))
+ if err == nil {
+ title := "renamed"
+ _, err = testHandler.IssueService.UpdateContent(context.Background(), issue, service.IssueContentPatch{Title: &title})
+ }
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ return w
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ parent := dbfx.Issue(t, "concurrent-update-parent")
+ issueID := dbfx.Issue(t, "concurrent-update")
+ project := dbfx.Insert(t, "project", testutil.Cols{"workspace_id": testWorkspaceID, "title": "concurrent-update"})
+
+ var mu sync.Mutex
+ var payloads []map[string]any
+ testHandler.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ if resp, ok := payload["issue"].(IssueResponse); ok && resp.ID == issueID {
+ mu.Lock()
+ payloads = append(payloads, payload)
+ mu.Unlock()
+ }
+ })
+
+ // Hold the other write open so the one under test reads the old row
+ // and then waits for this one.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(context.Background())
+ var pid int
+ if err := tx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tx.Exec(ctx, `UPDATE issue SET assignee_type = 'member', assignee_id = $2,
+ start_date = '2026-01-02', due_date = '2026-01-03', parent_issue_id = $3, project_id = $4, stage = 2
+ WHERE id = $1`, issueID, testUserID, parent, project); err != nil {
+ t.Fatal(err)
+ }
+
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() { done <- write(issueID) }()
+ blocked := false
+ for deadline := time.Now().Add(10 * time.Second); !blocked && time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ if err := testPool.QueryRow(ctx, `SELECT EXISTS (
+ SELECT 1 FROM pg_stat_activity WHERE $1::int = ANY(pg_blocking_pids(pid)))`, pid).Scan(&blocked); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case w := <-done:
+ if w.Code != http.StatusOK {
+ t.Fatalf("status %d: %s", w.Code, w.Body.String())
+ }
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+ if !blocked {
+ t.Fatal("the update never waited on the row, so the interleaving under test did not happen")
+ }
+
+ var got string
+ if err := testPool.QueryRow(ctx, `SELECT concat_ws(' ', assignee_type, assignee_id, start_date, due_date, parent_issue_id, project_id, stage)
+ FROM issue WHERE id = $1`, issueID).Scan(&got); err != nil {
+ t.Fatal(err)
+ }
+ if want := "member " + testUserID + " 2026-01-02 2026-01-03 " + parent + " " + project + " 2"; got != want {
+ t.Errorf("concurrent fields = %q, want %q", got, want)
+ }
+
+ // The other write announces its own changes.
+ mu.Lock()
+ defer mu.Unlock()
+ for _, payload := range payloads {
+ for _, key := range []string{"assignee_changed", "project_changed", "start_date_changed", "due_date_changed", "parent_changed", "stage_changed"} {
+ if payload[key] == true {
+ t.Errorf("%s = true for a write that did not touch it", key)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/issue_duplicate_maintenance_test.go b/server/internal/handler/issue_duplicate_maintenance_test.go
index ab67b2acc9..063d15f1a5 100644
--- a/server/internal/handler/issue_duplicate_maintenance_test.go
+++ b/server/internal/handler/issue_duplicate_maintenance_test.go
@@ -201,7 +201,7 @@ func concurrentWriteAfterPointerCleared(t *testing.T, deleteOriginal bool) {
SELECT 1 FROM pg_stat_activity
WHERE datname = current_database()
AND wait_event_type = 'Lock'
- AND query LIKE '-- name: UpdateIssue :one%')`).Scan(&blocked); err != nil {
+ AND query LIKE '-- name: LockIssueForDescriptionUpdate :one%')`).Scan(&blocked); err != nil {
t.Fatal(err)
}
if blocked {
diff --git a/server/internal/service/issue_public.go b/server/internal/service/issue_public.go
index 5e7c42e5c9..29ea3c701b 100644
--- a/server/internal/service/issue_public.go
+++ b/server/internal/service/issue_public.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
+ "fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -27,6 +28,21 @@ type IssueContentPatch struct {
// remain separate operations because each has additional policy and side
// effects.
func (s *IssueService) UpdateContent(ctx context.Context, issue db.Issue, patch IssueContentPatch) (db.Issue, error) {
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.Issue{}, fmt.Errorf("begin issue content update: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.Queries.WithTx(tx)
+ // The update writes these fields as given, so take them from the locked row:
+ // the caller's copy may predate a concurrent write.
+ issue, err = qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return db.Issue{}, fmt.Errorf("lock issue for content update: %w", err)
+ }
params := db.UpdateIssueParams{
ID: issue.ID,
AssigneeType: issue.AssigneeType,
@@ -47,9 +63,15 @@ func (s *IssueService) UpdateContent(ctx context.Context, issue db.Issue, patch
params.Description = pgtype.Text{String: *patch.Description, Valid: true}
}
- updated, err := s.Queries.UpdateIssue(ctx, params)
+ updated, err := qtx.UpdateIssue(ctx, params)
if patch.ExpectedRevision != nil && errors.Is(err, pgx.ErrNoRows) {
return db.Issue{}, ErrIssueRevisionConflict
}
- return updated, err
+ if err != nil {
+ return db.Issue{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.Issue{}, fmt.Errorf("commit issue content update: %w", err)
+ }
+ return updated, nil
}