Skip to content

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

Go

fix(agent-builder): serialise draft autosave against session delete (MUL-5642) (#6376)

Naiyuan Qing9fb46adc438a
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index 803108bedd..e29fb1bfbf 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -235,6 +235,16 @@ type SaveAgentBuilderDraftRequest struct {
// Whole-object last-write-wins is correct here because a conversation has one
// editor on one screen — a field-level merge could only reconstruct a state the
// user never saw.
+//
+// The upsert runs under LockChatSessionForDraftWrite, the row lock the delete
+// path already takes, and re-checks the session inside it. Unlocked, this
+// handler's read and its write are two statements a delete can commit between:
+// the client autosaves on a debounce, so a discard confirmed mid-window used to
+// leave a draft hanging off a session that no longer exists — invisible to the
+// UI, and reachable by no prune but the workspace teardown. agent_builder_draft
+// has no chat_session FK to reject that INSERT, so the lock is what makes the
+// two orderings the only ones: either the save commits first and the delete
+// prunes it, or the delete commits first and the save finds nothing to write to.
func (h *Handler) SaveAgentBuilderDraft(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
userID, ok := requireUserID(w, r)
@@ -262,15 +272,13 @@ func (h *Handler) SaveAgentBuilderDraft(w http.ResponseWriter, r *http.Request)
// Creator-only, and only for a builder carrier — the same two gates the
// runtime switch applies. Without the carrier check this would be a way to
- // hang arbitrary JSON off any chat session the caller owns.
+ // hang arbitrary JSON off any chat session the caller owns. Both are decided
+ // on this unlocked read: workspace, creator and carrier are immutable for a
+ // given session, so nothing the lock below could observe would change them.
session, ok := h.loadChatSessionForUser(w, r, userID, workspaceID, chi.URLParam(r, "sessionId"))
if !ok {
return
}
- if session.Status != "active" {
- writeError(w, http.StatusBadRequest, "chat session is archived")
- return
- }
agent, err := h.Queries.GetAgent(r.Context(), session.AgentID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to load chat agent")
@@ -281,14 +289,45 @@ func (h *Handler) SaveAgentBuilderDraft(w http.ResponseWriter, r *http.Request)
return
}
- if _, err := h.Queries.UpsertAgentBuilderDraft(r.Context(), db.UpsertAgentBuilderDraftParams{
- ChatSessionID: session.ID,
- WorkspaceID: session.WorkspaceID,
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent builder draft")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Everything a concurrent writer can still change about this session —
+ // whether it exists at all, and whether it is still active — is decided here,
+ // under the lock, on a re-read row. A save that blocked on a delete or an
+ // archive resumes holding the values it read before blocking, so the earlier
+ // read cannot be trusted for either.
+ locked, err := qtx.LockChatSessionForDraftWrite(r.Context(), session.ID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "chat session not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock chat session")
+ return
+ }
+ if locked.Status != "active" {
+ writeError(w, http.StatusBadRequest, "chat session is archived")
+ return
+ }
+
+ if _, err := qtx.UpsertAgentBuilderDraft(r.Context(), db.UpsertAgentBuilderDraftParams{
+ ChatSessionID: locked.ID,
+ WorkspaceID: locked.WorkspaceID,
Draft: req.Draft,
}); err != nil {
writeError(w, http.StatusInternalServerError, "failed to save agent builder draft")
return
}
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent builder draft")
+ return
+ }
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index bef4e5bdfb..5f80e76e96 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -563,6 +563,132 @@ func TestDeleteChatSessionPrunesTheBuilderDraft(t *testing.T) {
}
}
+// newSaveDraftRequest prepares a save the way saveBuilderDraft does but hands
+// the pieces back, so the two tests below can run the handler on their own
+// goroutine — both need a save in flight while another transaction holds the
+// session row.
+func newSaveDraftRequest(t *testing.T, sessionID string, draft any) (*httptest.ResponseRecorder, *http.Request) {
+ t.Helper()
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(),
+ `DELETE FROM agent_builder_draft WHERE chat_session_id = $1`, sessionID)
+ })
+ return httptest.NewRecorder(), withURLParams(
+ newRequest(http.MethodPut, "/api/agent-builder/sessions/"+sessionID+"/draft",
+ map[string]any{"draft": draft}),
+ "sessionId", sessionID,
+ )
+}
+
+func countBuilderDrafts(t *testing.T, sessionID string) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_builder_draft WHERE chat_session_id = $1
+ `, sessionID).Scan(&n); err != nil {
+ t.Fatalf("count stored drafts: %v", err)
+ }
+ return n
+}
+
+// runSaveDraftAgainst holds the session row in a transaction, runs `hold`
+// inside it, then starts a save and proves the save is waiting rather than
+// racing. Returns once the save has finished, after the transaction commits.
+//
+// Asserting that the save blocks is the point: before the fix it read the
+// session, sailed past the uncommitted transaction and wrote its row, so the
+// outcome depended on which statement won rather than on the lock.
+func runSaveDraftAgainst(t *testing.T, sessionID string, w *httptest.ResponseRecorder, req *http.Request, hold string) {
+ t.Helper()
+ ctx := context.Background()
+
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder transaction: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ // The same row and lock mode DeleteChatSession and SetChatSessionArchived
+ // take, as their transaction's first statement.
+ if _, err := tx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, sessionID); err != nil {
+ t.Fatalf("lock chat session: %v", err)
+ }
+ if _, err := tx.Exec(ctx, hold, sessionID); err != nil {
+ t.Fatalf("hold statement %q: %v", hold, err)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ testHandler.SaveAgentBuilderDraft(w, req)
+ }()
+
+ select {
+ case <-done:
+ t.Fatalf("save finished while the session row was held: %d %s", w.Code, w.Body.String())
+ case <-time.After(500 * time.Millisecond):
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit holder transaction: %v", err)
+ }
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("save never returned after the holder committed")
+ }
+}
+
+// The client autosaves on a debounce, so a save is routinely in flight when the
+// user confirms "Discard this draft" — and because the conversation is
+// addressable by URL, a second tab can autosave at any moment while this one
+// discards. Unlocked, the save's read and its write straddled the delete: the
+// upsert landed after the conversation was gone, and agent_builder_draft has no
+// chat_session FK to reject it. What survived was the configuration the user had
+// just explicitly discarded, invisible to the UI and reachable by no prune but
+// the workspace teardown.
+func TestSaveAgentBuilderDraftLosesToAConcurrentDelete(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ // Deliberately no draft saved first. A pre-existing row would make the
+ // upsert contend on that row's own lock, and the test would pass for a
+ // reason that has nothing to do with the session lock under test.
+ w, req := newSaveDraftRequest(t, session.SessionID, map[string]any{"name": "Discarded"})
+
+ runSaveDraftAgainst(t, session.SessionID, w, req,
+ `DELETE FROM chat_session WHERE id = $1`)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("save after the conversation was deleted: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+ if n := countBuilderDrafts(t, session.SessionID); n != 0 {
+ t.Fatalf("orphaned draft rows = %d, want 0", n)
+ }
+}
+
+// Same race against the other writer of chat_session.status. Creating the agent
+// archives the conversation, and the studio's last autosave can still be in
+// flight — an unlocked status check let it write a draft onto a session that is
+// already read-only, where the drafts list will never show it again.
+func TestSaveAgentBuilderDraftLosesToAConcurrentArchive(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ w, req := newSaveDraftRequest(t, session.SessionID, map[string]any{"name": "Too late"})
+
+ runSaveDraftAgainst(t, session.SessionID, w, req,
+ `UPDATE chat_session SET status = 'archived' WHERE id = $1`)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("save after the conversation was archived: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ if n := countBuilderDrafts(t, session.SessionID); n != 0 {
+ t.Fatalf("draft rows on an archived conversation = %d, want 0", n)
+ }
+}
+
// A rebind moves the carrier without touching chat_session.runtime_id, which is
// deliberately left stale as the daemon's resume pointer. Reading the list from
// that column instead of the carrier would resume the conversation onto a
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 84e4dd994d..a77a0932c4 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -1589,6 +1589,56 @@ func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID)
return id_2, err
}
+const lockChatSessionForDraftWrite = `-- name: LockChatSessionForDraftWrite :one
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+WHERE id = $1
+FOR UPDATE
+`
+
+// The autosave half of the agent_builder_draft protocol, and the writer's
+// answer to LockChatSessionForDelete.
+//
+// agent_builder_draft carries no chat_session FK (repo rule), so an INSERT into
+// it takes no lock on the parent row and nothing stops a draft from landing
+// after its conversation is gone: the save path read the session, the delete
+// transaction then committed, and the upsert still succeeded — leaving a row
+// the user explicitly discarded, invisible to the UI and unreachable by every
+// prune except the workspace teardown. The FK that would have rejected that
+// INSERT is the one we are not allowed to have, so the lock replaces it.
+//
+// Returns the whole row, not just the id: the caller must re-check creator and
+// status INSIDE the transaction, because a save blocked here resumes holding
+// values it read before blocking (the same reason the runtime-bind path re-reads
+// the agent under its lock).
+//
+// Same row and same lock mode as LockChatSessionForDelete and
+// LockChatSessionForRuntimeBind, taken as the transaction's first statement, so
+// no ordering against the repo-wide chat_session -> agent_task_queue sequence is
+// introduced and none of the three can deadlock against each other.
+func (q *Queries) LockChatSessionForDraftWrite(ctx context.Context, id pgtype.UUID) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForDraftWrite, id)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ )
+ return i, err
+}
+
const lockChatSessionForRuntimeBind = `-- name: LockChatSessionForRuntimeBind :one
SELECT id FROM chat_session
WHERE id = $1
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 89c0ade4a3..84c1aa5b95 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -295,6 +295,31 @@ SELECT id FROM chat_session
WHERE id = $1
FOR UPDATE;
+-- name: LockChatSessionForDraftWrite :one
+-- The autosave half of the agent_builder_draft protocol, and the writer's
+-- answer to LockChatSessionForDelete.
+--
+-- agent_builder_draft carries no chat_session FK (repo rule), so an INSERT into
+-- it takes no lock on the parent row and nothing stops a draft from landing
+-- after its conversation is gone: the save path read the session, the delete
+-- transaction then committed, and the upsert still succeeded — leaving a row
+-- the user explicitly discarded, invisible to the UI and unreachable by every
+-- prune except the workspace teardown. The FK that would have rejected that
+-- INSERT is the one we are not allowed to have, so the lock replaces it.
+--
+-- Returns the whole row, not just the id: the caller must re-check creator and
+-- status INSIDE the transaction, because a save blocked here resumes holding
+-- values it read before blocking (the same reason the runtime-bind path re-reads
+-- the agent under its lock).
+--
+-- Same row and same lock mode as LockChatSessionForDelete and
+-- LockChatSessionForRuntimeBind, taken as the transaction's first statement, so
+-- no ordering against the repo-wide chat_session -> agent_task_queue sequence is
+-- introduced and none of the three can deadlock against each other.
+SELECT * FROM chat_session
+WHERE id = $1
+FOR UPDATE;
+
-- name: DeleteChatSession :exec
-- Hard delete. chat_message rows cascade via FK ON DELETE CASCADE; the
-- chat_session_id on agent_task_queue is set NULL by FK so completed/failed