Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(tasks): settle supplements in application transactions (MUL-7630) (#8755)
Multica Eved45aba1cd758
diff --git a/server/cmd/migrate/migrate_task_supplement_test.go b/server/cmd/migrate/migrate_task_supplement_test.goindex 16d8f7142f..e4e96bc677 100644--- a/server/cmd/migrate/migrate_task_supplement_test.go+++ b/server/cmd/migrate/migrate_task_supplement_test.go@@ -26,6 +26,7 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {"541_task_supplement_comment_index","542_task_supplement_primary_key","543_task_supplement_teardown_guard",+ "544_task_supplement_application_settlement",}if direction == "down" {slices.Reverse(versions)@@ -61,7 +62,19 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {if err := pool.QueryRow(ctx, `SELECT indisprimary FROM pg_index WHERE indexrelid = 'task_supplement_pkey'::regclass`).Scan(&primary); err != nil || !primary {t.Fatalf("receipt primary key missing: %v", err)}- // Teardown owns dependent deletion and must not run receipt settlement.+ var triggerExists bool+ if err := pool.QueryRow(ctx, `+ SELECT EXISTS (+ SELECT 1 FROM pg_trigger+ WHERE tgname = 'trg_settle_terminal_task_supplements'+ AND NOT tgisinternal+ )+ `).Scan(&triggerExists); err != nil || triggerExists {+ t.Fatalf("terminal supplement trigger exists=%v: %v", triggerExists, err)+ }++ // A bare task update no longer has hidden cross-table effects. The+ // application owns receipt settlement in the surrounding transaction.tx, err := pool.Begin(ctx)if err != nil {t.Fatal(err)@@ -70,7 +83,6 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {INSERT INTO agent_task_queue VALUES ('00000000-0000-0000-0000-000000000001', 'running');INSERT INTO task_supplement (task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status)VALUES ('00000000-0000-0000-0000-000000000001', gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'pending');- SET LOCAL multica.workspace_teardown = 'on';UPDATE agent_task_queue SET status='cancelled';`)var status stringif err == nil {@@ -78,7 +90,7 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {}_ = tx.Rollback(ctx)if err != nil || status != "pending" {- t.Fatalf("teardown ran receipt settlement: %s, %v", status, err)+ t.Fatalf("task update had hidden receipt settlement: %s, %v", status, err)}}}diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex fe447b17e5..e77f7528a9 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -613,8 +613,8 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to cancel queued tasks for the archived session")return}- if err = service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...); err != nil {- writeError(w, http.StatusInternalServerError, "failed to settle delegated failure recoveries")+ if err = service.SettleTerminalTaskState(r.Context(), qtx, cancelled...); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to settle terminal task state")return}case errors.Is(bindingErr, pgx.ErrNoRows):@@ -722,8 +722,8 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to cancel chat session tasks")return}- if err := service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...); err != nil {- writeError(w, http.StatusInternalServerError, "failed to settle delegated failure recoveries")+ if err := service.SettleTerminalTaskState(r.Context(), qtx, cancelled...); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to settle terminal task state")return}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex b0a17d666a..745ade041a 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -3507,7 +3507,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {if err == nil && oldContent != req.Content && strictContentEdit {cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)if err == nil {- err = service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...)+ err = service.SettleTerminalTaskState(r.Context(), qtx, cancelled...)}}if err == nil && replaceAttachments {diff --git a/server/internal/handler/task_supplement_test.go b/server/internal/handler/task_supplement_test.goindex 8c96c3ec2b..64e6842a0c 100644--- a/server/internal/handler/task_supplement_test.go+++ b/server/internal/handler/task_supplement_test.go@@ -44,6 +44,26 @@ func TestStableTaskSupplementFailureReason(t *testing.T) {}}+func TestTaskSupplementSettlementHasNoDatabaseTrigger(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ var exists bool+ if err := testPool.QueryRow(t.Context(), `+ SELECT EXISTS (+ SELECT 1+ FROM pg_trigger+ WHERE tgname = 'trg_settle_terminal_task_supplements'+ AND NOT tgisinternal+ )+ `).Scan(&exists); err != nil {+ t.Fatal(err)+ }+ if exists {+ t.Fatal("task supplement settlement still depends on a database trigger")+ }+}+func TestTaskSupplementClaimStartReplay(t *testing.T) {f := newSupplementFixture(t, "codex", "dispatched", false)dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id=$1`, f.taskID)@@ -77,7 +97,9 @@ func TestTaskSupplementLateDeliveryAndDeletion(t *testing.T) {return withURLParam(newRequest(http.MethodDelete, "/comments/"+sent.ID, nil), "commentId", sent.ID)}testutil.Call(t, testHandler.DeleteComment, deleteRequest()).Want(http.StatusConflict)- dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed' WHERE id=$1`, f.taskID)+ if w := completeTaskViaHandler(t, f.taskID, "done"); w.Code != http.StatusOK {+ t.Fatalf("complete task: status %d: %s", w.Code, w.Body.String())+ }for _, c := range []CommentResponse{sent, pending} {req := withURLParams(newDaemonTokenRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}, testWorkspaceID, "legit-daemon"), "taskId", f.taskID, "commentId", c.ID)want := http.StatusOK@@ -520,6 +542,52 @@ func TestTaskSupplementStopRemainsIndependent(t *testing.T) {}}+func TestTaskSupplementFailureSettlesPendingReceipt(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ var comment CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-555555555555", "pending when failed").+ Want(http.StatusCreated).JSON(&comment)+ if w := failTaskViaHandler(t, fixture.taskID); w.Code != http.StatusOK {+ t.Fatalf("fail task: status %d: %s", w.Code, w.Body.String())+ }+ receipt, err := testHandler.Queries.GetTaskSupplementByComment(t.Context(), db.GetTaskSupplementByCommentParams{+ CommentID: parseUUID(comment.ID), WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != protocol.TaskSupplementFailureTurnEnded {+ t.Fatalf("failed task receipt = %#v, err %v", receipt, err)+ }+}++func TestTaskSupplementTerminalWriteRollsBackWhenSettlementFails(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ var comment CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-aaaaaaaaaaaa", "must settle atomically").+ Want(http.StatusCreated).JSON(&comment)++ dbfx.Exec(t, `+ CREATE OR REPLACE FUNCTION reject_task_supplement_settlement() RETURNS trigger AS $$+ BEGIN RAISE EXCEPTION 'settlement rejected'; END;+ $$ LANGUAGE plpgsql;+ CREATE TRIGGER reject_task_supplement_settlement+ BEFORE UPDATE OF status ON task_supplement+ FOR EACH ROW EXECUTE FUNCTION reject_task_supplement_settlement()+ `)+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DROP TRIGGER IF EXISTS reject_task_supplement_settlement ON task_supplement`)+ _, _ = testPool.Exec(context.Background(), `DROP FUNCTION IF EXISTS reject_task_supplement_settlement()`)+ })++ if w := completeTaskViaHandler(t, fixture.taskID, "done"); w.Code != http.StatusInternalServerError {+ t.Fatalf("complete task with rejected settlement: status %d: %s", w.Code, w.Body.String())+ }+ var taskStatus, receiptStatus string+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, fixture.taskID).Scan(&taskStatus)+ dbfx.QueryRow(t, `SELECT status FROM task_supplement WHERE comment_id = $1`, comment.ID).Scan(&receiptStatus)+ if taskStatus != "running" || receiptStatus != "pending" {+ t.Fatalf("partial terminal commit: task=%s receipt=%s", taskStatus, receiptStatus)+ }+}+func TestTaskSupplementPermissionAndTenantIsolation(t *testing.T) {fixture := newSupplementFixture(t, "codex", "running", true)otherUser := dbfx.Insert(t, "user", testutil.Cols{"name": "No Invoke", "email": "[email protected]"})diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex f96b335f9c..c02b3eb697 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -110,7 +110,7 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDif err != nil {return empty, err}- if err = service.SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, result.CancelledTasks...); err != nil {+ if err = service.SettleTerminalTaskState(ctx, qtx, result.CancelledTasks...); err != nil {return empty, err}diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.goindex 9aa1c1ac37..c19259718b 100644--- a/server/internal/service/runtime_teardown.go+++ b/server/internal/service/runtime_teardown.go@@ -98,7 +98,7 @@ func TeardownRuntime(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUIDif err != nil {return out, fmt.Errorf("cancel tasks: %w", err)}- if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...); err != nil {+ if err := SettleTerminalTaskState(ctx, qtx, cancelled...); err != nil {return out, err}out.CancelledTasks = cancelleddiff --git a/server/internal/service/task.go b/server/internal/service/task.goindex e1d57f84c0..914e757ae5 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2607,7 +2607,7 @@ func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UUif err != nil {return err}- return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)+ return SettleTerminalTaskState(ctx, qtx, cancelled...)}); err != nil {return err}@@ -2658,7 +2658,7 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UUif err != nil {return err}- return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)+ return SettleTerminalTaskState(ctx, qtx, cancelled...)}); err != nil {return nil, err}@@ -2686,7 +2686,7 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentIDif err != nil {return err}- return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)+ return SettleTerminalTaskState(ctx, qtx, cancelled...)}); err != nil {return nil, err}@@ -2937,7 +2937,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUtask = cancelled// CancelAgentTaskByUser appends the recovery receipt in the same// statement, so the returned row already carries it.- if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled); err != nil {+ if err := SettleTerminalTaskState(ctx, qtx, cancelled); err != nil {return err}if !cancelled.ChatSessionID.Valid {@@ -2999,7 +2999,7 @@ func (s *TaskService) CancelQueuedChatTasks(ctx context.Context, sessionID, agenif err != nil {return fmt.Errorf("cancel queued chat tasks: %w", err)}- if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, tasks...); err != nil {+ if err := SettleTerminalTaskState(ctx, qtx, tasks...); err != nil {return err}for _, task := range tasks {@@ -4397,7 +4397,7 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt// Atomic with the status flip: a crash between the two would leave a// finished obligation looking pending forever.- if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, t); err != nil {+ if err := SettleTerminalTaskState(ctx, qtx, t); err != nil {return err}@@ -4892,7 +4892,7 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.// coordinator that already received the recovery comment has consumed// the obligation: the pre-existing delivered_comment_ids coverage check// never looked at the covering task's status either.- if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, t); err != nil {+ if err := SettleTerminalTaskState(ctx, qtx, t); err != nil {return err}@@ -5767,7 +5767,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourcif err != nil {return err}- return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)+ return SettleTerminalTaskState(ctx, qtx, cancelled...)})if cerr != nil {slog.Warn("rerun: cancel pending tasks failed",@@ -5900,7 +5900,7 @@ func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agen// The bulk terminal writes below are the sweeper, archive and daemon-recovery// paths that finalize many tasks in one statement. They exist on TaskService rather than-// being called as bare queries so the statement and its delegated-failure+// being called as bare queries so the statement and all terminal-state// settlement share a transaction.//// That is not a stylistic preference. HandleFailedTasks and@@ -5979,7 +5979,7 @@ func (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Querif err != nil {return err}- return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, failed...)+ return SettleTerminalTaskState(ctx, qtx, failed...)}); err != nil {return nil, err}@@ -6102,6 +6102,30 @@ const (delegatedFailureRecoveryCommentType = "progress_update")+// SettleTerminalTaskState applies every application-owned side effect of a+// task entering a terminal state. It must run with the same qtx as the status+// update so task completion and its dependent receipts commit atomically.+//+// Keeping this as the single terminal-settlement entry point is important:+// task supplements used to rely on an agent_task_queue trigger that performed+// a cross-table update invisibly. Explicit settlement preserves the existing+// task-row -> dependent-row lock order without making task status writes depend+// on database trigger behavior.+func SettleTerminalTaskState(ctx context.Context, q *db.Queries, tasks ...db.AgentTaskQueue) error {+ if len(tasks) == 0 {+ return nil+ }++ taskIDs := make([]pgtype.UUID, 0, len(tasks))+ for _, task := range tasks {+ taskIDs = append(taskIDs, task.ID)+ }+ if _, err := q.SettleTerminalTaskSupplements(ctx, taskIDs); err != nil {+ return fmt.Errorf("settle terminal task supplements: %w", err)+ }+ return SettleDeliveredDelegatedFailureRecoveries(ctx, q, tasks...)+}+// SettleDeliveredDelegatedFailureRecoveries retires every delegated-failure// recovery comment the given now-terminal tasks actually received, so those// comments drop out of idx_comment_delegated_failure_unsettled instead of@@ -6109,10 +6133,11 @@ const (// sweeper tick. Without it the outbox scan grows with total history even when// it returns nothing.//-// INVARIANT: every path that moves tasks to a terminal status must reach this-// with the same qtx as the terminal write — per-task writes and bulk-// cancellations alike, so the marker commits atomically with the status change-// or not at all. A row stranded by a committed-but-unsettled terminal write+// INVARIANT: every path that moves tasks to a terminal status must reach+// SettleTerminalTaskState with the same qtx as the terminal write — per-task+// writes and bulk cancellations alike, so every marker commits atomically with+// the status change or not at all. A row stranded by a+// committed-but-unsettled terminal write// cannot be repaired later: ListPendingDelegatedFailureRecoveries excludes a// comment whose covering task is already terminal and holds its receipt, so// nothing replays the settlement and nothing else marks it, and the indexdiff --git a/server/migrations/544_task_supplement_application_settlement.down.sql b/server/migrations/544_task_supplement_application_settlement.down.sqlnew file mode 100644index 0000000000..4b08b05bd9--- /dev/null+++ b/server/migrations/544_task_supplement_application_settlement.down.sql@@ -0,0 +1,21 @@+CREATE FUNCTION settle_terminal_task_supplements() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ IF OLD.status IN ('queued', 'deferred', 'dispatched', 'waiting_local_directory', 'running')+ AND NEW.status IN ('completed', 'failed', 'cancelled') THEN+ UPDATE task_supplement+ SET status = 'failed',+ failure_reason = 'turn_ended',+ updated_at = now()+ WHERE task_id = NEW.id+ AND status IN ('pending', 'delivering');+ END IF;+ RETURN NEW;+END;+$$;++CREATE TRIGGER trg_settle_terminal_task_supplements+AFTER UPDATE OF status ON agent_task_queue+FOR EACH ROW+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')+EXECUTE FUNCTION settle_terminal_task_supplements();diff --git a/server/migrations/544_task_supplement_application_settlement.up.sql b/server/migrations/544_task_supplement_application_settlement.up.sqlnew file mode 100644index 0000000000..1727ee0ce3--- /dev/null+++ b/server/migrations/544_task_supplement_application_settlement.up.sql@@ -0,0 +1,5 @@+-- Task terminal transitions now settle pending supplements explicitly in the+-- application transaction. Remove the cross-table trigger so task completion+-- no longer acquires task_supplement locks through database-side cascade logic.+DROP TRIGGER IF EXISTS trg_settle_terminal_task_supplements ON agent_task_queue;+DROP FUNCTION IF EXISTS settle_terminal_task_supplements();diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.goindex 63c3ee7085..c750f6d219 100644--- a/server/pkg/db/generated/supplement.sql.go+++ b/server/pkg/db/generated/supplement.sql.go@@ -552,6 +552,30 @@ func (q *Queries) RetryTaskSupplement(ctx context.Context, arg RetryTaskSupplemereturn i, err}+const settleTerminalTaskSupplements = `-- name: SettleTerminalTaskSupplements :execrows+UPDATE task_supplement AS supplement+SET status = 'failed',+ failure_reason = 'turn_ended',+ updated_at = now()+FROM agent_task_queue AS task+WHERE supplement.task_id = task.id+ AND task.id = ANY($1::uuid[])+ AND task.status IN ('completed', 'failed', 'cancelled')+ AND supplement.status IN ('pending', 'delivering')+`++// Application terminal transitions call this in the same transaction as the+// agent_task_queue update. Re-checking the persisted task status makes an+// accidental early call a no-op while preserving the task-row -> supplement+// lock order used by creation and delivery acknowledgement.+func (q *Queries) SettleTerminalTaskSupplements(ctx context.Context, taskIds []pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, settleTerminalTaskSupplements, taskIds)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const startAgentTaskWithSupplement = `-- name: StartAgentTaskWithSupplement :oneWITH candidate AS MATERIALIZED (SELECT t.id, t.issue_id, r.workspace_id, r.providerdiff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sqlindex 236ccdc4c5..dea1fb7604 100644--- a/server/pkg/db/queries/supplement.sql+++ b/server/pkg/db/queries/supplement.sql@@ -114,6 +114,21 @@ WHERE cap.workspace_id = @workspace_idAND cap.task_id = ANY(@task_ids::uuid[])GROUP BY cap.task_id, cap.capability;+-- name: SettleTerminalTaskSupplements :execrows+-- Application terminal transitions call this in the same transaction as the+-- agent_task_queue update. Re-checking the persisted task status makes an+-- accidental early call a no-op while preserving the task-row -> supplement+-- lock order used by creation and delivery acknowledgement.+UPDATE task_supplement AS supplement+SET status = 'failed',+ failure_reason = 'turn_ended',+ updated_at = now()+FROM agent_task_queue AS task+WHERE supplement.task_id = task.id+ AND task.id = ANY(@task_ids::uuid[])+ AND task.status IN ('completed', 'failed', 'cancelled')+ AND supplement.status IN ('pending', 'delivering');+-- name: ClaimNextTaskSupplement :oneWITH next AS MATERIALIZED (SELECT s.comment_id