Skip to content

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

Go

fix(handler): serialize project resource read-modify-write with a row lock (#9240)

小七f9b3065ae1ae
diff --git a/server/internal/handler/project.go b/server/internal/handler/project.go
index 4739de5916..d85a129d67 100644
--- a/server/internal/handler/project.go
+++ b/server/internal/handler/project.go
@@ -384,7 +384,7 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {
// run — caught only later, by the claim gate cancelling the task.
// It writes its own 422; it runs before the transaction, so a
// rejection leaves nothing behind.
- if !h.requireWorktreeCapableDaemon(w, r, wsUUID, res.ResourceType, ref) {
+ if !requireWorktreeCapableDaemon(w, r, h.Queries, wsUUID, res.ResourceType, ref) {
return
}
}
diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.go
index 525a6fb7e0..4cb5d6b643 100644
--- a/server/internal/handler/project_resource.go
+++ b/server/internal/handler/project_resource.go
@@ -163,7 +163,14 @@ type localDirectoryRef struct {
// Returns true to proceed; on false the 422 response has already been written,
// using the same daemon_version_unsupported code as the quick-create gate so
// clients can branch on it.
-func (h *Handler) requireWorktreeCapableDaemon(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, resourceType string, normalizedRef json.RawMessage) bool {
+//
+// Queries arrive as a parameter rather than off the handler: the update path
+// calls this while its transaction holds the resource row lock, and a
+// handler-level read would borrow a second connection from the pool for every
+// locked request — enough concurrent updates would drain the pool into
+// deadlock. Passing the caller's queries (the transaction there, the pool on
+// tx-free create paths) keeps every read on one connection.
+func requireWorktreeCapableDaemon(w http.ResponseWriter, r *http.Request, q *db.Queries, workspaceID pgtype.UUID, resourceType string, normalizedRef json.RawMessage) bool {
if resourceType != "local_directory" {
return true
}
@@ -175,7 +182,7 @@ func (h *Handler) requireWorktreeCapableDaemon(w http.ResponseWriter, r *http.Re
// One machine hosts one runtime row per provider, all registered by the
// same daemon binary. A workspace has a handful of runtimes; the unfiltered
// list is a tiny read.
- runtimes, err := h.Queries.ListAgentRuntimes(r.Context(), workspaceID)
+ runtimes, err := q.ListAgentRuntimes(r.Context(), workspaceID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to check runtime capabilities")
return false
@@ -569,7 +576,7 @@ func (h *Handler) CreateProjectResource(w http.ResponseWriter, r *http.Request)
return
}
- if conflict, err := h.findLocalDirectoryConflict(r.Context(), project.ID, req.ResourceType, normalizedRef, pgtype.UUID{}); err != nil {
+ if conflict, err := findLocalDirectoryConflict(r.Context(), h.Queries, project.ID, req.ResourceType, normalizedRef, pgtype.UUID{}); err != nil {
writeError(w, http.StatusInternalServerError, "failed to check existing resources")
return
} else if conflict {
@@ -577,7 +584,7 @@ func (h *Handler) CreateProjectResource(w http.ResponseWriter, r *http.Request)
return
}
- if !h.requireWorktreeCapableDaemon(w, r, project.WorkspaceID, req.ResourceType, normalizedRef) {
+ if !requireWorktreeCapableDaemon(w, r, h.Queries, project.WorkspaceID, req.ResourceType, normalizedRef) {
return
}
@@ -644,7 +651,21 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
return
}
- existing, err := h.Queries.GetProjectResourceInWorkspace(r.Context(), db.GetProjectResourceInWorkspaceParams{
+ // The read-decide-write flow below derives every column it writes back
+ // from the row read here. Two concurrent partial updates would otherwise
+ // interleave read→read→write→write, and the second writer's stale snapshot
+ // would silently revert the first writer's change (#9238). Taking the row
+ // lock at read time inside a short transaction serializes competitors:
+ // they block on this row until the write commits, then re-read fresh.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start update transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ existing, err := qtx.GetProjectResourceInWorkspaceForUpdate(r.Context(), db.GetProjectResourceInWorkspaceForUpdateParams{
ID: resourceUUID, WorkspaceID: project.WorkspaceID,
})
if err != nil {
@@ -676,7 +697,11 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
nextRef = normalized
}
- if conflict, err := h.findLocalDirectoryConflict(r.Context(), project.ID, existing.ResourceType, nextRef, existing.ID); err != nil {
+ // Both checks read through the transaction (qtx) rather than the handler's
+ // pool queries: this request holds the resource row lock until commit, and
+ // a pool-level read would borrow a second connection per locked request,
+ // draining the pool under enough concurrent updates.
+ if conflict, err := findLocalDirectoryConflict(r.Context(), qtx, project.ID, existing.ResourceType, nextRef, existing.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to check existing resources")
return
} else if conflict {
@@ -697,7 +722,7 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
// after the mode was legitimately saved. The row already says worktree; the
// claim gate is what stops it from running somewhere that cannot.
if refProvided && !refRenameOnly {
- if !h.requireWorktreeCapableDaemon(w, r, project.WorkspaceID, existing.ResourceType, nextRef) {
+ if !requireWorktreeCapableDaemon(w, r, qtx, project.WorkspaceID, existing.ResourceType, nextRef) {
return
}
}
@@ -784,7 +809,7 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
}
}
- updated, err := h.Queries.UpdateProjectResource(r.Context(), db.UpdateProjectResourceParams{
+ updated, err := qtx.UpdateProjectResource(r.Context(), db.UpdateProjectResourceParams{
ID: existing.ID,
ResourceRef: nextRef,
Label: nextLabel,
@@ -798,6 +823,10 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to update project resource")
return
}
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update project resource")
+ return
+ }
resp := projectResourceToResponse(updated)
h.publish(
@@ -823,7 +852,12 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
// through. We do the daemon-scoped check here in application code instead.
//
// `excludeID` lets the update path ignore the row being edited.
-func (h *Handler) findLocalDirectoryConflict(ctx context.Context, projectID pgtype.UUID, resourceType string, normalizedRef json.RawMessage, excludeID pgtype.UUID) (bool, error) {
+//
+// Like requireWorktreeCapableDaemon, the read goes through the passed queries
+// so the update path can run it on its transaction: a handler-level read while
+// the transaction holds the row lock would borrow a second pooled connection
+// per locked request.
+func findLocalDirectoryConflict(ctx context.Context, q *db.Queries, projectID pgtype.UUID, resourceType string, normalizedRef json.RawMessage, excludeID pgtype.UUID) (bool, error) {
if resourceType != "local_directory" {
return false, nil
}
@@ -831,7 +865,7 @@ func (h *Handler) findLocalDirectoryConflict(ctx context.Context, projectID pgty
if err := json.Unmarshal(normalizedRef, &incoming); err != nil {
return false, err
}
- rows, err := h.Queries.ListProjectResources(ctx, projectID)
+ rows, err := q.ListProjectResources(ctx, projectID)
if err != nil {
return false, err
}
diff --git a/server/internal/handler/project_resource_partial_update_test.go b/server/internal/handler/project_resource_partial_update_test.go
new file mode 100644
index 0000000000..95ddabbb69
--- /dev/null
+++ b/server/internal/handler/project_resource_partial_update_test.go
@@ -0,0 +1,240 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// resourceReadPauseDB pauses the non-transactional read path, so the racing
+// update test also exercises (and fails on) the pre-fix code that reads
+// outside a transaction.
+type resourceReadPauseDB struct {
+ db.DBTX
+ paused, release chan struct{}
+}
+
+func (d resourceReadPauseDB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {
+ row := d.DBTX.QueryRow(ctx, query, args...)
+ // Prefix (not equality): matches both the plain read and the
+ // FOR UPDATE variant added by the fix, whichever the handler uses.
+ if strings.HasPrefix(query, "-- name: GetProjectResourceInWorkspace") {
+ return &contextLockPauseRow{Row: row, paused: d.paused, release: d.release}
+ }
+ return row
+}
+
+// pausedUpdateHandler returns a copy of the test handler whose project
+// resource read pauses until resume is called: on the pre-fix code the pause
+// sits in the plain read, with the fix it sits in the FOR UPDATE read inside
+// the transaction — the prefix match in resourceReadPauseDB and the
+// contextLockTestStarter cover both shapes.
+func pausedUpdateHandler(paused, release chan struct{}) *Handler {
+ h := *testHandler
+ h.Queries = db.New(resourceReadPauseDB{DBTX: testPool, paused: paused, release: release})
+ h.TxStarter = &contextLockTestStarter{
+ pool: testPool, pauseAfter: "GetProjectResourceInWorkspaceForUpdate",
+ paused: paused, release: release,
+ }
+ return &h
+}
+
+// waitRefRequestGated makes the two-request race deterministic: it returns
+// only once the racing ref-only update has either completed outright or is
+// blocked inside its FOR UPDATE read waiting for the paused request's row
+// lock. The paused request is resumed only after that point, so the write
+// order is fixed instead of left to the scheduler.
+//
+// Which of the two happens separates the worlds. On the pre-fix code nothing
+// blocks the ref request: it reads and writes while the paused request holds
+// no lock, so its write has already landed when this returns, and the resumed
+// write (derived from a stale snapshot) reverts it — the assertion fails. On
+// the serialized code the ref request cannot complete: its FOR UPDATE read
+// waits for the row lock the paused request holds, visible the way a DBA
+// would see it, as wait_event_type='Lock' on the backend running that query.
+// The pre-fix code never issues that query, so the lock signal cannot fire
+// and completion is the only exit — the two outcomes are mutually exclusive
+// rather than timing-dependent. Completion needs no deadline (however slow,
+// it is observed); the deadline only bounds the fixed-world wait for the
+// blocked backend to show up.
+func waitRefRequestGated(t *testing.T, ctx context.Context, done <-chan error) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case <-done:
+ return
+ default:
+ }
+ var lockWaiters int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity
+WHERE wait_event_type = 'Lock' AND query LIKE '%GetProjectResourceInWorkspaceForUpdate%'`).Scan(&lockWaiters); err == nil && lockWaiters > 0 {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("ref update neither completed nor became blocked on the row lock")
+}
+
+// runConcurrentPartialUpdate starts a label-only update that pauses right
+// after its row read, starts the caller's ref-only update against the real
+// handler, and releases the paused request only once the race outcome is
+// decided. Both recorders must end at 200.
+func runConcurrentPartialUpdate(t *testing.T, ctx context.Context, projectID, resourceID string, refBody map[string]any) {
+ t.Helper()
+
+ paused, release := make(chan struct{}), make(chan struct{})
+ h := pausedUpdateHandler(paused, release)
+ var releaseOnce sync.Once
+ resume := func() { releaseOnce.Do(func() { close(release) }) }
+ defer resume()
+
+ recA := httptest.NewRecorder()
+ reqA := withURLParams(newRequest("PUT", "/api/projects/"+projectID+"/resources/"+resourceID,
+ map[string]any{"label": "New label"}), "id", projectID, "resourceId", resourceID)
+ doneA := make(chan error, 1)
+ go func() {
+ h.UpdateProjectResource(recA, reqA)
+ doneA <- nil
+ }()
+ waitContextLockSignal(t, paused, "label update did not read resource")
+
+ recB := httptest.NewRecorder()
+ reqB := withURLParams(newRequest("PUT", "/api/projects/"+projectID+"/resources/"+resourceID,
+ map[string]any{"resource_ref": refBody}), "id", projectID, "resourceId", resourceID)
+ doneB := make(chan error, 1)
+ go func() {
+ testHandler.UpdateProjectResource(recB, reqB)
+ doneB <- nil
+ // Closed after the send so both observers of this channel —
+ // waitRefRequestGated's completion probe and the final wait below —
+ // can receive without draining each other: once closed, every
+ // receive returns immediately.
+ close(doneB)
+ }()
+
+ waitRefRequestGated(t, ctx, doneB)
+ resume()
+ waitContextLockResult(t, doneA, "label-only update")
+ waitContextLockResult(t, doneB, "ref update")
+ if recA.Code != http.StatusOK {
+ t.Fatalf("label-only update status = %d, want 200", recA.Code)
+ }
+ if recB.Code != http.StatusOK {
+ t.Fatalf("ref update status = %d, want 200", recB.Code)
+ }
+}
+
+// storedProjectResource reads the row back after both updates settled.
+func storedProjectResource(t *testing.T, ctx context.Context, resourceID string) db.ProjectResource {
+ t.Helper()
+ stored, err := testHandler.Queries.GetProjectResourceInWorkspace(ctx, db.GetProjectResourceInWorkspaceParams{
+ ID: parseUUID(resourceID), WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return stored
+}
+
+// TestUpdateProjectResourceConcurrentPartialUpdate serializes a label-only
+// update and a ref-only update at the read edge: the label request pauses
+// right after reading the row, the ref request is only released once it has
+// either completed (pre-fix code) or blocked on the row lock (fix), then the
+// label request resumes. The persisted row must keep the ref update — the
+// reader's stale snapshot must not silently revert a field it never received
+// (#9238). With the fix, the reader holds the row lock from its FOR UPDATE
+// read until commit, so the ref request waits and re-reads after the label
+// write lands.
+func TestUpdateProjectResourceConcurrentPartialUpdate(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ projectID := dbfx.Project(t, "racing project")
+ resourceID := dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "github_repo",
+ "resource_ref": `{"url":"https://github.com/example/repo","ref":"main"}`,
+ "label": "Old label",
+ "position": 1,
+ })
+
+ runConcurrentPartialUpdate(t, ctx, projectID, resourceID, map[string]any{
+ "url": "https://github.com/example/repo", "ref": "release",
+ })
+
+ stored := storedProjectResource(t, ctx, resourceID)
+ var ref struct {
+ Ref string `json:"ref"`
+ }
+ if err := json.Unmarshal(stored.ResourceRef, &ref); err != nil {
+ t.Fatalf("stored ref %s: %v", stored.ResourceRef, err)
+ }
+ if ref.Ref != "release" {
+ t.Errorf("stored ref = %q, want the concurrent ref update (release)", ref.Ref)
+ }
+ if !stored.Label.Valid || stored.Label.String != "New label" {
+ t.Errorf("stored label = %v, want New label", stored.Label)
+ }
+ if stored.Position != 1 {
+ t.Errorf("stored position = %d, want 1", stored.Position)
+ }
+}
+
+// TestUpdateProjectResourceConcurrentLabelMirrorVsExecutionMode covers the
+// same stale-snapshot race through the local_directory label-mirror write: a
+// label-only update races an execution_mode update, and the mirror step
+// rewrites the whole ref from the row the label request read. The persisted
+// ref must keep the racing mode change — a stale ref snapshot must not carry
+// the old execution_mode back in behind a rename (#9238). With the fix the
+// label request writes first and the mode request re-reads, so its ref (which
+// intentionally omits execution_mode, i.e. in_place) lands last.
+func TestUpdateProjectResourceConcurrentLabelMirrorVsExecutionMode(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ projectID := dbfx.Project(t, "racing local directory project")
+ resourceID := dbfx.Insert(t, "project_resource", testutil.Cols{
+ "project_id": projectID,
+ "workspace_id": testWorkspaceID,
+ "resource_type": "local_directory",
+ "resource_ref": `{"local_path":"/repo","daemon_id":"daemon-1","execution_mode":"worktree"}`,
+ "label": "Old label",
+ "position": 1,
+ })
+
+ runConcurrentPartialUpdate(t, ctx, projectID, resourceID, map[string]any{
+ "local_path": "/repo", "daemon_id": "daemon-1",
+ })
+
+ stored := storedProjectResource(t, ctx, resourceID)
+ var ref struct {
+ ExecutionMode string `json:"execution_mode"`
+ }
+ if err := json.Unmarshal(stored.ResourceRef, &ref); err != nil {
+ t.Fatalf("stored ref %s: %v", stored.ResourceRef, err)
+ }
+ if ref.ExecutionMode != "" {
+ t.Errorf("stored execution_mode = %q, want the concurrent mode update (cleared = in_place)", ref.ExecutionMode)
+ }
+ if !stored.Label.Valid || stored.Label.String != "New label" {
+ t.Errorf("stored label = %v, want New label", stored.Label)
+ }
+ if stored.Position != 1 {
+ t.Errorf("stored position = %d, want 1", stored.Position)
+ }
+}
diff --git a/server/pkg/db/generated/project_resource.sql.go b/server/pkg/db/generated/project_resource.sql.go
index 1818c28109..e6180a7f64 100644
--- a/server/pkg/db/generated/project_resource.sql.go
+++ b/server/pkg/db/generated/project_resource.sql.go
@@ -155,6 +155,37 @@ func (q *Queries) GetProjectResourceInWorkspace(ctx context.Context, arg GetProj
return i, err
}
+const getProjectResourceInWorkspaceForUpdate = `-- name: GetProjectResourceInWorkspaceForUpdate :one
+SELECT id, project_id, workspace_id, resource_type, resource_ref, label, position, created_at, created_by FROM project_resource
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type GetProjectResourceInWorkspaceForUpdateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Same row as GetProjectResourceInWorkspace, but takes a row lock held until
+// the caller's transaction ends, serializing the read-decide-write flow in
+// UpdateProjectResource against competing partial updates (#9238).
+func (q *Queries) GetProjectResourceInWorkspaceForUpdate(ctx context.Context, arg GetProjectResourceInWorkspaceForUpdateParams) (ProjectResource, error) {
+ row := q.db.QueryRow(ctx, getProjectResourceInWorkspaceForUpdate, arg.ID, arg.WorkspaceID)
+ var i ProjectResource
+ err := row.Scan(
+ &i.ID,
+ &i.ProjectID,
+ &i.WorkspaceID,
+ &i.ResourceType,
+ &i.ResourceRef,
+ &i.Label,
+ &i.Position,
+ &i.CreatedAt,
+ &i.CreatedBy,
+ )
+ return i, err
+}
+
const listProjectResources = `-- name: ListProjectResources :many
SELECT id, project_id, workspace_id, resource_type, resource_ref, label, position, created_at, created_by FROM project_resource
WHERE project_id = $1
diff --git a/server/pkg/db/queries/project_resource.sql b/server/pkg/db/queries/project_resource.sql
index 7050fecfe2..8eb1b33330 100644
--- a/server/pkg/db/queries/project_resource.sql
+++ b/server/pkg/db/queries/project_resource.sql
@@ -24,6 +24,14 @@ WHERE id = $1;
SELECT * FROM project_resource
WHERE id = $1 AND workspace_id = $2;
+-- name: GetProjectResourceInWorkspaceForUpdate :one
+-- Same row as GetProjectResourceInWorkspace, but takes a row lock held until
+-- the caller's transaction ends, serializing the read-decide-write flow in
+-- UpdateProjectResource against competing partial updates (#9238).
+SELECT * FROM project_resource
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: CreateProjectResource :one
INSERT INTO project_resource (
project_id, workspace_id, resource_type, resource_ref, label, position, created_by