Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5999: make workspace teardown index-driven, bounded and fenced (#6754)
Multica Evec4f0d8cc8c83
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 829e5c72a5..33ad3ba581 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -59,13 +59,47 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error// way, so it carries the same hazard — an INVALID v2 leftover recorded as// success would let migration 262 drop the still-valid v1, leaving all four// dashboard rollups on a full table scan.-var preMigrationHooks = map[string]preMigrationHook{- "103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,- "198_agent_task_attribution_strict_constraint_validate": runAttributionStrictHook,- "257_agent_task_queue_channel_media_pending_unique_v2": cleanupInvalidConcurrentIndexHook("idx_one_pending_task_per_issue_agent_v2"),- "261_agent_task_queue_terminal_completed_at_v2": cleanupInvalidConcurrentIndexHook("idx_agent_task_queue_terminal_completed_at_v2"),+// concurrentIndexCleanups maps a migration version to the index it builds with+// CREATE INDEX CONCURRENTLY. Every entry gets an invalid-index cleanup hook, so+// an interrupted build cannot be mistaken for success on retry.+//+// The mapping is data rather than seven hand-written hook registrations so a+// test can check each entry against the index its migration file actually+// creates — a typo here would be invisible at runtime, because a hook that names+// a nonexistent index is a silent no-op.+//+// MUL-5999: migrations 273–277 each build one index concurrently, three of them+// on hot tables (agent_task_queue is the largest table in the database). They+// carry the same hazard as 257 / 261: an interrupted build leaves an INVALID+// index of the same name, `IF NOT EXISTS` then skips the rebuild, the runner+// records the migration as applied, and the queries that need the index silently+// stay on a full scan — the exact regression these migrations exist to fix.+var concurrentIndexCleanups = map[string]string{+ "257_agent_task_queue_channel_media_pending_unique_v2": "idx_one_pending_task_per_issue_agent_v2",+ "261_agent_task_queue_terminal_completed_at_v2": "idx_agent_task_queue_terminal_completed_at_v2",+ "273_agent_task_queue_runtime_id_index": "idx_agent_task_queue_runtime_id",+ "274_task_token_workspace_id_index": "idx_task_token_workspace_id",+ "275_task_token_agent_id_index": "idx_task_token_agent_id",+ "276_chat_draft_restore_task_id_index": "idx_chat_draft_restore_task_id",+ "277_autopilot_run_task_id_index": "idx_autopilot_run_task_id",+ "278_agent_task_queue_agent_id_keyset_index": "idx_agent_task_queue_agent_id_keyset",+ "279_agent_task_queue_issue_id_keyset_index": "idx_agent_task_queue_issue_id_keyset",+ "281_agent_workspace_id_keyset_index": "idx_agent_workspace_id_keyset",+ "282_issue_workspace_id_keyset_index": "idx_issue_workspace_id_keyset",+ "283_agent_runtime_workspace_id_keyset_index": "idx_agent_runtime_workspace_id_keyset",}+var preMigrationHooks = func() map[string]preMigrationHook {+ hooks := map[string]preMigrationHook{+ "103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,+ "198_agent_task_attribution_strict_constraint_validate": runAttributionStrictHook,+ }+ for version, index := range concurrentIndexCleanups {+ hooks[version] = cleanupInvalidConcurrentIndexHook(index)+ }+ return hooks+}()+// cleanupInvalidConcurrentIndexHook removes an INVALID index left by an// interrupted or failed CREATE INDEX CONCURRENTLY before the migration retries.// Without this guard, CREATE INDEX ... IF NOT EXISTS would treat the leftoverdiff --git a/server/cmd/migrate/migrate_mul5999_index_retry_test.go b/server/cmd/migrate/migrate_mul5999_index_retry_test.gonew file mode 100644index 0000000000..a94c712252--- /dev/null+++ b/server/cmd/migrate/migrate_mul5999_index_retry_test.go@@ -0,0 +1,194 @@+package main++import (+ "bytes"+ "context"+ "fmt"+ "math/rand/v2"+ "os"+ "path/filepath"+ "regexp"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+)++var concurrentIndexNamePattern = regexp.MustCompile(+ `(?i)CREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-z0-9_]+)`)++// stripSQLLineComments drops `--` comment lines so prose that mentions SQL is+// not mistaken for SQL.+func stripSQLLineComments(body []byte) []byte {+ var kept [][]byte+ for _, line := range bytes.Split(body, []byte("\n")) {+ if bytes.HasPrefix(bytes.TrimSpace(line), []byte("--")) {+ continue+ }+ kept = append(kept, line)+ }+ return bytes.Join(kept, []byte("\n"))+}++// TestConcurrentIndexCleanupsMatchTheirMigrations guards the mapping that wires+// invalid-index cleanup hooks to migrations. A hook that names an index no+// migration creates is a silent no-op: the retry then treats the INVALID+// leftover as success and the index stays unusable. Nothing at runtime would+// report that, so the names are checked against the migration files here.+func TestConcurrentIndexCleanupsMatchTheirMigrations(t *testing.T) {+ for version, indexName := range concurrentIndexCleanups {+ path := filepath.Join("..", "..", "migrations", version+".up.sql")+ body, err := os.ReadFile(path)+ if err != nil {+ t.Errorf("%s: read migration: %v", version, err)+ continue+ }+ // The comment headers on these migrations mention CREATE INDEX+ // CONCURRENTLY in prose, so match statements only.+ match := concurrentIndexNamePattern.FindSubmatch(stripSQLLineComments(body))+ if match == nil {+ t.Errorf("%s: has a cleanup hook but builds no index concurrently", version)+ continue+ }+ if got := string(match[1]); got != indexName {+ t.Errorf("%s: hook cleans %q but the migration builds %q", version, indexName, got)+ }+ if preMigrationHooks[version] == nil {+ t.Errorf("%s: no pre-migration hook registered", version)+ }+ }++ // The MUL-5999 batch specifically: every one of these builds an index the+ // new teardown queries depend on, so none of them may lose its hook.+ for _, version := range []string{+ "273_agent_task_queue_runtime_id_index",+ "274_task_token_workspace_id_index",+ "275_task_token_agent_id_index",+ "276_chat_draft_restore_task_id_index",+ "277_autopilot_run_task_id_index",+ } {+ if _, ok := concurrentIndexCleanups[version]; !ok {+ t.Errorf("%s: missing from concurrentIndexCleanups", version)+ }+ }+}++// TestRunMigrationsRepairsInvalidRuntimeIDIndex is the MUL-5999 counterpart of+// the 257 / 261 repair tests, run against migration 273's real SQL and its real+// registered hook.+//+// 273 is the representative case: it uses `CREATE INDEX CONCURRENTLY IF NOT+// EXISTS` on agent_task_queue, so an interrupted build leaves an INVALID index+// that the retry would otherwise skip past, recording the migration as applied+// while every all-status runtime_id lookup — teardown's runtime path and the+// FK's own cascade probe — stays on a full table scan.+func TestRunMigrationsRepairsInvalidRuntimeIDIndex(t *testing.T) {+ pool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()++ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())+ schema := "migrate_mul5999_" + suffix+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cleanupCancel()+ if _, err := pool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {+ t.Logf("drop schema %s: %v", schema, err)+ }+ })++ const indexName = "idx_agent_task_queue_runtime_id"+ const version = "273_agent_task_queue_runtime_id_index"+ tableName := pgx.Identifier{schema, "agent_task_queue"}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE TABLE "+tableName+` (+ id BIGSERIAL PRIMARY KEY,+ runtime_id UUID+ )`); err != nil {+ t.Fatalf("create task table: %v", err)+ }++ qualifiedIndex := pgx.Identifier{schema, indexName}.Sanitize()+ createIndex := "CREATE INDEX CONCURRENTLY IF NOT EXISTS " + pgx.Identifier{indexName}.Sanitize() ++ " ON " + tableName + " (runtime_id)"++ // Interrupt the build the way a real one gets interrupted: an open+ // transaction that has written to the table owns an xid the concurrent+ // build must wait for, and statement_timeout cancels the wait.+ blocker, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatalf("acquire blocker conn: %v", err)+ }+ blockerTx, err := blocker.Begin(ctx)+ if err != nil {+ blocker.Release()+ t.Fatalf("begin blocker tx: %v", err)+ }+ if _, err := blockerTx.Exec(ctx, "INSERT INTO "+tableName+" (runtime_id) VALUES (gen_random_uuid())"); err != nil {+ blocker.Release()+ t.Fatalf("blocker insert: %v", err)+ }++ builder, err := pool.Acquire(ctx)+ if err != nil {+ blocker.Release()+ t.Fatalf("acquire builder conn: %v", err)+ }+ if _, err := builder.Exec(ctx, "SET statement_timeout = '2s'"); err != nil {+ builder.Release()+ blocker.Release()+ t.Fatalf("set statement_timeout: %v", err)+ }+ _, buildErr := builder.Exec(ctx, createIndex)+ // pgxpool does not reset session state, so clear the fuse before the+ // connection goes back to the pool.+ if _, err := builder.Exec(ctx, "SET statement_timeout = DEFAULT"); err != nil {+ t.Logf("reset statement_timeout: %v", err)+ }+ builder.Release()+ if buildErr == nil {+ blocker.Release()+ t.Fatal("interrupted build unexpectedly succeeded")+ }+ _ = blockerTx.Rollback(ctx)+ blocker.Release()++ assertIndexValidity(t, pool, schema, indexName, false)++ migrationPath := filepath.Join(t.TempDir(), version+".up.sql")+ if err := os.WriteFile(migrationPath, []byte(createIndex+";\n"), 0o600); err != nil {+ t.Fatalf("write retry migration: %v", err)+ }+ opts := runOptions{+ Direction: "up",+ Files: []string{migrationPath},+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ }++ // Without the hook the retry is a silent no-op: IF NOT EXISTS sees the+ // invalid relation, reports success, and the migration is recorded.+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatalf("retry without hook: %v", err)+ }+ assertIndexValidity(t, pool, schema, indexName, false)++ // With the production hook — schema-qualified so it resolves inside the+ // test schema — the leftover is dropped and the index is rebuilt.+ if preMigrationHooks[version] == nil {+ t.Fatalf("production hook is not registered for %s", version)+ }+ if _, err := pool.Exec(ctx, "DELETE FROM "+pgx.Identifier{schema, "schema_migrations"}.Sanitize()+" WHERE version = $1", version); err != nil {+ t.Fatalf("reset recorded version: %v", err)+ }+ opts.Hooks = map[string]preMigrationHook{+ version: cleanupInvalidConcurrentIndexHook(qualifiedIndex),+ }+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatalf("retry migration with invalid-index cleanup: %v", err)+ }+ assertIndexValidity(t, pool, schema, indexName, true)+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 45d2b8d5f0..e5011d5e5a 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -751,45 +751,124 @@ func (h *Handler) mergeLegacyRuntimes(r *http.Request, registered db.AgentRuntim}merged[oldID] = struct{}{}- agents, err := h.Queries.ReassignAgentsToRuntime(r.Context(), db.ReassignAgentsToRuntimeParams{- NewRuntimeID: registered.ID,- OldRuntimeID: old.ID,- })- if err != nil {- slog.Warn("legacy runtime merge: reassign agents failed", "legacy_daemon_id", legacyID, "old_runtime_id", oldID, "new_runtime_id", newID, "error", err)- continue- }- tasks, err := h.Queries.ReassignTasksToRuntime(r.Context(), db.ReassignTasksToRuntimeParams{- NewRuntimeID: registered.ID,- OldRuntimeID: old.ID,- })- if err != nil {- slog.Warn("legacy runtime merge: reassign tasks failed", "legacy_daemon_id", legacyID, "old_runtime_id", oldID, "new_runtime_id", newID, "error", err)- continue- }- if err := h.Queries.RecordRuntimeLegacyDaemonID(r.Context(), db.RecordRuntimeLegacyDaemonIDParams{- ID: registered.ID,- LegacyDaemonID: strToText(legacyID),- }); err != nil {- slog.Warn("legacy runtime merge: record legacy daemon_id failed", "legacy_daemon_id", legacyID, "error", err)- }- if err := h.Queries.DeleteAgentRuntime(r.Context(), old.ID); err != nil {- slog.Warn("legacy runtime merge: delete old runtime failed", "old_runtime_id", oldID, "error", err)- continue+ if err := h.mergeLegacyRuntime(r.Context(), registered.ID, old.ID, legacyID, provider); err != nil {+ slog.Warn("legacy runtime merge failed",+ "legacy_daemon_id", legacyID, "old_runtime_id", oldID, "new_runtime_id", newID, "error", err)}-- slog.Info("legacy runtime merged",- "legacy_daemon_id", legacyID,- "old_runtime_id", oldID,- "new_runtime_id", newID,- "provider", provider,- "agents_reassigned", agents,- "tasks_reassigned", tasks,- )}}}+// errRuntimeMergeFenced reports that the task-write fence refused the+// reassignment because the target runtime's workspace is being deleted or is+// already gone. The merge is abandoned, not retried in place: the next daemon+// registration re-runs it, and by then either the workspace is gone entirely or+// the teardown rolled back.+var errRuntimeMergeFenced = errors.New("runtime merge refused by the task-write fence")++// mergeLegacyRuntime folds one legacy runtime row into the freshly registered one,+// as a single transaction.+//+// Order is load-bearing. The fence comes first — workspace row, then both runtime+// rows FOR UPDATE — and tasks move next, because that statement carries the same+// fence predicate every task write uses and is the only step that can tell us the+// target workspace is being torn down. Its verdict is separate from its row+// count for exactly this reason: "0 tasks reassigned" is also what a legacy runtime+// with no history looks like, and treating a fenced refusal as success would take+// us straight to DeleteAgentRuntime below — where agent_task_queue's+// ON DELETE CASCADE would delete the history this merge is supposed to carry+// forward (MUL-5999 review).+//+// One transaction, because the fence's workspace lock lives only as long as the+// statement that took it. Run as four autocommit statements, the merge had two+// ways to leave the tenant inconsistent and the registration reporting success:+//+// - a transient failure on the agent reassignment left tasks pointing at the new+// runtime while their agents stayed on the old one, self-healing only on some+// later registration;+// - worse, in the gap after the task commit a workspace teardown could lock and+// delete the target runtime, whose UnbindTasksFromRuntime step clears+// runtime_id on the tasks that had just moved. The next merge looks for tasks+// by the OLD runtime id, so that history was permanently detached.+//+// Holding the fence lock from the first statement to COMMIT closes both: the+// teardown cannot start deleting the target until this merge finishes, and any+// failure rolls the whole merge back to its starting state.+func (h *Handler) mergeLegacyRuntime(ctx context.Context, newRuntimeID, oldRuntimeID pgtype.UUID, legacyID, provider string) error {+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return fmt.Errorf("begin merge tx: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)++ // Fence, in the same order every task write uses: workspace row first, then the+ // owner rows. Without the FOR UPDATE on the runtimes, a concurrent enqueue+ // against the OLD runtime slipped through after the task scan — writers hold+ // only FOR KEY SHARE on the workspace, and so did this merge, and two KEY SHARE+ // locks do not conflict — and DeleteAgentRuntime below then removed that+ // brand-new task through ON DELETE CASCADE.+ runtimeIDs := []pgtype.UUID{oldRuntimeID, newRuntimeID}+ if err := qtx.LockWorkspaceForRuntimeMerge(ctx, runtimeIDs); err != nil {+ return fmt.Errorf("lock workspace: %w", err)+ }+ locked, err := qtx.LockRuntimesForMerge(ctx, runtimeIDs)+ if err != nil {+ return fmt.Errorf("lock runtimes: %w", err)+ }+ if len(locked) != len(runtimeIDs) {+ // One of them went away while we were queueing for the lock; the fence+ // inside the reassignment would refuse anyway.+ return errRuntimeMergeFenced+ }++ reassignment, err := qtx.ReassignTasksToRuntime(ctx, db.ReassignTasksToRuntimeParams{+ NewRuntimeID: newRuntimeID,+ OldRuntimeID: oldRuntimeID,+ })+ if err != nil {+ return fmt.Errorf("reassign tasks: %w", err)+ }+ if !reassignment.FenceOk {+ return errRuntimeMergeFenced+ }++ agents, err := qtx.ReassignAgentsToRuntime(ctx, db.ReassignAgentsToRuntimeParams{+ NewRuntimeID: newRuntimeID,+ OldRuntimeID: oldRuntimeID,+ })+ if err != nil {+ return fmt.Errorf("reassign agents: %w", err)+ }++ // Inside the transaction this can no longer be best-effort: a failed statement+ // poisons the transaction, so it either lands with the rest of the merge or the+ // merge is rolled back.+ if err := qtx.RecordRuntimeLegacyDaemonID(ctx, db.RecordRuntimeLegacyDaemonIDParams{+ ID: newRuntimeID,+ LegacyDaemonID: strToText(legacyID),+ }); err != nil {+ return fmt.Errorf("record legacy daemon_id: %w", err)+ }+ if err := qtx.DeleteAgentRuntime(ctx, oldRuntimeID); err != nil {+ return fmt.Errorf("delete old runtime: %w", err)+ }++ if err := tx.Commit(ctx); err != nil {+ return fmt.Errorf("commit merge: %w", err)+ }++ slog.Info("legacy runtime merged",+ "legacy_daemon_id", legacyID,+ "old_runtime_id", uuidToString(oldRuntimeID),+ "new_runtime_id", uuidToString(newRuntimeID),+ "provider", provider,+ "agents_reassigned", agents,+ "tasks_reassigned", reassignment.ReassignedTasks,+ )+ return nil+}+func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Request) {workspaceID := strings.TrimSpace(chi.URLParam(r, "workspaceId"))if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex db30bb39fd..beef59b18c 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1,6 +1,7 @@package handlerimport (+ "context""encoding/json""errors""fmt"@@ -766,28 +767,31 @@ func effectiveWorkspaceDeleteLockTimeout() time.Duration {return workspaceDeleteLockTimeout}-// isLockTimeout reports whether err is Postgres' lock_not_available-// (SQLSTATE 55P03), which is what `SET LOCAL lock_timeout` raises when a lock-// wait exceeds its budget. It says nothing about the workspace itself: the row-// is untouched and the caller can retry once the other holder is done.-func isLockTimeout(err error) bool {+// isRetryableLockFailure reports whether err is one of the two transient lock+// outcomes a teardown can hit: lock_not_available (55P03), which is what+// `SET LOCAL lock_timeout` raises when a wait exceeds its budget, and+// deadlock_detected (40P01), which the owner-row locks can hit against a+// concurrent task update that takes the same locks in the opposite order (task+// row first, then its owner). Neither says anything about the workspace itself:+// the transaction rolled back untouched and the caller can retry.+func isRetryableLockFailure(err error) bool {if err == nil {return false}var pgErr *pgconn.PgErrorif errors.As(err, &pgErr) {- return pgErr.Code == "55P03"+ return pgErr.Code == "55P03" || pgErr.Code == "40P01"}return false}// failWorkspaceDelete logs a failed teardown step and writes the response for-// it. A lock timeout is transient and retryable, so it answers 503 with a-// message the delete dialog can show; every other failure stays a 500.+// it. A lock timeout or deadlock is transient and retryable, so it answers 503+// with a message the delete dialog can show; every other failure stays a 500.func failWorkspaceDelete(w http.ResponseWriter, r *http.Request, workspaceID, step string, err error) {attrs := append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "step", step)- if isLockTimeout(err) {- slog.Warn("workspace delete blocked by lock timeout", attrs...)+ if isRetryableLockFailure(err) {+ slog.Warn("workspace delete blocked by lock contention", attrs...)writeError(w, http.StatusServiceUnavailable, "workspace deletion is temporarily blocked by another operation, please try again")return}@@ -795,6 +799,249 @@ func failWorkspaceDelete(w http.ResponseWriter, r *http.Request, workspaceID, stwriteError(w, http.StatusInternalServerError, "failed to delete workspace")}+// workspaceDeleteTaskPageSize bounds one task page: the ids held in this process,+// the array parameter sent back to Postgres, and the row count of a single+// DELETE. A whole workspace's task set is not bounded by anything — one busy+// agent can own millions of historical rows — so it must never be materialized at+// once (MUL-5999 review).+const workspaceDeleteTaskPageSize = 1000++// workspaceDeleteOwnerPageSize bounds owner enumeration the same way. A workspace+// with a very large agent or issue set must not have its whole id list held here+// either.+const workspaceDeleteOwnerPageSize = 500++// workspaceDeleteVerifyPasses caps how many times a single owner may be swept.+//+// Pass 1 removes what is there; pass 2 confirms the owner came back empty. This is+// a cheap self-check, NOT the concurrency guarantee: a task inserted after the+// final empty scan and before COMMIT would not be caught by any number of passes.+// What closes that window is the in-transaction fence on task writes+// (migration 284) plus the workspace row lock teardown already holds. The passes+// exist so that anything unexpected — a path that somehow bypassed the fence — is+// either cleaned up or turns into a failed, rolled-back teardown rather than a+// tenant with rows left behind.+const workspaceDeleteVerifyPasses = 3++// deleteWorkspaceTasks removes every agent_task_queue row a workspace owns,+// together with the rows that hang off those tasks, in bounded keyset pages.+//+// Shape, and why:+//+// - One owner key per query. agent_task_queue has no workspace_id and all three+// ownership paths must stay (nothing enforces that a task's agent, runtime and+// issue share a workspace), but combining them in one statement — as the+// previous three-way OR, as a UNION of joins, or as `= ANY(array)` over a+// whole workspace's agents — leaves the planner estimating a proportional+// share of the global table and choosing a Seq Scan.+// - Keyset pages, so the SCAN is bounded and not just the result. Each page is+// an index range scan that resumes where the previous one stopped. Bounding+// only the result (`ORDER BY id LIMIT n` with no id in the index) puts a Sort+// over the owner's whole task set in front of every page, which costs roughly+// O(N² / page) for a busy owner.+// - Row locks, not a read snapshot. Each page takes FOR UPDATE, so under READ+// COMMITTED Postgres re-checks ownership after acquiring each lock: a task a+// concurrent commit already moved elsewhere is skipped rather than deleted on+// a stale claim, and a task we locked cannot move before we delete it.+// - Children first, in the application layer. DetachTaskBatchReferences breaks+// inbound references and DeleteTaskBatch removes task_usage, task_message,+// task_token, the two outbound card tables and chat_draft_restore before the+// task rows themselves. The legacy FK cascades stay a safety net only.+//+// Late arrivals are handled by the fence, not here: migration 284 makes every task+// write take FOR KEY SHARE on its owners' workspace rows, which conflicts with the+// FOR UPDATE that LockWorkspaceForDelete holds for this whole transaction.+func deleteWorkspaceTasks(ctx context.Context, qtx *db.Queries, workspaceID pgtype.UUID) error {+ ownerKinds := []struct {+ label string+ ownerFirstPage func(context.Context, int32) ([]pgtype.UUID, error)+ ownerPage func(context.Context, pgtype.UUID, int32) ([]pgtype.UUID, error)+ taskFirstPage func(context.Context, pgtype.UUID, int32) ([]pgtype.UUID, error)+ taskPage func(context.Context, pgtype.UUID, pgtype.UUID, int32) ([]pgtype.UUID, error)+ sweepAgent bool+ }{+ {+ label: "agent",+ ownerFirstPage: func(ctx context.Context, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceAgentIDFirstPage(ctx, db.ListWorkspaceAgentIDFirstPageParams{+ WorkspaceID: workspaceID, Limit: limit,+ })+ },+ ownerPage: func(ctx context.Context, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceAgentIDPage(ctx, db.ListWorkspaceAgentIDPageParams{+ WorkspaceID: workspaceID, ID: cursor, Limit: limit,+ })+ },+ taskFirstPage: func(ctx context.Context, owner pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByAgentFirstPage(ctx, db.ListTaskIDsByAgentFirstPageParams{+ AgentID: owner, Limit: limit,+ })+ },+ taskPage: func(ctx context.Context, owner, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByAgentPage(ctx, db.ListTaskIDsByAgentPageParams{+ AgentID: owner, ID: cursor, Limit: limit,+ })+ },+ // The third explicit task_token path. workspace_id (leaf data) and+ // task_id (DeleteTaskBatch) leave one shape uncovered: a token whose+ // own workspace_id points at a neighbour while its agent lives here.+ sweepAgent: true,+ },+ {+ label: "issue",+ ownerFirstPage: func(ctx context.Context, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceIssueIDFirstPage(ctx, db.ListWorkspaceIssueIDFirstPageParams{+ WorkspaceID: workspaceID, Limit: limit,+ })+ },+ ownerPage: func(ctx context.Context, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceIssueIDPage(ctx, db.ListWorkspaceIssueIDPageParams{+ WorkspaceID: workspaceID, ID: cursor, Limit: limit,+ })+ },+ taskFirstPage: func(ctx context.Context, owner pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByIssueFirstPage(ctx, db.ListTaskIDsByIssueFirstPageParams{+ IssueID: owner, Limit: limit,+ })+ },+ taskPage: func(ctx context.Context, owner, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByIssuePage(ctx, db.ListTaskIDsByIssuePageParams{+ IssueID: owner, ID: cursor, Limit: limit,+ })+ },+ },+ {+ label: "runtime",+ ownerFirstPage: func(ctx context.Context, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceRuntimeIDFirstPage(ctx, db.ListWorkspaceRuntimeIDFirstPageParams{+ WorkspaceID: workspaceID, Limit: limit,+ })+ },+ ownerPage: func(ctx context.Context, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListWorkspaceRuntimeIDPage(ctx, db.ListWorkspaceRuntimeIDPageParams{+ WorkspaceID: workspaceID, ID: cursor, Limit: limit,+ })+ },+ taskFirstPage: func(ctx context.Context, owner pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByRuntimeFirstPage(ctx, db.ListTaskIDsByRuntimeFirstPageParams{+ RuntimeID: owner, Limit: limit,+ })+ },+ taskPage: func(ctx context.Context, owner, cursor pgtype.UUID, limit int32) ([]pgtype.UUID, error) {+ return qtx.ListTaskIDsByRuntimePage(ctx, db.ListTaskIDsByRuntimePageParams{+ RuntimeID: owner, ID: cursor, Limit: limit,+ })+ },+ },+ }++ for _, kind := range ownerKinds {+ owners, err := kind.ownerFirstPage(ctx, workspaceDeleteOwnerPageSize)+ if err != nil {+ return fmt.Errorf("list workspace %ss: %w", kind.label, err)+ }+ for len(owners) > 0 {+ for _, ownerID := range owners {+ if err := sweepTasksForOwner(ctx, kind.label, ownerID,+ kind.taskFirstPage, kind.taskPage,+ qtx.DetachTaskBatchReferences, qtx.DeleteTaskBatch); err != nil {+ return err+ }+ if kind.sweepAgent {+ if err := qtx.DeleteTaskTokensByAgent(ctx, ownerID); err != nil {+ return fmt.Errorf("delete task tokens by agent: %w", err)+ }+ }+ }+ if owners, err = kind.ownerPage(ctx, owners[len(owners)-1], workspaceDeleteOwnerPageSize); err != nil {+ return fmt.Errorf("list workspace %ss: %w", kind.label, err)+ }+ }+ }++ return nil+}++// sweepTasksForOwner deletes one owner's tasks, then re-verifies that owner.+//+// Each pass walks the owner's tasks by keyset and deletes each page. A pass that+// deletes nothing means the owner is clean. A later pass that still finds tasks+// means something reached agent_task_queue without going through the fence, which+// is logged and retried; exhausting the passes fails the whole teardown rather+// than committing a workspace with tasks left behind.+func sweepTasksForOwner(+ ctx context.Context,+ label string,+ ownerID pgtype.UUID,+ taskFirstPage func(context.Context, pgtype.UUID, int32) ([]pgtype.UUID, error),+ taskPage func(context.Context, pgtype.UUID, pgtype.UUID, int32) ([]pgtype.UUID, error),+ detach func(context.Context, []pgtype.UUID) error,+ deletePage func(context.Context, []pgtype.UUID) error,+) error {+ for pass := 1; pass <= workspaceDeleteVerifyPasses; pass++ {+ deleted := 0+ taskIDs, err := taskFirstPage(ctx, ownerID, workspaceDeleteTaskPageSize)+ if err != nil {+ return fmt.Errorf("list tasks by %s: %w", label, err)+ }+ for len(taskIDs) > 0 {+ if err := detach(ctx, taskIDs); err != nil {+ return fmt.Errorf("detach task page references: %w", err)+ }+ if err := deletePage(ctx, taskIDs); err != nil {+ return fmt.Errorf("delete task page: %w", err)+ }+ deleted += len(taskIDs)+ if taskIDs, err = taskPage(ctx, ownerID, taskIDs[len(taskIDs)-1], workspaceDeleteTaskPageSize); err != nil {+ return fmt.Errorf("list tasks by %s: %w", label, err)+ }+ }+ if deleted == 0 {+ return nil+ }+ if pass > 1 {+ slog.Warn("workspace delete swept tasks that appeared after the owner was fenced",+ "owner_kind", label, "owner_id", uuidToString(ownerID), "pass", pass, "deleted", deleted)+ }+ }+ return fmt.Errorf("tasks kept appearing for %s %s after %d sweep passes; refusing to commit a partial teardown",+ label, uuidToString(ownerID), workspaceDeleteVerifyPasses)+}++// lockWorkspaceTaskOwners locks every row through which a task can belong to this+// workspace.+//+// Defence in depth on top of the real fence. The fence that closes the+// insert-after-sweep window is migration 284's lock_task_owner_rows, a predicate+// every ownership-writing statement calls in its own WHERE clause: it takes+// FOR KEY SHARE on the workspace rows behind the task's owners and then on the+// owner rows themselves, which conflicts with the FOR UPDATE that+// LockWorkspaceForDelete holds for this whole transaction. Called from the writing+// statement, so it is in the writer's transaction by construction, and independent+// of the legacy foreign keys.+//+// These owner-row locks add a second, narrower barrier — they also block+// ownership-changing UPDATEs of tasks that already exist — and cost nothing to+// hold, since teardown deletes these very rows a few steps later. They are taken+// set-based and return no ids, so a workspace with a huge owner set costs no+// memory here.+//+// The wait is bounded by SET LOCAL lock_timeout, and taking these locks can+// deadlock against a concurrent task update that locks in the opposite order+// (task row, then owner); both outcomes surface as a retryable 503.+func lockWorkspaceTaskOwners(ctx context.Context, qtx *db.Queries, workspaceID pgtype.UUID) error {+ if err := qtx.LockWorkspaceTaskOwnerAgents(ctx, workspaceID); err != nil {+ return fmt.Errorf("lock workspace agents: %w", err)+ }+ if err := qtx.LockWorkspaceTaskOwnerIssues(ctx, workspaceID); err != nil {+ return fmt.Errorf("lock workspace issues: %w", err)+ }+ if err := qtx.LockWorkspaceTaskOwnerRuntimes(ctx, workspaceID); err != nil {+ return fmt.Errorf("lock workspace runtimes: %w", err)+ }+ return nil+}+func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "id")@@ -880,6 +1127,13 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "set teardown mode",run: func() error { return qtx.SetWorkspaceTeardownMode(ctx) },},+ {+ // Fences task enqueue / reassignment for the rest of the+ // transaction. Must run before anything sweeps tasks — see+ // lockWorkspaceTaskOwners.+ name: "lock task owners",+ run: func() error { return lockWorkspaceTaskOwners(ctx, qtx, requester.WorkspaceID) },+ },{name: "prepare relationship graph",run: func() error { return qtx.PrepareWorkspaceDeletionLinks(ctx, requester.WorkspaceID) },@@ -897,6 +1151,13 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "lock task usage rollup",run: func() error { return qtx.LockTaskUsageRollupForWorkspaceDelete(ctx) },},+ {+ // Bounded batches, after the rollup lock because it deletes+ // task_usage. Replaces both the task-keyed arms of the old leaf+ // data statement and the separate whole-workspace task delete.+ name: "delete tasks",+ run: func() error { return deleteWorkspaceTasks(ctx, qtx, requester.WorkspaceID) },+ },{name: "delete leaf data",run: func() error { return qtx.DeleteWorkspaceLeafData(ctx, requester.WorkspaceID) },@@ -905,10 +1166,6 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "delete autopilot runs",run: func() error { return qtx.DeleteWorkspaceAutopilotRuns(ctx, requester.WorkspaceID) },},- {- name: "delete tasks",- run: func() error { return qtx.DeleteWorkspaceTasks(ctx, requester.WorkspaceID) },- },{name: "delete chat messages",run: func() error { return qtx.DeleteWorkspaceChatMessages(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.gonew file mode 100644index 0000000000..b85fcedfc1--- /dev/null+++ b/server/internal/handler/workspace_delete_fence_test.go@@ -0,0 +1,772 @@+package handler++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// enqueueViaRealQuery creates a task through the generated CreateAgentTask query —+// the actual production enqueue path, fence included. Raw INSERTs in tests would+// bypass the fence, which lives in the application SQL rather than in a trigger.+func enqueueViaRealQuery(ctx context.Context, q *db.Queries, agentID, runtimeID, issueID string) error {+ params := db.CreateAgentTaskParams{+ AgentID: parseUUID(agentID),+ RuntimeID: parseUUID(runtimeID),+ Priority: 0,+ }+ if issueID != "" {+ params.IssueID = parseUUID(issueID)+ }+ _, err := q.CreateAgentTask(ctx, params)+ return err+}++// waitForBlockedWriter blocks until the given backend is waiting on a lock, so a+// race test can be sure the writer really is queued before the other side commits.+// The pid comes from the writer itself rather than being guessed from statement+// text, which on a shared test database could match an unrelated backend. Fails the+// test on timeout rather than proceeding, so a missed race shows up as a failure+// instead of a vacuous pass.+func waitForBlockedWriter(t *testing.T, ctx context.Context, pid int32) {+ t.Helper()+ deadline := time.Now().Add(10 * time.Second)+ for time.Now().Before(deadline) {+ var waiting bool+ if err := testPool.QueryRow(ctx, `+SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity+ WHERE pid = $1 AND state = 'active' AND wait_event_type = 'Lock'+)+`, pid).Scan(&waiting); err != nil {+ t.Fatalf("poll pg_stat_activity: %v", err)+ }+ if waiting {+ return+ }+ time.Sleep(20 * time.Millisecond)+ }+ t.Fatalf("backend %d never parked on a lock; the race was not set up", pid)+}++// TestTaskOwnershipWritesCallTheFence is the guard that keeps the fence from being+// a convention. Every statement that inserts an agent_task_queue row, or assigns+// one of its ownership columns, has to call lock_task_owner_rows — a new+// write path that forgets it would silently reopen the insert-after-sweep window+// that MUL-5999's teardown depends on being closed.+//+// This is the trade for not using a row trigger: the write path names its own+// fence, and CI checks that it did.+func TestTaskOwnershipWritesCallTheFence(t *testing.T) {+ queryDir := filepath.Join("..", "..", "pkg", "db", "queries")+ entries, err := os.ReadDir(queryDir)+ if err != nil {+ t.Fatalf("read query dir: %v", err)+ }++ nameRe := regexp.MustCompile(`(?m)^-- name: (\S+)`)+ // Go's regexp has no lookahead, so the SET clause is isolated first and its+ // ownership assignments are inspected individually. Clearing runtime_id cannot+ // move a task into another workspace, so `= NULL` is exempt; teardown's own+ // detach only touches parent_task_id.+ setClauseRe := regexp.MustCompile(`(?is)\bSET\b(.*?)(?:\bWHERE\b|\bFROM\b|\bRETURNING\b|;)`)+ ownerAssignRe := regexp.MustCompile(`(?i)\b(agent_id|issue_id|runtime_id)\s*=\s*(\S+)`)++ assignsOwner := func(code string) bool {+ for _, clause := range setClauseRe.FindAllStringSubmatch(code, -1) {+ for _, assign := range ownerAssignRe.FindAllStringSubmatch(clause[1], -1) {+ if !strings.EqualFold(strings.TrimSuffix(assign[2], ","), "NULL") {+ return true+ }+ }+ }+ return false+ }++ checked := 0+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {+ continue+ }+ body, err := os.ReadFile(filepath.Join(queryDir, entry.Name()))+ if err != nil {+ t.Fatalf("read %s: %v", entry.Name(), err)+ }+ text := string(body)+ matches := nameRe.FindAllStringSubmatchIndex(text, -1)+ for i, m := range matches {+ stop := len(text)+ if i+1 < len(matches) {+ stop = matches[i+1][0]+ }+ stmt := text[m[0]:stop]+ name := text[m[2]:m[3]]+ // Strip comment lines so prose cannot satisfy or trip the check.+ var sqlOnly strings.Builder+ for _, line := range strings.Split(stmt, "\n") {+ if strings.HasPrefix(strings.TrimSpace(line), "--") {+ continue+ }+ sqlOnly.WriteString(line)+ sqlOnly.WriteString("\n")+ }+ code := sqlOnly.String()++ writesOwnership := strings.Contains(code, "INSERT INTO agent_task_queue") ||+ (strings.Contains(code, "UPDATE agent_task_queue") && assignsOwner(code))+ if !writesOwnership {+ continue+ }+ checked+++ if !strings.Contains(code, "lock_task_owner_rows(") {+ t.Errorf("%s: %s writes agent_task_queue ownership without calling "++ "lock_task_owner_rows; that reopens the workspace-delete race "++ "(see migration 284)", entry.Name(), name)+ }+ }+ }+ if checked < 9 {+ t.Errorf("only %d ownership-writing statements found; the detector probably stopped matching", checked)+ }+}++// TestTaskWriteFence_BlocksOnWorkspaceLockAlone shows the fence, and only the+// fence, standing between a concurrent enqueue and a workspace being torn down.+//+// The holder locks ONLY the workspace row — no agent, issue or runtime row — so no+// foreign key on agent_task_queue has anything to block on: none of them+// references workspace. Anything that blocks here is the fence taking FOR KEY+// SHARE on the owners' workspace row from inside the writer's own statement.+func TestTaskWriteFence_BlocksOnWorkspaceLockAlone(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "fenceonly")++ holder, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin holder: %v", err)+ }+ defer holder.Rollback(ctx)+ // Exactly what LockWorkspaceForDelete does, and nothing else.+ if _, err := holder.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, f.victimID); err != nil {+ t.Fatalf("lock workspace row: %v", err)+ }++ blockedEnqueue := func(name, agentID, runtimeID, issueID string) {+ t.Helper()+ writer, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("%s: begin: %v", name, err)+ }+ defer writer.Rollback(ctx)+ if _, err := writer.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("%s: set lock_timeout: %v", name, err)+ }+ err = enqueueViaRealQuery(ctx, testHandler.Queries.WithTx(writer), agentID, runtimeID, issueID)+ if err == nil {+ t.Errorf("%s: enqueue committed while the workspace row was locked; the fence is not in the write path", name)+ return+ }+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "55P03" {+ t.Errorf("%s: got %v, want lock_not_available (55P03)", name, err)+ }+ }++ blockedEnqueue("enqueue via the victim's agent", f.victimAgent, f.neighbourRuntime, f.neighbourIssue)+ blockedEnqueue("enqueue via the victim's runtime", f.neighbourAgent, f.victimRuntime, f.neighbourIssue)+ blockedEnqueue("enqueue via the victim's issue", f.neighbourAgent, f.neighbourRuntime, f.victimIssue)++ // Reassignment onto the victim's runtime is fenced too.+ reassign, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin reassign: %v", err)+ }+ defer reassign.Rollback(ctx)+ if _, err := reassign.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("reassign: set lock_timeout: %v", err)+ }+ _, err = testHandler.Queries.WithTx(reassign).ReassignTasksToRuntime(ctx, db.ReassignTasksToRuntimeParams{+ NewRuntimeID: parseUUID(f.victimRuntime),+ OldRuntimeID: parseUUID(f.neighbourRuntime),+ })+ var pgErr *pgconn.PgError+ if err == nil || !errors.As(err, &pgErr) || pgErr.Code != "55P03" {+ t.Errorf("reassignment onto the victim's runtime: got %v, want lock_not_available (55P03)", err)+ }++ // A workspace nobody is deleting is unaffected.+ unrelated, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin unrelated: %v", err)+ }+ defer unrelated.Rollback(ctx)+ if _, err := unrelated.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("unrelated: set lock_timeout: %v", err)+ }+ if err := enqueueViaRealQuery(ctx, testHandler.Queries.WithTx(unrelated),+ f.neighbourAgent, f.neighbourRuntime, f.neighbourIssue); err != nil {+ t.Errorf("neighbour-only enqueue was blocked by the victim's workspace lock: %v", err)+ }++ // Status-only updates are the hot path and must not touch the fence at all.+ statusUpdate, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin status update: %v", err)+ }+ defer statusUpdate.Rollback(ctx)+ if _, err := statusUpdate.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("status update: set lock_timeout: %v", err)+ }+ if _, err := statusUpdate.Exec(ctx,+ `UPDATE agent_task_queue SET status = 'failed' WHERE id = $1`, f.taskViaAgent); err != nil {+ t.Errorf("status-only update was blocked: %v", err)+ }+}++// TestTaskWriteFence_QueuedWriterCannotLandAfterTeardownCommits is the race the+// review asked for, run as an actual race: a writer queues behind the workspace+// lock while teardown is in flight, teardown commits, and the writer must then be+// unable to put a row in the table.+//+// It also discriminates the fence from the foreign keys. The writer's failure is+// "no row written" — CreateAgentTask is a :one, so it comes back as+// pgx.ErrNoRows because the fence's predicate was false. An FK doing the work+// instead would surface as SQLSTATE 23503, which the assertion rejects.+func TestTaskWriteFence_QueuedWriterCannotLandAfterTeardownCommits(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "queuedwriter")++ teardown, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin teardown: %v", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = teardown.Rollback(ctx)+ }+ }()++ // The teardown transaction, in the order the handler does it.+ if _, err := teardown.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, f.victimID); err != nil {+ t.Fatalf("lock workspace: %v", err)+ }++ var wg sync.WaitGroup+ var writerErr error+ writerPID := make(chan int32, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ bg := context.Background()+ // A dedicated connection so the writer can report the backend the race+ // waits on, and so the enqueue still runs as its own autocommit statement+ // the way a real one does.+ conn, err := testPool.Acquire(bg)+ if err != nil {+ writerErr = err+ close(writerPID)+ return+ }+ defer conn.Release()++ var pid int32+ if err := conn.QueryRow(bg, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {+ writerErr = err+ close(writerPID)+ return+ }+ writerPID <- pid++ // No lock_timeout: this writer is supposed to wait for teardown, which is+ // what a real enqueue arriving mid-teardown does.+ writerErr = enqueueViaRealQuery(bg, db.New(conn), f.victimAgent, f.victimRuntime, f.victimIssue)+ }()++ pid, ok := <-writerPID+ if !ok {+ wg.Wait()+ t.Fatalf("writer could not start: %v", writerErr)+ }++ // Wait until the writer is genuinely parked on a lock rather than trusting a+ // fixed sleep: on a loaded machine a sleep can elapse before the writer even+ // reaches the fence, and the test would then pass without exercising the race.+ waitForBlockedWriter(t, ctx, pid)++ if _, err := teardown.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, f.victimID); err != nil {+ t.Fatalf("delete workspace: %v", err)+ }+ if err := teardown.Commit(ctx); err != nil {+ t.Fatalf("commit teardown: %v", err)+ }+ committed = true++ wg.Wait()++ if writerErr == nil {+ t.Fatal("the queued enqueue landed a task after teardown committed; the fence did not hold")+ }+ if !errors.Is(writerErr, pgx.ErrNoRows) {+ var pgErr *pgconn.PgError+ if errors.As(writerErr, &pgErr) && pgErr.Code == "23503" {+ t.Fatalf("the write was rejected by a foreign key (%s), not by the fence; "++ "the fence must hold on its own once the legacy FKs go away", pgErr.Code)+ }+ t.Fatalf("writer error = %v, want pgx.ErrNoRows from the fence returning false", writerErr)+ }++ var leftover int+ if err := testPool.QueryRow(ctx, `+SELECT count(*) FROM agent_task_queue WHERE agent_id = $1 OR runtime_id = $2 OR issue_id = $3+`, f.victimAgent, f.victimRuntime, f.victimIssue).Scan(&leftover); err != nil {+ t.Fatalf("count leftovers: %v", err)+ }+ if leftover != 0 {+ t.Errorf("%d task rows are left pointing at the deleted workspace's owners", leftover)+ }+}++// TestTaskWriteFence_LocksWorkspacesInIDOrder covers the deadlock surface the+// review flagged: a task may reference owners in different workspaces, so the+// fence can lock more than one workspace row, and two writers touching the same+// pair from opposite directions must not be able to take them in opposite orders.+//+// The fence sorts by workspace id, so both writers queue on the lower id first.+// The test runs the two mirrored writes concurrently and requires that both+// succeed — a deadlock would surface as 40P01 on one of them.+func TestTaskWriteFence_LocksWorkspacesInIDOrder(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "lockorder")++ const rounds = 25++ // One pending task per (issue, agent) is enforced by a partial unique index, so+ // each round needs its own issue pair; otherwise the rounds collide on that+ // index instead of exercising the lock order.+ victimIssues := make([]string, rounds)+ neighbourIssues := make([]string, rounds)+ for i := 0; i < rounds; i++ {+ if err := testPool.QueryRow(ctx, `+INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)+VALUES ($1, $2, 'member', $3, $4) RETURNING id+`, f.victimID, "lock-order victim "+strconv.Itoa(i), testUserID, i+100).Scan(&victimIssues[i]); err != nil {+ t.Fatalf("seed victim issue %d: %v", i, err)+ }+ if err := testPool.QueryRow(ctx, `+INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)+VALUES ($1, $2, 'member', $3, $4) RETURNING id+`, f.neighbourID, "lock-order neighbour "+strconv.Itoa(i), testUserID, i+100).Scan(&neighbourIssues[i]); err != nil {+ t.Fatalf("seed neighbour issue %d: %v", i, err)+ }+ }++ var wg sync.WaitGroup+ errs := make([]error, 2*rounds)+ for i := 0; i < rounds; i++ {+ wg.Add(2)+ // Owners drawn from both workspaces, in mirrored roles.+ go func(i int) {+ defer wg.Done()+ errs[2*i] = enqueueViaRealQuery(ctx, testHandler.Queries,+ f.victimAgent, f.neighbourRuntime, neighbourIssues[i])+ }(i)+ go func(i int) {+ defer wg.Done()+ errs[2*i+1] = enqueueViaRealQuery(ctx, testHandler.Queries,+ f.neighbourAgent, f.victimRuntime, victimIssues[i])+ }(i)+ }+ wg.Wait()++ for i, err := range errs {+ if err == nil {+ continue+ }+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "40P01" {+ t.Fatalf("write %d deadlocked (40P01): the fence is not locking workspaces in a fixed order", i)+ }+ t.Errorf("write %d failed: %v", i, err)+ }++ if _, err := testPool.Exec(ctx, `+DELETE FROM agent_task_queue+WHERE (agent_id = $1 AND runtime_id = $2) OR (agent_id = $3 AND runtime_id = $4)+`, f.victimAgent, f.neighbourRuntime, f.neighbourAgent, f.victimRuntime); err != nil {+ t.Fatalf("clean up: %v", err)+ }+}++// TestMergeLegacyRuntime_KeepsOldRuntimeWhenFenceRefuses is the regression test+// for the failure mode the review found: the fence refusing looked exactly like+// "the old runtime had no tasks", so the merge went on to delete the old runtime+// and agent_task_queue's ON DELETE CASCADE quietly took its history with it.+//+// Here the merge target has vanished before the reassignment runs, so the fence+// returns false. The old runtime and its task must both survive, and nothing may+// be recorded on the target.+func TestMergeLegacyRuntime_KeepsOldRuntimeWhenFenceRefuses(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "mergefence")++ // A target runtime id that does not resolve — the same state a merge sees when+ // the target's workspace was torn down a moment ago.+ vanishedTarget := parseUUID("00000000-0000-0000-0000-0000000000fe")++ err := testHandler.mergeLegacyRuntime(ctx, vanishedTarget, parseUUID(f.victimRuntime), "legacy-daemon", "delete-test")+ if !errors.Is(err, errRuntimeMergeFenced) {+ t.Fatalf("mergeLegacyRuntime = %v, want errRuntimeMergeFenced", err)+ }++ if !rowExists(t, "agent_runtime", f.victimRuntime) {+ t.Error("the old runtime was deleted even though the reassignment was fenced")+ }+ if !rowExists(t, "agent_task_queue", f.taskViaRuntime) {+ t.Error("the old runtime's task was deleted by the cascade behind a fenced merge")+ }+ var stillOnOldRuntime bool+ if err := testPool.QueryRow(ctx,+ `SELECT runtime_id = $1 FROM agent_task_queue WHERE id = $2`,+ f.victimRuntime, f.taskViaRuntime).Scan(&stillOnOldRuntime); err != nil {+ t.Fatalf("read task runtime: %v", err)+ }+ if !stillOnOldRuntime {+ t.Error("the task was re-pointed at the vanished runtime")+ }++ // And the happy path still merges, so the abort is not unconditional.+ var freshRuntime string+ if err := testPool.QueryRow(ctx, `+INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)+VALUES ($1, 'merge target', 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $2)+RETURNING id+`, f.victimID, testUserID).Scan(&freshRuntime); err != nil {+ t.Fatalf("create merge target: %v", err)+ }+ if err := testHandler.mergeLegacyRuntime(ctx, parseUUID(freshRuntime), parseUUID(f.victimRuntime),+ "legacy-daemon", "delete-test"); err != nil {+ t.Fatalf("merge onto a live runtime: %v", err)+ }+ if rowExists(t, "agent_runtime", f.victimRuntime) {+ t.Error("the old runtime survived a merge that should have completed")+ }+ if !rowExists(t, "agent_task_queue", f.taskViaRuntime) {+ t.Error("a completed merge lost the old runtime's task")+ }+}++// TestMergeLegacyRuntime_RollsBackWhenAStepFails is the fault-injection half of the+// merge contract: the four statements have to land together or not at all.+//+// Run as autocommit statements the merge could commit the task reassignment and+// then fail on the agent reassignment, leaving tasks on the new runtime and their+// agents on the old one while daemon registration still reported success. Worse,+// the fence's workspace lock ended with its own statement, so a teardown could slip+// into that gap, delete the target runtime and clear runtime_id on the tasks that+// had just moved — history the next merge could no longer find, because it looks up+// tasks by the OLD runtime id.+//+// The failure is injected in the database rather than through a code seam, so the+// test exercises the real statements: a trigger makes any agent row moving onto the+// merge target raise.+func TestMergeLegacyRuntime_RollsBackWhenAStepFails(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "mergerollback")++ var target string+ if err := testPool.QueryRow(ctx, `+INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)+VALUES ($1, 'rollback merge target', 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $2)+RETURNING id+`, f.victimID, testUserID).Scan(&target); err != nil {+ t.Fatalf("create merge target: %v", err)+ }++ if _, err := testPool.Exec(ctx, `+CREATE OR REPLACE FUNCTION mul5999_fail_agent_move() RETURNS trigger LANGUAGE plpgsql AS $fn$+BEGIN+ IF NEW.name = 'victim agent' AND NEW.runtime_id IS DISTINCT FROM OLD.runtime_id THEN+ RAISE EXCEPTION 'injected failure moving agent onto the merge target';+ END IF;+ RETURN NEW;+END+$fn$;+`); err != nil {+ t.Fatalf("create injection function: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+CREATE TRIGGER mul5999_fail_agent_move+BEFORE UPDATE OF runtime_id ON agent+FOR EACH ROW EXECUTE FUNCTION mul5999_fail_agent_move()+`); err != nil {+ t.Fatalf("create injection trigger: %v", err)+ }+ t.Cleanup(func() {+ bg := context.Background()+ _, _ = testPool.Exec(bg, `DROP TRIGGER IF EXISTS mul5999_fail_agent_move ON agent`)+ _, _ = testPool.Exec(bg, `DROP FUNCTION IF EXISTS mul5999_fail_agent_move()`)+ })++ err := testHandler.mergeLegacyRuntime(ctx, parseUUID(target), parseUUID(f.victimRuntime),+ "legacy-daemon", "delete-test")+ if err == nil {+ t.Fatal("merge reported success even though the agent reassignment failed")+ }+ if !strings.Contains(err.Error(), "reassign agents") {+ t.Errorf("error = %v, want the agent reassignment failure", err)+ }++ // Everything must look exactly as it did before the call.+ var taskRuntime, agentRuntime string+ if err := testPool.QueryRow(ctx,+ `SELECT runtime_id FROM agent_task_queue WHERE id = $1`, f.taskViaRuntime).Scan(&taskRuntime); err != nil {+ t.Fatalf("read task runtime: %v", err)+ }+ if taskRuntime != f.victimRuntime {+ t.Errorf("task moved to %s; the task reassignment was not rolled back", taskRuntime)+ }+ if err := testPool.QueryRow(ctx,+ `SELECT runtime_id FROM agent WHERE id = $1`, f.victimAgent).Scan(&agentRuntime); err != nil {+ t.Fatalf("read agent runtime: %v", err)+ }+ if agentRuntime != f.victimRuntime {+ t.Errorf("agent runtime = %s, want the original %s", agentRuntime, f.victimRuntime)+ }+ if !rowExists(t, "agent_runtime", f.victimRuntime) {+ t.Error("the old runtime was deleted by a merge that failed")+ }+ if !rowExists(t, "agent_runtime", target) {+ t.Error("the merge target disappeared")+ }+ var legacyRecorded bool+ if err := testPool.QueryRow(ctx,+ `SELECT legacy_daemon_id IS NOT NULL FROM agent_runtime WHERE id = $1`, target).Scan(&legacyRecorded); err != nil {+ t.Fatalf("read legacy daemon id: %v", err)+ }+ if legacyRecorded {+ t.Error("the legacy daemon_id audit write survived a rolled-back merge")+ }++ // With the injection removed the same merge completes, so the rollback above+ // was not just a permanently broken fixture.+ if _, err := testPool.Exec(ctx, `DROP TRIGGER mul5999_fail_agent_move ON agent`); err != nil {+ t.Fatalf("drop injection trigger: %v", err)+ }+ if err := testHandler.mergeLegacyRuntime(ctx, parseUUID(target), parseUUID(f.victimRuntime),+ "legacy-daemon", "delete-test"); err != nil {+ t.Fatalf("merge after removing the injection: %v", err)+ }+ if rowExists(t, "agent_runtime", f.victimRuntime) {+ t.Error("the old runtime survived a completed merge")+ }+}++// TestRuntimeMerge_LateWriteToOldRuntimeIsFencedNotCascaded is the regression test+// for the race the review reproduced: an enqueue that arrives against the OLD+// runtime after the merge has scanned its tasks.+//+// Before this fix the writer was not blocked at all — writers hold FOR KEY SHARE on+// the workspace and so did the merge, and two KEY SHARE locks do not conflict — so+// the insert committed and was then silently removed by agent_task_queue's+// ON DELETE CASCADE when the merge deleted the old runtime. The reviewer measured+// exactly that: `INSERT 0 1`, then the row count going from 1 to 0.+//+// The merge's statement sequence is driven by hand here so it can be stopped after+// the agent update and before the old runtime is deleted, which is where the window+// used to be. The writer must block on the fence, and once the merge commits it must+// come back as "no row written" — not 23503, and not a row that exists briefly and+// then disappears.+func TestRuntimeMerge_LateWriteToOldRuntimeIsFencedNotCascaded(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "latewrite")++ var target string+ if err := testPool.QueryRow(ctx, `+INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)+VALUES ($1, 'late write merge target', 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $2)+RETURNING id+`, f.victimID, testUserID).Scan(&target); err != nil {+ t.Fatalf("create merge target: %v", err)+ }++ merge, err := testHandler.TxStarter.Begin(ctx)+ if err != nil {+ t.Fatalf("begin merge tx: %v", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = merge.Rollback(ctx)+ }+ }()+ qtx := testHandler.Queries.WithTx(merge)+ runtimeIDs := []pgtype.UUID{parseUUID(f.victimRuntime), parseUUID(target)}++ // The merge, up to the point just before the old runtime is deleted.+ if err := qtx.LockWorkspaceForRuntimeMerge(ctx, runtimeIDs); err != nil {+ t.Fatalf("lock workspace: %v", err)+ }+ locked, err := qtx.LockRuntimesForMerge(ctx, runtimeIDs)+ if err != nil {+ t.Fatalf("lock runtimes: %v", err)+ }+ if len(locked) != 2 {+ t.Fatalf("locked %d runtimes, want 2", len(locked))+ }+ reassignment, err := qtx.ReassignTasksToRuntime(ctx, db.ReassignTasksToRuntimeParams{+ NewRuntimeID: parseUUID(target),+ OldRuntimeID: parseUUID(f.victimRuntime),+ })+ if err != nil {+ t.Fatalf("reassign tasks: %v", err)+ }+ if !reassignment.FenceOk {+ t.Fatal("the merge's own fence refused a live target")+ }+ if _, err := qtx.ReassignAgentsToRuntime(ctx, db.ReassignAgentsToRuntimeParams{+ NewRuntimeID: parseUUID(target),+ OldRuntimeID: parseUUID(f.victimRuntime),+ }); err != nil {+ t.Fatalf("reassign agents: %v", err)+ }++ // A concurrent enqueue that still believes in the old runtime.+ var wg sync.WaitGroup+ var writerErr error+ writerPID := make(chan int32, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ bg := context.Background()+ conn, err := testPool.Acquire(bg)+ if err != nil {+ writerErr = err+ close(writerPID)+ return+ }+ defer conn.Release()+ var pid int32+ if err := conn.QueryRow(bg, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {+ writerErr = err+ close(writerPID)+ return+ }+ writerPID <- pid+ writerErr = enqueueViaRealQuery(bg, db.New(conn), f.victimAgent, f.victimRuntime, f.victimIssue)+ }()++ pid, ok := <-writerPID+ if !ok {+ wg.Wait()+ t.Fatalf("writer could not start: %v", writerErr)+ }+ // The whole point: the writer must be parked, not sailing past the merge.+ waitForBlockedWriter(t, ctx, pid)++ if err := qtx.DeleteAgentRuntime(ctx, parseUUID(f.victimRuntime)); err != nil {+ t.Fatalf("delete old runtime: %v", err)+ }+ if err := merge.Commit(ctx); err != nil {+ t.Fatalf("commit merge: %v", err)+ }+ committed = true++ wg.Wait()++ if writerErr == nil {+ t.Fatal("the late enqueue landed against a runtime the merge was deleting; " ++ "it would have been removed by ON DELETE CASCADE")+ }+ var pgErr *pgconn.PgError+ if errors.As(writerErr, &pgErr) && pgErr.Code == "23503" {+ t.Fatalf("the late write was rejected by a foreign key (%s), not by the fence", pgErr.Code)+ }+ if !errors.Is(writerErr, pgx.ErrNoRows) {+ t.Fatalf("writer error = %v, want pgx.ErrNoRows from the fence returning false", writerErr)+ }++ // The merge's own history survived, and nothing is pointing at the deleted runtime.+ if !rowExists(t, "agent_task_queue", f.taskViaRuntime) {+ t.Error("the merge lost the old runtime's task")+ }+ var onTarget bool+ if err := testPool.QueryRow(ctx,+ `SELECT runtime_id = $1 FROM agent_task_queue WHERE id = $2`, target, f.taskViaRuntime).Scan(&onTarget); err != nil {+ t.Fatalf("read task runtime: %v", err)+ }+ if !onTarget {+ t.Error("the task was not moved onto the merge target")+ }+}++// TestLockTaskOwnerRows_RejectsUnresolvableOwner pins the hole the review+// found in the first version of this fence: counting only the owners that still+// resolve made a deleted owner invisible, and the statement fell through to the+// foreign key. A reference that does not resolve must make the predicate false on+// its own.+func TestLockTaskOwnerRows_RejectsUnresolvableOwner(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "unresolvable")+ missing := "00000000-0000-0000-0000-0000000000ff"++ for name, args := range map[string][3]any{+ "missing agent": {missing, nil, nil},+ "missing issue": {nil, missing, nil},+ "missing runtime": {nil, nil, missing},+ "one of three owners missing": {f.victimAgent, missing, f.victimRuntime},+ } {+ var ok bool+ if err := testPool.QueryRow(ctx,+ `SELECT lock_task_owner_rows($1, $2, $3)`, args[0], args[1], args[2]).Scan(&ok); err != nil {+ t.Fatalf("%s: %v", name, err)+ }+ if ok {+ t.Errorf("%s: fence returned true; the write would fall through to the foreign key", name)+ }+ }++ var ok bool+ if err := testPool.QueryRow(ctx, `SELECT lock_task_owner_rows($1, $2, $3)`,+ f.victimAgent, f.victimIssue, f.victimRuntime).Scan(&ok); err != nil {+ t.Fatalf("all owners present: %v", err)+ }+ if !ok {+ t.Error("fence returned false for a fully resolvable row")+ }+}++var _ = pgtype.UUID{}diff --git a/server/internal/handler/workspace_delete_task_discovery_test.go b/server/internal/handler/workspace_delete_task_discovery_test.gonew file mode 100644index 0000000000..dee38fe870--- /dev/null+++ b/server/internal/handler/workspace_delete_task_discovery_test.go@@ -0,0 +1,615 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// workspaceDeletePathFixture builds the ownership shapes teardown has to handle:+// one task reachable from the victim workspace only through agent_id, one only+// through issue_id, one only through runtime_id, and one that belongs entirely to+// a neighbour workspace and must survive.+//+// The tokens cover the three explicit task_token paths: one owned by the victim+// workspace, one whose workspace_id points at the neighbour while its TASK is the+// victim's, one whose workspace_id points at the neighbour while its AGENT is the+// victim's, and one that is entirely the neighbour's.+type workspaceDeletePathFixture struct {+ victimID string+ neighbourID string++ victimAgent string+ victimIssue string+ victimRuntime string++ neighbourAgent string+ neighbourIssue string+ neighbourRuntime string++ taskViaAgent string+ taskViaIssue string+ taskViaRuntime string+ neighbourTask string++ victimToken string+ crossTaskToken string+ crossAgentToken string+ neighbourOnlyToken string+}++func newWorkspaceDeletePathFixture(t *testing.T, slugSuffix string) workspaceDeletePathFixture {+ t.Helper()+ ctx := context.Background()++ victimSlug := "handler-tests-delete-paths-victim-" + slugSuffix+ neighbourSlug := "handler-tests-delete-paths-neighbour-" + slugSuffix+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = ANY($1::text[])`,+ []string{victimSlug, neighbourSlug})++ newWorkspace := func(name, slug string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+INSERT INTO workspace (name, slug) VALUES ($1, $2) RETURNING id+`, name, slug).Scan(&id); err != nil {+ t.Fatalf("create workspace %s: %v", slug, err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, id)+ })+ return id+ }+ f := workspaceDeletePathFixture{+ victimID: newWorkspace("Delete Paths Victim "+slugSuffix, victimSlug),+ neighbourID: newWorkspace("Delete Paths Neighbour "+slugSuffix, neighbourSlug),+ }++ if _, err := testPool.Exec(ctx, `+INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')+`, f.victimID, testUserID); err != nil {+ t.Fatalf("create owner member: %v", err)+ }++ newRuntime := func(wsID, name string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)+VALUES ($1, $2, 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $3)+RETURNING id+`, wsID, name, testUserID).Scan(&id); err != nil {+ t.Fatalf("create runtime %s: %v", name, err)+ }+ return id+ }+ newAgent := func(wsID, runtimeID, name string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, owner_id)+VALUES ($1, $2, 'cloud', '{}'::jsonb, $3, $4)+RETURNING id+`, wsID, name, runtimeID, testUserID).Scan(&id); err != nil {+ t.Fatalf("create agent %s: %v", name, err)+ }+ return id+ }+ newIssue := func(wsID, title string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+INSERT INTO issue (workspace_id, title, creator_type, creator_id)+VALUES ($1, $2, 'member', $3)+RETURNING id+`, wsID, title, testUserID).Scan(&id); err != nil {+ t.Fatalf("create issue %s: %v", title, err)+ }+ return id+ }++ f.victimRuntime = newRuntime(f.victimID, "victim runtime")+ f.victimAgent = newAgent(f.victimID, f.victimRuntime, "victim agent")+ f.victimIssue = newIssue(f.victimID, "victim issue")+ f.neighbourRuntime = newRuntime(f.neighbourID, "neighbour runtime")+ f.neighbourAgent = newAgent(f.neighbourID, f.neighbourRuntime, "neighbour agent")+ f.neighbourIssue = newIssue(f.neighbourID, "neighbour issue")++ f.taskViaAgent = insertDeletePathTask(t, f.victimAgent, f.neighbourIssue, f.neighbourRuntime)+ f.taskViaIssue = insertDeletePathTask(t, f.neighbourAgent, f.victimIssue, f.neighbourRuntime)+ f.taskViaRuntime = insertDeletePathTask(t, f.neighbourAgent, f.neighbourIssue, f.victimRuntime)+ f.neighbourTask = insertDeletePathTask(t, f.neighbourAgent, f.neighbourIssue, f.neighbourRuntime)++ f.victimToken = insertDeletePathToken(t, "mul5999-victim-"+slugSuffix, f.taskViaAgent, f.victimAgent, f.victimID)+ f.crossTaskToken = insertDeletePathToken(t, "mul5999-cross-task-"+slugSuffix, f.taskViaIssue, f.neighbourAgent, f.neighbourID)+ f.crossAgentToken = insertDeletePathToken(t, "mul5999-cross-agent-"+slugSuffix, f.neighbourTask, f.victimAgent, f.neighbourID)+ f.neighbourOnlyToken = insertDeletePathToken(t, "mul5999-neighbour-"+slugSuffix, f.neighbourTask, f.neighbourAgent, f.neighbourID)++ t.Cleanup(func() {+ bg := context.Background()+ _, _ = testPool.Exec(bg, `DELETE FROM task_token WHERE id = ANY($1::uuid[])`,+ []string{f.victimToken, f.crossTaskToken, f.crossAgentToken, f.neighbourOnlyToken})+ _, _ = testPool.Exec(bg, `DELETE FROM agent_task_queue WHERE id = ANY($1::uuid[])`,+ []string{f.taskViaAgent, f.taskViaIssue, f.taskViaRuntime, f.neighbourTask})+ })++ return f+}++func insertDeletePathTask(t *testing.T, agentID, issueID, runtimeID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(), `+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+VALUES ($1, $2, $3, 'completed', now())+RETURNING id+`, agentID, issueID, runtimeID).Scan(&id); err != nil {+ t.Fatalf("create task: %v", err)+ }+ return id+}++func insertDeletePathToken(t *testing.T, hash, taskID, agentID, wsID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(), `+INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)+VALUES ($1, $2, $3, $4, $5, now() + interval '1 hour')+RETURNING id+`, hash, taskID, agentID, wsID, testUserID).Scan(&id); err != nil {+ t.Fatalf("create task token %s: %v", hash, err)+ }+ return id+}++func rowExists(t *testing.T, table, id string) bool {+ t.Helper()+ var found bool+ if err := testPool.QueryRow(context.Background(),+ `SELECT EXISTS (SELECT 1 FROM `+table+` WHERE id = $1)`, id).Scan(&found); err != nil {+ t.Fatalf("check %s %s: %v", table, id, err)+ }+ return found+}++// TestDeleteWorkspaceTasks_IsSelfSufficientWithoutCascades asserts that the task+// sweep removes the rows on its own, inside the transaction and before any owner+// row is deleted. That ordering is the whole point: the legacy FK cascades are+// documented as an expand-phase safety net, so an assertion taken after the+// handler has finished cannot tell teardown apart from a cascade doing the work.+func TestDeleteWorkspaceTasks_IsSelfSufficientWithoutCascades(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "selfsufficient")++ tx, err := testHandler.TxStarter.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ qtx := testHandler.Queries.WithTx(tx)++ if err := qtx.SetWorkspaceTeardownMode(ctx); err != nil {+ t.Fatalf("set teardown mode: %v", err)+ }+ if err := lockWorkspaceTaskOwners(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("lock task owners: %v", err)+ }+ if err := deleteWorkspaceTasks(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("deleteWorkspaceTasks: %v", err)+ }++ // Still inside the transaction: no agent, issue or runtime row has been+ // deleted, so nothing here can be attributed to ON DELETE CASCADE.+ count := func(query string, args ...any) int {+ var n int+ if err := tx.QueryRow(ctx, query, args...).Scan(&n); err != nil {+ t.Fatalf("count: %v", err)+ }+ return n+ }+ if n := count(`SELECT count(*) FROM agent_task_queue WHERE id = ANY($1::uuid[])`,+ []string{f.taskViaAgent, f.taskViaIssue, f.taskViaRuntime}); n != 0 {+ t.Errorf("%d of the 3 ownership-path tasks survived the sweep", n)+ }+ if n := count(`SELECT count(*) FROM task_token WHERE id = ANY($1::uuid[])`,+ []string{f.victimToken, f.crossTaskToken, f.crossAgentToken}); n != 0 {+ t.Errorf("%d of the 3 task_token paths survived the sweep", n)+ }+ if n := count(`SELECT count(*) FROM agent WHERE id = $1`, f.victimAgent); n != 1 {+ t.Fatalf("victim agent row was deleted by the task sweep; the assertions above prove nothing")+ }+ if n := count(`SELECT count(*) FROM agent_task_queue WHERE id = $1`, f.neighbourTask); n != 1 {+ t.Error("neighbour-only task was deleted by the victim's task sweep")+ }+ if n := count(`SELECT count(*) FROM task_token WHERE id = $1`, f.neighbourOnlyToken); n != 1 {+ t.Error("neighbour-only task token was deleted by the victim's task sweep")+ }+}++// TestDeleteWorkspace_CollectsTasksThroughEveryOwnershipPath is the end-to-end+// counterpart: the handler returns 204, every ownership path is gone, and the+// neighbour workspace is untouched.+func TestDeleteWorkspace_CollectsTasksThroughEveryOwnershipPath(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ f := newWorkspaceDeletePathFixture(t, "endtoend")++ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/workspaces/"+f.victimID, nil)+ req = withURLParam(req, "id", f.victimID)+ testHandler.DeleteWorkspace(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("DeleteWorkspace = %d, want 204: %s", w.Code, w.Body.String())+ }++ for name, id := range map[string]string{+ "task reachable only via agent_id": f.taskViaAgent,+ "task reachable only via issue_id": f.taskViaIssue,+ "task reachable only via runtime_id": f.taskViaRuntime,+ } {+ if rowExists(t, "agent_task_queue", id) {+ t.Errorf("%s survived workspace delete", name)+ }+ }+ for name, id := range map[string]string{+ "token owned by the deleted workspace": f.victimToken,+ "token whose task is the victim's": f.crossTaskToken,+ "token whose agent is the victim's": f.crossAgentToken,+ } {+ if rowExists(t, "task_token", id) {+ t.Errorf("%s survived workspace delete", name)+ }+ }++ if !rowExists(t, "agent_task_queue", f.neighbourTask) {+ t.Error("neighbour workspace task was deleted")+ }+ if !rowExists(t, "task_token", f.neighbourOnlyToken) {+ t.Error("neighbour workspace task token was deleted")+ }+ if !rowExists(t, "agent", f.neighbourAgent) ||+ !rowExists(t, "issue", f.neighbourIssue) ||+ !rowExists(t, "agent_runtime", f.neighbourRuntime) {+ t.Error("neighbour workspace objects were deleted")+ }+ if rowExists(t, "workspace", f.victimID) {+ t.Error("victim workspace still exists")+ }+}++// TestDeleteWorkspaceTasks_PagesPastTheBatchSize covers the bound itself: a+// single owner with more tasks than one batch must be swept by several+// iterations, and the loop must terminate. Nothing here may depend on the whole+// task set fitting in one statement or in this process (MUL-5999 review).+func TestDeleteWorkspaceTasks_PagesPastTheBatchSize(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "batched")++ // Two and a half batches on one agent, so the loop has to page and then+ // see an empty page.+ const extraTasks = workspaceDeleteTaskPageSize*2 + workspaceDeleteTaskPageSize/2+ if _, err := testPool.Exec(ctx, `+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+SELECT $1, $2, $3, 'completed', now() FROM generate_series(1, $4::int)+`, f.victimAgent, f.victimIssue, f.victimRuntime, extraTasks); err != nil {+ t.Fatalf("seed %d tasks: %v", extraTasks, err)+ }++ tx, err := testHandler.TxStarter.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ qtx := testHandler.Queries.WithTx(tx)++ if err := qtx.SetWorkspaceTeardownMode(ctx); err != nil {+ t.Fatalf("set teardown mode: %v", err)+ }+ if err := lockWorkspaceTaskOwners(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("lock task owners: %v", err)+ }++ // The bound is a keyset page, not just a LIMIT: each page must return at+ // most the requested rows AND resume strictly after the previous page, so+ // the scan never re-walks what it already deleted. A LIMIT alone would still+ // read (and sort) the owner's whole task set per page.+ const probeLimit = 10+ firstPage, err := qtx.ListTaskIDsByAgentFirstPage(ctx, db.ListTaskIDsByAgentFirstPageParams{+ AgentID: parseUUID(f.victimAgent), Limit: probeLimit,+ })+ if err != nil {+ t.Fatalf("first page: %v", err)+ }+ if len(firstPage) != probeLimit {+ t.Fatalf("first page returned %d ids for LIMIT %d; the page query is not bounded",+ len(firstPage), probeLimit)+ }+ secondPage, err := qtx.ListTaskIDsByAgentPage(ctx, db.ListTaskIDsByAgentPageParams{+ AgentID: parseUUID(f.victimAgent), ID: firstPage[len(firstPage)-1], Limit: probeLimit,+ })+ if err != nil {+ t.Fatalf("second page: %v", err)+ }+ if len(secondPage) != probeLimit {+ t.Fatalf("second page returned %d ids, want %d", len(secondPage), probeLimit)+ }+ seen := make(map[string]struct{}, len(firstPage))+ for _, id := range firstPage {+ seen[uuidToString(id)] = struct{}{}+ }+ for _, id := range secondPage {+ if _, dup := seen[uuidToString(id)]; dup {+ t.Fatalf("page 2 re-returned id %s; the cursor is not advancing", uuidToString(id))+ }+ }+ if uuidToString(secondPage[0]) <= uuidToString(firstPage[len(firstPage)-1]) {+ t.Errorf("page 2 starts at %s, which is not after page 1's last id %s",+ uuidToString(secondPage[0]), uuidToString(firstPage[len(firstPage)-1]))+ }++ if err := deleteWorkspaceTasks(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("deleteWorkspaceTasks: %v", err)+ }++ var remaining int+ if err := tx.QueryRow(ctx, `+SELECT count(*) FROM agent_task_queue+WHERE agent_id = $1 OR issue_id = $2 OR runtime_id = $3+`, f.victimAgent, f.victimIssue, f.victimRuntime).Scan(&remaining); err != nil {+ t.Fatalf("count remaining: %v", err)+ }+ if remaining != 0 {+ t.Errorf("%d tasks survived a multi-batch sweep", remaining)+ }+}++// TestDeleteWorkspaceTasks_PagesOwnersBeyondOnePage covers the other unbounded+// dimension: owner enumeration. A workspace with more agents than one owner page+// must still be swept completely, and the owner ids must never all be held here at+// once (MUL-5999 review).+func TestDeleteWorkspaceTasks_PagesOwnersBeyondOnePage(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "ownerpages")++ // One more agent than a single owner page, each with a task, so the sweep has+ // to fetch a second owner page and then see an empty one.+ extraAgents := workspaceDeleteOwnerPageSize + 1+ if _, err := testPool.Exec(ctx, `+WITH new_agents AS (+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, owner_id)+ SELECT $1, 'owner-page-agent-' || g, 'cloud', '{}'::jsonb, $2, $3+ FROM generate_series(1, $4::int) g+ RETURNING id+)+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+SELECT id, $5, $2, 'completed', now() FROM new_agents+`, f.victimID, f.victimRuntime, testUserID, extraAgents, f.neighbourIssue); err != nil {+ t.Fatalf("seed %d agents: %v", extraAgents, err)+ }++ tx, err := testHandler.TxStarter.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ qtx := testHandler.Queries.WithTx(tx)++ if err := qtx.SetWorkspaceTeardownMode(ctx); err != nil {+ t.Fatalf("set teardown mode: %v", err)+ }+ if err := lockWorkspaceTaskOwners(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("lock task owners: %v", err)+ }++ // The owner page is bounded and advances the same way the task page does.+ firstOwners, err := qtx.ListWorkspaceAgentIDFirstPage(ctx, db.ListWorkspaceAgentIDFirstPageParams{+ WorkspaceID: parseUUID(f.victimID), Limit: workspaceDeleteOwnerPageSize,+ })+ if err != nil {+ t.Fatalf("first owner page: %v", err)+ }+ if len(firstOwners) != workspaceDeleteOwnerPageSize {+ t.Fatalf("first owner page returned %d ids, want %d", len(firstOwners), workspaceDeleteOwnerPageSize)+ }+ nextOwners, err := qtx.ListWorkspaceAgentIDPage(ctx, db.ListWorkspaceAgentIDPageParams{+ WorkspaceID: parseUUID(f.victimID), ID: firstOwners[len(firstOwners)-1], Limit: workspaceDeleteOwnerPageSize,+ })+ if err != nil {+ t.Fatalf("second owner page: %v", err)+ }+ if len(nextOwners) == 0 {+ t.Fatal("second owner page is empty; owner enumeration stopped after one page")+ }++ if err := deleteWorkspaceTasks(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("deleteWorkspaceTasks: %v", err)+ }++ var remaining int+ if err := tx.QueryRow(ctx, `+SELECT count(*) FROM agent_task_queue q+JOIN agent a ON a.id = q.agent_id+WHERE a.workspace_id = $1+`, f.victimID).Scan(&remaining); err != nil {+ t.Fatalf("count remaining: %v", err)+ }+ if remaining != 0 {+ t.Errorf("%d tasks survived; owners past the first page were not swept", remaining)+ }+}++// TestSweepTasksForOwner_FailsClosedWhenTasksKeepArriving pins the behaviour that+// makes the sweep safe without an application-wide enqueue protocol: if tasks keep+// appearing for an owner that has already been swept, teardown refuses to commit+// instead of leaving a half-cleaned tenant behind.+//+// The page function stands in for a broken fence — it keeps producing a task the+// sweep cannot get rid of.+func TestSweepTasksForOwner_FailsClosedWhenTasksKeepArriving(t *testing.T) {+ ctx := context.Background()+ owner := parseUUID("11111111-2222-3333-4444-555555555555")+ stubTask := parseUUID("66666666-7777-8888-9999-aaaaaaaaaaaa")++ // Faithful model of a broken fence: each pass finds one page of tasks and+ // then reports the owner clean, so the next pass starts from the beginning+ // and finds another one. Honours the page query's `id > cursor` contract, so+ // the only thing that can stop this is the pass cap.+ pages := 0+ firstPage := func(_ context.Context, _ pgtype.UUID, _ int32) ([]pgtype.UUID, error) {+ pages+++ if pages > 100 {+ t.Fatal("sweep did not stop; the pass cap is not working")+ }+ return []pgtype.UUID{stubTask}, nil+ }+ nextPage := func(context.Context, pgtype.UUID, pgtype.UUID, int32) ([]pgtype.UUID, error) {+ return nil, nil+ }+ noop := func(context.Context, []pgtype.UUID) error { return nil }++ err := sweepTasksForOwner(ctx, "agent", owner, firstPage, nextPage, noop, noop)+ if err == nil {+ t.Fatal("sweep succeeded while tasks kept arriving; teardown would commit a partial cleanup")+ }+ if !strings.Contains(err.Error(), "refusing to commit a partial teardown") {+ t.Errorf("error = %v, want a fail-closed partial-teardown error", err)+ }+}++// TestAgentTaskQueueOwnerFKsStillExist guards the precondition the write fence+// leans on. Blocking a concurrent enqueue depends on an INSERT taking FOR KEY+// SHARE on the agent / issue / runtime it references, which is a property of these+// foreign keys. The file header calls the legacy FKs an expand-phase safety net,+// so if a later migration removes them this test is what turns a silently missing+// fence into a red build — the replacement has to be an explicit protocol shared+// with every enqueue path.+func TestAgentTaskQueueOwnerFKsStillExist(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ for column, referenced := range map[string]string{+ "agent_id": "agent",+ "issue_id": "issue",+ "runtime_id": "agent_runtime",+ } {+ var exists bool+ if err := testPool.QueryRow(ctx, `+SELECT EXISTS (+ SELECT 1+ FROM pg_constraint c+ JOIN pg_class child ON child.oid = c.conrelid+ JOIN pg_class parent ON parent.oid = c.confrelid+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)+ WHERE c.contype = 'f'+ AND child.relname = 'agent_task_queue'+ AND parent.relname = $1+ AND a.attname = $2+ AND array_length(c.conkey, 1) = 1+)+`, referenced, column).Scan(&exists); err != nil {+ t.Fatalf("look up FK on %s: %v", column, err)+ }+ if !exists {+ t.Errorf("agent_task_queue.%s no longer has an FK to %s: the workspace-delete write fence "++ "relied on that FK's implicit FOR KEY SHARE to block concurrent enqueues, so it needs an "++ "explicit application-layer replacement before this FK goes away", column, referenced)+ }+ }+}++// TestDeleteWorkspaceTasks_FencesConcurrentEnqueueAndReassignment covers the two+// races a per-batch sweep would otherwise lose:+//+// - enqueue after the sweep: a task inserted for an already-swept owner would+// be left behind with its own leaf rows;+// - reassignment during the sweep: a task moved to another workspace's runtime+// between read and delete would be deleted on a stale ownership claim.+//+// Both are closed by locks the sweep takes, so the assertion is that a concurrent+// writer is blocked (and hits its own lock_timeout) while teardown holds them.+func TestDeleteWorkspaceTasks_FencesConcurrentEnqueueAndReassignment(t *testing.T) {+ if testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ f := newWorkspaceDeletePathFixture(t, "fence")++ tearDownTx, err := testHandler.TxStarter.Begin(ctx)+ if err != nil {+ t.Fatalf("begin teardown tx: %v", err)+ }+ defer tearDownTx.Rollback(ctx)+ qtx := testHandler.Queries.WithTx(tearDownTx)+ if err := lockWorkspaceTaskOwners(ctx, qtx, parseUUID(f.victimID)); err != nil {+ t.Fatalf("lock task owners: %v", err)+ }++ // A second transaction standing in for a concurrent writer. Its own short+ // lock_timeout turns "blocked forever" into an assertable error.+ blocked := func(name, sql string, args ...any) {+ t.Helper()+ other, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("%s: begin: %v", name, err)+ }+ defer other.Rollback(ctx)+ if _, err := other.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("%s: set lock_timeout: %v", name, err)+ }+ _, err = other.Exec(ctx, sql, args...)+ if err == nil {+ t.Errorf("%s: succeeded while teardown held the owner locks; the fence is not working", name)+ return+ }+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "55P03" {+ t.Errorf("%s: got %v, want lock_not_available (55P03)", name, err)+ }+ }++ blocked("enqueue for a locked agent", `+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+VALUES ($1, $2, $3, 'completed', now())+`, f.victimAgent, f.neighbourIssue, f.neighbourRuntime)++ blocked("enqueue against a locked runtime", `+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+VALUES ($1, $2, $3, 'completed', now())+`, f.neighbourAgent, f.neighbourIssue, f.victimRuntime)++ blocked("reassignment onto a locked runtime", `+UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2+`, f.victimRuntime, f.neighbourTask)++ // A writer that has nothing to do with the workspace under teardown must+ // still get through, so the fence is not a global stop-the-world.+ unrelated, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin unrelated tx: %v", err)+ }+ defer unrelated.Rollback(ctx)+ if _, err := unrelated.Exec(ctx, "SET LOCAL lock_timeout = 750"); err != nil {+ t.Fatalf("unrelated: set lock_timeout: %v", err)+ }+ if _, err := unrelated.Exec(ctx, `+INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, completed_at)+VALUES ($1, $2, $3, 'completed', now())+`, f.neighbourAgent, f.neighbourIssue, f.neighbourRuntime); err != nil {+ t.Errorf("neighbour-only enqueue was blocked by the victim's teardown locks: %v", err)+ }+}diff --git a/server/migrations/273_agent_task_queue_runtime_id_index.down.sql b/server/migrations/273_agent_task_queue_runtime_id_index.down.sqlnew file mode 100644index 0000000000..6e5650bb29--- /dev/null+++ b/server/migrations/273_agent_task_queue_runtime_id_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_runtime_id;diff --git a/server/migrations/273_agent_task_queue_runtime_id_index.up.sql b/server/migrations/273_agent_task_queue_runtime_id_index.up.sqlnew file mode 100644index 0000000000..eb6d74fd4a--- /dev/null+++ b/server/migrations/273_agent_task_queue_runtime_id_index.up.sql@@ -0,0 +1,28 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- agent_task_queue has never carried a plain runtime_id index. Every existing+-- one is partial — idx_agent_task_queue_runtime_pending (004),+-- idx_agent_task_queue_claim_candidates (067),+-- idx_agent_task_queue_dispatched_prepare (125) — and a partial index is only+-- usable when the planner can prove the query predicate implies the index+-- predicate. Two all-status consumers therefore had no index at all:+--+-- 1. Workspace teardown, which has to find every task belonging to a+-- workspace's runtimes regardless of status (MUL-5999).+-- 2. The runtime_id foreign key itself. PostgreSQL does not index the+-- referencing side of a FK, so `DELETE FROM agent_runtime` runs its+-- ON DELETE CASCADE probe (`WHERE runtime_id = $1`) once per deleted+-- runtime row — with no usable index that is a full scan of the largest+-- table in the database per runtime, on the ordinary delete path too.+--+-- Cheap to carry: runtime_id is set on essentially every row, so this is a+-- one-entry-per-row btree with no maintenance beyond what the FK column+-- already implies.+--+-- The trailing id column is what makes teardown's keyset paging free: the sweep+-- pages with `runtime_id = $1 AND id > $cursor ORDER BY id`, and without id in+-- the index every page would have to read the runtime's whole task set and sort+-- it before applying LIMIT.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_runtime_id+ ON agent_task_queue (runtime_id, id);diff --git a/server/migrations/274_task_token_workspace_id_index.down.sql b/server/migrations/274_task_token_workspace_id_index.down.sqlnew file mode 100644index 0000000000..f60d3e06bd--- /dev/null+++ b/server/migrations/274_task_token_workspace_id_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_task_token_workspace_id;diff --git a/server/migrations/274_task_token_workspace_id_index.up.sql b/server/migrations/274_task_token_workspace_id_index.up.sqlnew file mode 100644index 0000000000..9b01a30a5e--- /dev/null+++ b/server/migrations/274_task_token_workspace_id_index.up.sql@@ -0,0 +1,12 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- task_token has carried workspace_id NOT NULL since migration 108, but only+-- token_hash and task_id were indexed. Workspace teardown is the one consumer+-- that filters on workspace_id, and without this index it had no choice but to+-- scan the whole table (MUL-5999).+--+-- The column is also the natural key for any future per-tenant token audit, so+-- the index is not teardown-only.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_token_workspace_id+ ON task_token (workspace_id);diff --git a/server/migrations/275_task_token_agent_id_index.down.sql b/server/migrations/275_task_token_agent_id_index.down.sqlnew file mode 100644index 0000000000..7b9cda9b6b--- /dev/null+++ b/server/migrations/275_task_token_agent_id_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_task_token_agent_id;diff --git a/server/migrations/275_task_token_agent_id_index.up.sql b/server/migrations/275_task_token_agent_id_index.up.sqlnew file mode 100644index 0000000000..3d9ae20a92--- /dev/null+++ b/server/migrations/275_task_token_agent_id_index.up.sql@@ -0,0 +1,15 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- task_token.agent_id has been a NOT NULL FK since migration 108 with no index.+-- Two consumers need one:+--+-- 1. Workspace teardown deletes tokens by agent as one of the three explicit+-- task_token paths (MUL-5999). It must not fall back on the agent_id+-- cascade, because the legacy FKs are documented as an expand-phase safety+-- net that a later contract removes.+-- 2. The FK's own ON DELETE CASCADE probe, which PostgreSQL runs once per+-- deleted agent row — a full scan of task_token per agent without an index,+-- on the ordinary agent-delete path too.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_token_agent_id+ ON task_token (agent_id);diff --git a/server/migrations/276_chat_draft_restore_task_id_index.down.sql b/server/migrations/276_chat_draft_restore_task_id_index.down.sqlnew file mode 100644index 0000000000..539c4419e7--- /dev/null+++ b/server/migrations/276_chat_draft_restore_task_id_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_draft_restore_task_id;diff --git a/server/migrations/276_chat_draft_restore_task_id_index.up.sql b/server/migrations/276_chat_draft_restore_task_id_index.up.sqlnew file mode 100644index 0000000000..cb3b502843--- /dev/null+++ b/server/migrations/276_chat_draft_restore_task_id_index.up.sql@@ -0,0 +1,9 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- chat_draft_restore.task_id is an unindexed FK. Workspace teardown now deletes+-- drafts one bounded task batch at a time (MUL-5999), and without an index each+-- batch would scan the table; the FK's own ON DELETE SET NULL probe has the same+-- problem on every ordinary task delete.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_draft_restore_task_id+ ON chat_draft_restore (task_id);diff --git a/server/migrations/277_autopilot_run_task_id_index.down.sql b/server/migrations/277_autopilot_run_task_id_index.down.sqlnew file mode 100644index 0000000000..79232a3f22--- /dev/null+++ b/server/migrations/277_autopilot_run_task_id_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_autopilot_run_task_id;diff --git a/server/migrations/277_autopilot_run_task_id_index.up.sql b/server/migrations/277_autopilot_run_task_id_index.up.sqlnew file mode 100644index 0000000000..240b5881d1--- /dev/null+++ b/server/migrations/277_autopilot_run_task_id_index.up.sql@@ -0,0 +1,10 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- autopilot_run.task_id is an unindexed FK with ON DELETE SET NULL, so today+-- every single agent_task_queue row deletion anywhere in the product makes+-- PostgreSQL run `UPDATE autopilot_run SET task_id = NULL WHERE task_id = $1`+-- with no index behind it. Workspace teardown detaches these references+-- explicitly per task batch (MUL-5999) and needs the index for the same reason.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_autopilot_run_task_id+ ON autopilot_run (task_id);diff --git a/server/migrations/278_agent_task_queue_agent_id_keyset_index.down.sql b/server/migrations/278_agent_task_queue_agent_id_keyset_index.down.sqlnew file mode 100644index 0000000000..d0ff857876--- /dev/null+++ b/server/migrations/278_agent_task_queue_agent_id_keyset_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_agent_id_keyset;diff --git a/server/migrations/278_agent_task_queue_agent_id_keyset_index.up.sql b/server/migrations/278_agent_task_queue_agent_id_keyset_index.up.sqlnew file mode 100644index 0000000000..daa1221830--- /dev/null+++ b/server/migrations/278_agent_task_queue_agent_id_keyset_index.up.sql@@ -0,0 +1,14 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Workspace teardown pages a busy agent's tasks with+-- `agent_id = $1 AND id > $cursor ORDER BY id LIMIT n` (MUL-5999). The existing+-- idx_agent_task_queue_agent is (agent_id, status), which cannot produce id+-- order, so every page would read the agent's entire task set and sort it before+-- applying LIMIT — quadratic in the number of pages, which is exactly the busy+-- agent this issue is about.+--+-- (agent_id, status) stays: the hot dispatch and claim queries filter on status,+-- and this index does not serve them.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_agent_id_keyset+ ON agent_task_queue (agent_id, id);diff --git a/server/migrations/279_agent_task_queue_issue_id_keyset_index.down.sql b/server/migrations/279_agent_task_queue_issue_id_keyset_index.down.sqlnew file mode 100644index 0000000000..1e3f7ba5c4--- /dev/null+++ b/server/migrations/279_agent_task_queue_issue_id_keyset_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_issue_id_keyset;diff --git a/server/migrations/279_agent_task_queue_issue_id_keyset_index.up.sql b/server/migrations/279_agent_task_queue_issue_id_keyset_index.up.sqlnew file mode 100644index 0000000000..62f311aec9--- /dev/null+++ b/server/migrations/279_agent_task_queue_issue_id_keyset_index.up.sql@@ -0,0 +1,15 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Same keyset-paging reason as migration 278, for teardown's issue path.+--+-- This makes idx_agent_task_queue_issue_id (migration 035) redundant: a btree on+-- (issue_id, id) serves every `issue_id = $1` predicate that the single-column+-- index served, and additionally produces id order. The old index is left in+-- place deliberately. Dropping it needs its own migration with a+-- direction-aware INVALID-index cleanup, because the down path of such a drop is+-- a CREATE INDEX CONCURRENTLY and the runner only runs cleanup hooks in the up+-- direction — an interrupted rollback would otherwise leave no usable issue_id+-- index at all.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_issue_id_keyset+ ON agent_task_queue (issue_id, id);diff --git a/server/migrations/281_agent_workspace_id_keyset_index.down.sql b/server/migrations/281_agent_workspace_id_keyset_index.down.sqlnew file mode 100644index 0000000000..10c2b3be0b--- /dev/null+++ b/server/migrations/281_agent_workspace_id_keyset_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_workspace_id_keyset;diff --git a/server/migrations/281_agent_workspace_id_keyset_index.up.sql b/server/migrations/281_agent_workspace_id_keyset_index.up.sqlnew file mode 100644index 0000000000..cd417c15f2--- /dev/null+++ b/server/migrations/281_agent_workspace_id_keyset_index.up.sql@@ -0,0 +1,14 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Workspace teardown enumerates the workspace's agents in bounded pages —+-- `workspace_id = $1 AND id > $cursor ORDER BY id LIMIT n` — so a workspace with+-- a very large owner set never has its whole id list held in the API process+-- (MUL-5999). The existing single-column workspace_id index cannot produce id+-- order, which would put a Sort over the entire owner set in front of every page.+--+-- id rather than a natural key on purpose: a keyset column has to be immutable,+-- and renaming an agent row mid-teardown would otherwise let it sort behind the+-- cursor and escape the sweep.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_workspace_id_keyset+ ON agent (workspace_id, id);diff --git a/server/migrations/282_issue_workspace_id_keyset_index.down.sql b/server/migrations/282_issue_workspace_id_keyset_index.down.sqlnew file mode 100644index 0000000000..11bc4b5130--- /dev/null+++ b/server/migrations/282_issue_workspace_id_keyset_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_id_keyset;diff --git a/server/migrations/282_issue_workspace_id_keyset_index.up.sql b/server/migrations/282_issue_workspace_id_keyset_index.up.sqlnew file mode 100644index 0000000000..9ba1e669d4--- /dev/null+++ b/server/migrations/282_issue_workspace_id_keyset_index.up.sql@@ -0,0 +1,14 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Workspace teardown enumerates the workspace's issues in bounded pages —+-- `workspace_id = $1 AND id > $cursor ORDER BY id LIMIT n` — so a workspace with+-- a very large owner set never has its whole id list held in the API process+-- (MUL-5999). The existing single-column workspace_id index cannot produce id+-- order, which would put a Sort over the entire owner set in front of every page.+--+-- id rather than a natural key on purpose: a keyset column has to be immutable,+-- and renaming an issue row mid-teardown would otherwise let it sort behind the+-- cursor and escape the sweep.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_id_keyset+ ON issue (workspace_id, id);diff --git a/server/migrations/283_agent_runtime_workspace_id_keyset_index.down.sql b/server/migrations/283_agent_runtime_workspace_id_keyset_index.down.sqlnew file mode 100644index 0000000000..949be50e8c--- /dev/null+++ b/server/migrations/283_agent_runtime_workspace_id_keyset_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_runtime_workspace_id_keyset;diff --git a/server/migrations/283_agent_runtime_workspace_id_keyset_index.up.sql b/server/migrations/283_agent_runtime_workspace_id_keyset_index.up.sqlnew file mode 100644index 0000000000..79a1e093d1--- /dev/null+++ b/server/migrations/283_agent_runtime_workspace_id_keyset_index.up.sql@@ -0,0 +1,14 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Workspace teardown enumerates the workspace's runtimes in bounded pages —+-- `workspace_id = $1 AND id > $cursor ORDER BY id LIMIT n` — so a workspace with+-- a very large owner set never has its whole id list held in the API process+-- (MUL-5999). The existing single-column workspace_id index cannot produce id+-- order, which would put a Sort over the entire owner set in front of every page.+--+-- id rather than a natural key on purpose: a keyset column has to be immutable,+-- and renaming an agent_runtime row mid-teardown would otherwise let it sort behind the+-- cursor and escape the sweep.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_runtime_workspace_id_keyset+ ON agent_runtime (workspace_id, id);diff --git a/server/migrations/284_task_owner_row_fence.down.sql b/server/migrations/284_task_owner_row_fence.down.sqlnew file mode 100644index 0000000000..4e66e241aa--- /dev/null+++ b/server/migrations/284_task_owner_row_fence.down.sql@@ -0,0 +1 @@+DROP FUNCTION IF EXISTS lock_task_owner_rows(uuid, uuid, uuid);diff --git a/server/migrations/284_task_owner_row_fence.up.sql b/server/migrations/284_task_owner_row_fence.up.sqlnew file mode 100644index 0000000000..1cdce03d4b--- /dev/null+++ b/server/migrations/284_task_owner_row_fence.up.sql@@ -0,0 +1,154 @@+-- The write half of workspace teardown's concurrency contract, and of the legacy+-- runtime merge's (MUL-5999).+--+-- THE WINDOWS+--+-- Two deletes remove rows a task write depends on, and both would otherwise strand+-- or silently drop a task that arrives while they run:+--+-- 1. Workspace teardown sweeps a workspace's tasks and then commits. A task+-- inserted between the last sweep and COMMIT would be left behind with its own+-- leaf rows, owned by rows that no longer exist.+-- 2. The legacy runtime merge moves an old runtime's tasks onto a new one and then+-- deletes the old runtime. A task inserted against the OLD runtime after that+-- scan is deleted by agent_task_queue's ON DELETE CASCADE when the old runtime+-- goes — it was never a task anyone chose to discard.+--+-- Re-scanning cannot close either: the check and the commit are not atomic with+-- respect to a concurrent writer, so a row can always land after the final scan.+--+-- WHAT THIS IS+--+-- A predicate that every statement writing agent_task_queue ownership calls in its+-- own WHERE clause:+--+-- INSERT INTO agent_task_queue (...)+-- SELECT ... WHERE lock_task_owner_rows(@agent_id, @issue_id, @runtime_id)+--+-- It locks, in a fixed order, the workspace rows behind the row's agent, issue and+-- runtime, and then those owner rows themselves — all FOR KEY SHARE — and returns+-- false unless every owner reference still resolves afterwards.+--+-- * FOR KEY SHARE on the workspace conflicts with the FOR UPDATE that+-- LockWorkspaceForDelete holds for a whole teardown transaction.+-- * FOR KEY SHARE on the owner rows conflicts with the FOR UPDATE that the legacy+-- merge takes on the runtimes it is about to collapse (LockRuntimesForMerge),+-- and with the DELETE of any owner row.+--+-- So a task write racing either delete blocks until it finishes, and then either+-- proceeds (the delete rolled back) or writes no row (it committed). Locking the+-- workspace alone was not enough: the merge holds only KEY SHARE there, which does+-- not conflict with another KEY SHARE, so a writer sailed past it and had its task+-- cascade-deleted with the old runtime.+--+-- WHY A CALLED PREDICATE RATHER THAN A TRIGGER OR THE FOREIGN KEYS+--+-- * Not the foreign keys. An INSERT does take FOR KEY SHARE on the rows it+-- references, which is why these windows have been survivable so far — but that+-- is a side effect of FK enforcement, and workspace_delete.sql documents the+-- legacy FKs as an expand-phase net a later contract removes. Cleanup+-- correctness must not be a hostage of that migration.+-- * Not a trigger. A row trigger is a database-layer relational constraint that+-- coordinates application behaviour behind the caller's back. This repo keeps+-- relationships in the application layer, so the write path names its own+-- fence, and TestTaskOwnershipWritesCallTheFence fails the build if a statement+-- that writes ownership forgets to.+-- * It must be in the writer's transaction. Several enqueue statements run as+-- single autocommit statements, so a separate "take the fence" statement issued+-- by the caller would be its own transaction and release the lock before the+-- insert landed. Calling the predicate from the writing statement is+-- in-transaction by construction.+--+-- DETERMINISTIC LOCK ORDER+--+-- Workspaces first (ORDER BY id), then owners as agent, issue, runtime. Every+-- reader of this contract — writers, teardown, the merge — takes locks in that+-- order, so no two of them can hold each other's next lock. Within a step,+-- LockRows sits above Sort in the plan, so ORDER BY really does fix acquisition+-- order.+--+-- VOLATILE (the default) is load-bearing: it stops the planner from inlining the+-- body or optimising the call away, which would drop the locks.++CREATE OR REPLACE FUNCTION lock_task_owner_rows(+ p_agent_id uuid,+ p_issue_id uuid,+ p_runtime_id uuid+)+RETURNS boolean+LANGUAGE plpgsql+AS $$+DECLARE+ required int := (CASE WHEN p_agent_id IS NULL THEN 0 ELSE 1 END)+ + (CASE WHEN p_issue_id IS NULL THEN 0 ELSE 1 END)+ + (CASE WHEN p_runtime_id IS NULL THEN 0 ELSE 1 END);+ resolved int;+ distinct_workspaces int;+ locked int;+BEGIN+ -- A row with no owner reference at all cannot belong to any workspace.+ IF required = 0 THEN+ RETURN TRUE;+ END IF;++ WITH owners AS (+ SELECT a.workspace_id FROM agent a WHERE a.id = p_agent_id+ UNION ALL+ SELECT i.workspace_id FROM issue i WHERE i.id = p_issue_id+ UNION ALL+ SELECT r.workspace_id FROM agent_runtime r WHERE r.id = p_runtime_id+ )+ SELECT count(*), count(DISTINCT workspace_id)+ INTO resolved, distinct_workspaces+ FROM owners;++ -- An owner reference that no longer resolves means its row has been deleted —+ -- by a teardown or a merge that already committed, most likely. Refuse without+ -- leaning on the foreign key to report it.+ IF resolved <> required THEN+ RETURN FALSE;+ END IF;++ -- Step 1: the workspaces.+ WITH locked_workspaces AS (+ SELECT w.id+ FROM workspace w+ WHERE w.id IN (+ SELECT a.workspace_id FROM agent a WHERE a.id = p_agent_id+ UNION+ SELECT i.workspace_id FROM issue i WHERE i.id = p_issue_id+ UNION+ SELECT r.workspace_id FROM agent_runtime r WHERE r.id = p_runtime_id+ )+ ORDER BY w.id+ FOR KEY SHARE+ )+ SELECT count(*) INTO locked FROM locked_workspaces;++ IF locked <> distinct_workspaces THEN+ RETURN FALSE;+ END IF;++ -- Step 2: the owner rows, agent then issue then runtime. Re-checking existence+ -- here is what closes the merge window: whoever is deleting one of these rows+ -- holds FOR UPDATE on it, so this either waits for them or finds the row gone.+ locked := 0;++ IF p_agent_id IS NOT NULL THEN+ PERFORM 1 FROM agent WHERE id = p_agent_id FOR KEY SHARE;+ IF FOUND THEN locked := locked + 1; END IF;+ END IF;++ IF p_issue_id IS NOT NULL THEN+ PERFORM 1 FROM issue WHERE id = p_issue_id FOR KEY SHARE;+ IF FOUND THEN locked := locked + 1; END IF;+ END IF;++ IF p_runtime_id IS NOT NULL THEN+ PERFORM 1 FROM agent_runtime WHERE id = p_runtime_id FOR KEY SHARE;+ IF FOUND THEN locked := locked + 1; END IF;+ END IF;++ RETURN locked = required;+END;+$$;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 80b382571f..7f24ec97b6 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1734,7 +1734,7 @@ INSERT INTO agent_task_queue (squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, $3, 'queued', $4, $5,COALESCE($6::uuid[], '{}'),$7,@@ -1757,7 +1757,7 @@ VALUES ($20,$21,$22-)+WHERE lock_task_owner_rows($1, $3, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -1786,6 +1786,10 @@ type CreateAgentTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// head_sha stamps the commit under review into the task's context JSONB so the// reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run// against an OLD head apart from a fresh request against a NEW head (TEN-356).@@ -1882,25 +1886,28 @@ INSERT INTO agent_task_queue (originator_user_id, accountable_user_id, originator_source,delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (- $1, $2, $3, 'deferred', $4,- $5,- $6,- COALESCE($7::boolean, FALSE),+SELECT+ $4, $5, $6, 'deferred', $7,$8,$9,- $10,+ COALESCE($10::boolean, FALSE),$11,$12,$13,$14,$15,- $16-)+ $16,+ $17,+ $18,+ $19+WHERE lock_task_owner_rows($1, $3, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`type CreateDeferredAgentTaskParams struct {+ PAgentID pgtype.UUID `json:"p_agent_id"`+ PRuntimeID pgtype.UUID `json:"p_runtime_id"`+ PIssueID pgtype.UUID `json:"p_issue_id"`AgentID pgtype.UUID `json:"agent_id"`RuntimeID pgtype.UUID `json:"runtime_id"`IssueID pgtype.UUID `json:"issue_id"`@@ -1919,6 +1926,10 @@ type CreateDeferredAgentTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them// to queued. Used for comment-routing escalation: a thread-owner primary task// gets a delayed assignee fallback without waking both agents at t=0.@@ -1928,6 +1939,9 @@ type CreateDeferredAgentTaskParams struct {// (MUL-4302 §2).func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferredAgentTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createDeferredAgentTask,+ arg.PAgentID,+ arg.PRuntimeID,+ arg.PIssueID,arg.AgentID,arg.RuntimeID,arg.IssueID,@@ -2010,7 +2024,7 @@ INSERT INTO agent_task_queue (originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,trigger_evidence_kind, trigger_evidence_ref_id, fire_at)-VALUES (+SELECT$1, $2, $3, 'deferred', $4, $5,COALESCE($6::uuid[], '{}'),$7,@@ -2033,7 +2047,7 @@ VALUES ($21,$22,$23-)+WHERE lock_task_owner_rows($1, $3, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -2063,6 +2077,10 @@ type CreateDeferredChannelIssueTaskParams struct {FireAt pgtype.Timestamptz `json:"fire_at"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Channel /issue media resolves after issue creation. Persist the assigned// issue task up front for crash safety, but keep it inert until attachment// binding settles or the fire_at fallback is promoted by the normal sweeper.@@ -2155,7 +2173,7 @@ INSERT INTO agent_task_queue (accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, NULL, 'queued', $3, $4,$5,$6,@@ -2164,7 +2182,7 @@ VALUES ($9,$10,$11-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -2182,6 +2200,10 @@ type CreateQuickCreateTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Quick-create tasks have no issue / chat / autopilot link; the entire job// description (prompt, requester, workspace) lives in context JSONB. The// daemon detects this variant via context.type == "quick_create".@@ -2290,6 +2312,7 @@ SELECTp.chat_input_task_id, $2FROM agent_task_queue pWHERE p.id = $1+ AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -2301,6 +2324,10 @@ type CreateRetryTaskParams struct {RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Clones a parent task into a fresh queued attempt. Carries forward the// agent's resume context (session_id/work_dir) so the child can continue// the conversation when the backend supports it. Resume-unsafe failures are@@ -3856,6 +3883,7 @@ const linkTaskToIssue = `-- name: LinkTaskToIssue :execUPDATE agent_task_queueSET issue_id = $2WHERE id = $1 AND issue_id IS NULL+ AND lock_task_owner_rows(NULL, $2, NULL)`type LinkTaskToIssueParams struct {@@ -3863,6 +3891,10 @@ type LinkTaskToIssueParams struct {IssueID pgtype.UUID `json:"issue_id"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Attaches the issue a quick-create task produced back to the task row, once// the agent has finished and the issue exists. Guarded by `issue_id IS NULL`// so this never overwrites an issue id that was set at task creation (onlydiff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex f5d3593259..1095b47f4e 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -280,7 +280,7 @@ INSERT INTO agent_task_queue (originator_user_id, accountable_user_id, rule_version_id,originator_source, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, NULL, 'queued', $3, $4, $5,$6,$7,@@ -288,7 +288,7 @@ VALUES ($9,$10,$11-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -309,6 +309,10 @@ type CreateAutopilotTaskParams struct {// =====================// Task Queue (run_only mode)// =====================+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// run_only autopilot dispatch. Attribution depends on the trigger:// - schedule / webhook / api: no human authorized the run, so originator_user_id// stays NULL and accountable_user_id is the rule_owner (the publisher of thediff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 9a188dff52..831f807c4c 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -340,7 +340,7 @@ INSERT INTO agent_task_queue (runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,fire_at)-VALUES (+SELECT$1, $2, NULL,CASE WHEN $6::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,$3, $4, $5,@@ -353,7 +353,7 @@ VALUES ($13,$14,$6::timestamptz-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for`@@ -374,6 +374,10 @@ type CreateChatTaskParams struct {TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`}+// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// The chat sender (initiator) is a direct_human originator and accountable;// attribution provenance is stamped so this path is not a NULL-source enqueue// bypass (MUL-4302 §2).diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex ef720f14a5..f3ce248f49 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -706,6 +706,68 @@ func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRureturn i, err}+const lockRuntimesForMerge = `-- name: LockRuntimesForMerge :many+SELECT id FROM agent_runtime+WHERE id = ANY($1::uuid[])+ORDER BY id+FOR UPDATE+`++// Step 2: the runtime rows themselves, FOR UPDATE, in id order.+//+// FOR UPDATE is the point. A task write's fence takes FOR KEY SHARE on the runtime+// it references, and KEY SHARE conflicts with UPDATE but not with another KEY+// SHARE — so while the merge held only the workspace's KEY SHARE, a concurrent+// enqueue against the OLD runtime went straight through after the task scan and was+// then silently removed by ON DELETE CASCADE when the old runtime was deleted.+// Holding FOR UPDATE on both runtimes from before the scan until COMMIT means a+// late writer either commits first (and the scan sees its task) or waits and finds+// the runtime gone, which its fence reports as "no row written".+//+// Both runtimes are locked in one ordered statement so two merges running in+// opposite directions cannot take the same pair in opposite orders.+//+// Returns the ids it actually locked: a caller that asked for two and got fewer+// knows a runtime disappeared before it got there and must abandon the merge.+func (q *Queries) LockRuntimesForMerge(ctx context.Context, runtimeIds []pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, lockRuntimesForMerge, runtimeIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockWorkspaceForRuntimeMerge = `-- name: LockWorkspaceForRuntimeMerge :exec+SELECT 1 FROM workspace w+WHERE w.id IN (+ SELECT r.workspace_id FROM agent_runtime r WHERE r.id = ANY($1::uuid[])+)+ORDER BY w.id+FOR KEY SHARE+`++// Step 1 of the legacy runtime merge's fence, and the same first step every task+// write takes (lock_task_owner_rows, migration 284): the workspace row, FOR KEY+// SHARE. Taking it here rather than relying on the fence inside the reassignment+// keeps the merge's lock order identical to the writers' — workspaces before owner+// rows — so the two can never hold each other's next lock (MUL-5999).+func (q *Queries) LockWorkspaceForRuntimeMerge(ctx context.Context, runtimeIds []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkspaceForRuntimeMerge, runtimeIds)+ return err+}+const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :oneUPDATE agent_runtimeSET status = 'online', last_seen_at = now(), updated_at = now()@@ -820,10 +882,23 @@ func (q *Queries) ReassignAgentsToRuntime(ctx context.Context, arg ReassignAgentreturn result.RowsAffected(), nil}-const reassignTasksToRuntime = `-- name: ReassignTasksToRuntime :execrows-UPDATE agent_task_queue-SET runtime_id = $1-WHERE runtime_id = $2+const reassignTasksToRuntime = `-- name: ReassignTasksToRuntime :one+WITH fence AS MATERIALIZED (+ -- Once per statement rather than once per row: the predicate is VOLATILE, so+ -- calling it from the WHERE clause of a bulk UPDATE would re-run it for every+ -- candidate row.+ SELECT lock_task_owner_rows(NULL, NULL, $1) AS ok+),+reassigned AS (+ UPDATE agent_task_queue+ SET runtime_id = $1+ WHERE runtime_id = $2+ AND (SELECT ok FROM fence)+ RETURNING id+)+SELECT+ (SELECT ok FROM fence) AS fence_ok,+ (SELECT count(*) FROM reassigned) AS reassigned_tasks`type ReassignTasksToRuntimeParams struct {@@ -831,15 +906,29 @@ type ReassignTasksToRuntimeParams struct {OldRuntimeID pgtype.UUID `json:"old_runtime_id"`}+type ReassignTasksToRuntimeRow struct {+ FenceOk bool `json:"fence_ok"`+ ReassignedTasks int64 `json:"reassigned_tasks"`+}++// Fenced against workspace teardown: lock_task_owner_rows (migration 284)+// locks the owners' workspace rows in the writer's own transaction and returns+// false once they are gone, so this statement writes no row instead of stranding+// a task in a workspace that has just been deleted (MUL-5999).// Re-points every queued/running/completed task referencing old_runtime_id.// Required before deleting the old runtime row because agent_task_queue has// an ON DELETE CASCADE FK that would otherwise drop historical tasks.-func (q *Queries) ReassignTasksToRuntime(ctx context.Context, arg ReassignTasksToRuntimeParams) (int64, error) {- result, err := q.db.Exec(ctx, reassignTasksToRuntime, arg.NewRuntimeID, arg.OldRuntimeID)- if err != nil {- return 0, err- }- return result.RowsAffected(), nil+//+// Returns the fence verdict separately from the row count on purpose. "0 rows"+// is ambiguous — it means either "the old runtime had no tasks" or "the fence+// refused" — and a caller that cannot tell them apart would go on to delete the+// old runtime, letting that same ON DELETE CASCADE drop the very history this+// statement exists to preserve. FenceOk = false must abort the merge.+func (q *Queries) ReassignTasksToRuntime(ctx context.Context, arg ReassignTasksToRuntimeParams) (ReassignTasksToRuntimeRow, error) {+ row := q.db.QueryRow(ctx, reassignTasksToRuntime, arg.NewRuntimeID, arg.OldRuntimeID)+ var i ReassignTasksToRuntimeRow+ err := row.Scan(&i.FenceOk, &i.ReassignedTasks)+ return i, err}const recordRuntimeLegacyDaemonID = `-- name: RecordRuntimeLegacyDaemonID :execdiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex efd68053f2..7da47b0063 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -11,6 +11,56 @@ import ("github.com/jackc/pgx/v5/pgtype")+const deleteTaskBatch = `-- name: DeleteTaskBatch :exec+WITH+batch AS MATERIALIZED (+ SELECT id FROM unnest($1::uuid[]) AS t(id)+),+deleted_task_usage AS (+ DELETE FROM task_usage WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_messages AS (+ DELETE FROM task_message WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_tokens AS (+ DELETE FROM task_token WHERE task_id IN (SELECT id FROM batch)+),+deleted_channel_outbound_cards AS (+ DELETE FROM channel_outbound_card_message WHERE task_id IN (SELECT id FROM batch)+),+deleted_lark_outbound_cards AS (+ DELETE FROM lark_outbound_card_message WHERE task_id IN (SELECT id FROM batch)+),+deleted_draft_restores AS (+ DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)+)+DELETE FROM agent_task_queue WHERE id IN (SELECT id FROM batch)+`++// Deletes one bounded batch of tasks together with everything that hangs off+// them, every arm keyed by task_id against an existing index, then the task rows+// by primary key. The legacy FK cascades stay a safety net only: this statement+// is what actually removes the rows, so teardown keeps working when they go.+func (q *Queries) DeleteTaskBatch(ctx context.Context, taskIds []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteTaskBatch, taskIds)+ return err+}++const deleteTaskTokensByAgent = `-- name: DeleteTaskTokensByAgent :exec+DELETE FROM task_token WHERE agent_id = $1+`++// The third explicit task_token path. workspace_id (in DeleteWorkspaceLeafData)+// and task_id (in DeleteTaskBatch) do not cover a token whose own workspace_id+// points at a neighbour while its agent lives here, and teardown must not fall+// back on the agent_id cascade for it. Uses idx_task_token_agent_id+// (migration 275); one agent key per call for the same planner reason as+// ListTaskIDsByAgentBatch.+func (q *Queries) DeleteTaskTokensByAgent(ctx context.Context, agentID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteTaskTokensByAgent, agentID)+ return err+}+const deleteWorkspaceAdministration = `-- name: DeleteWorkspaceAdministration :execWITHdeleted_members AS (@@ -174,9 +224,6 @@ WITHws_agents AS MATERIALIZED (SELECT id FROM agent WHERE workspace_id = $1),-ws_runtimes AS MATERIALIZED (- SELECT id FROM agent_runtime WHERE workspace_id = $1-),ws_issues AS MATERIALIZED (SELECT id FROM issue WHERE workspace_id = $1),@@ -189,13 +236,6 @@ ws_skills AS MATERIALIZED (ws_squads AS MATERIALIZED (SELECT id FROM squad WHERE workspace_id = $1),-ws_tasks AS MATERIALIZED (- SELECT id- FROM agent_task_queue- WHERE agent_id IN (SELECT id FROM ws_agents)- OR issue_id IN (SELECT id FROM ws_issues)- OR runtime_id IN (SELECT id FROM ws_runtimes)-),ws_sessions AS MATERIALIZED (SELECT id FROM chat_session WHERE workspace_id = $1),@@ -217,19 +257,9 @@ ws_channel_installations AS MATERIALIZED (ws_lark_installations AS MATERIALIZED (SELECT id FROM lark_installation WHERE workspace_id = $1),-deleted_task_usage AS (- DELETE FROM task_usage- WHERE task_id IN (SELECT id FROM ws_tasks)-),-deleted_task_messages AS (- DELETE FROM task_message- WHERE task_id IN (SELECT id FROM ws_tasks)-),deleted_task_tokens AS (DELETE FROM task_tokenWHERE workspace_id = $1- OR task_id IN (SELECT id FROM ws_tasks)- OR agent_id IN (SELECT id FROM ws_agents)),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1@@ -243,17 +273,14 @@ deleted_attachments AS (deleted_channel_outbound_cards AS (DELETE FROM channel_outbound_card_messageWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),deleted_lark_outbound_cards AS (DELETE FROM lark_outbound_card_messageWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),deleted_draft_restores AS (DELETE FROM chat_draft_restoreWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),deleted_agent_builder_drafts AS (DELETE FROM agent_builder_draft WHERE workspace_id = $1@@ -404,6 +431,15 @@ SET state = CASEWHERE channel_media_pending_object.workspace_id = $1`+// Everything task-keyed moved to DeleteTaskBatch, which runs in bounded batches+// before this step; what is left is keyed by the workspace or by one of the+// workspace-scoped id sets below.+// One of three explicit task_token paths. This is the workspace-keyed one;+// DeleteTaskBatch covers task_id and DeleteTaskTokensByAgent covers agent_id, so+// a token whose workspace_id points at a neighbour while its task or agent lives+// here is still removed by this teardown rather than by the FK cascade. The+// former single statement combined all three with OR, which cost a full scan of+// task_token (MUL-5999); split, each path is an index scan.// Same no-FK chore as chat_draft_restore above. Matched on workspace_id rather// than the session set because that column exists precisely so this statement// does not have to join through chat_session, which it deletes in this same CTE.@@ -457,18 +493,482 @@ func (q *Queries) DeleteWorkspaceSquadsAndSkills(ctx context.Context, workspaceIreturn err}-const deleteWorkspaceTasks = `-- name: DeleteWorkspaceTasks :exec-DELETE FROM agent_task_queue-WHERE agent_id IN (SELECT id FROM agent WHERE agent.workspace_id = $1)- OR issue_id IN (SELECT id FROM issue WHERE issue.workspace_id = $1)- OR runtime_id IN (SELECT id FROM agent_runtime WHERE agent_runtime.workspace_id = $1)+const detachTaskBatchReferences = `-- name: DetachTaskBatchReferences :exec+WITH detached_runs AS (+ UPDATE autopilot_run+ SET task_id = NULL+ WHERE task_id = ANY($1::uuid[])+)+UPDATE agent_task_queue+SET parent_task_id = NULL+WHERE parent_task_id = ANY($1::uuid[])`-func (q *Queries) DeleteWorkspaceTasks(ctx context.Context, workspaceID pgtype.UUID) error {- _, err := q.db.Exec(ctx, deleteWorkspaceTasks, workspaceID)+// Break inbound references to a task batch before deleting it, in the+// application layer rather than through the FKs' ON DELETE SET NULL. Both+// referencing columns are indexed (idx_agent_task_queue_parent from migration+// 055, idx_autopilot_run_task_id from migration 277) so this stays a per-batch+// index scan instead of the per-row full scan the FK action would do.+//+// Kept separate from DeleteTaskBatch: a task can be both a member of the batch+// and the parent of another member, and updating plus deleting the same row+// inside one statement is not well defined.+func (q *Queries) DetachTaskBatchReferences(ctx context.Context, taskIds []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, detachTaskBatchReferences, taskIds)return err}+const listTaskIDsByAgentFirstPage = `-- name: ListTaskIDsByAgentFirstPage :many+SELECT id FROM agent_task_queue+WHERE agent_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE+`++type ListTaskIDsByAgentFirstPageParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+// a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+// the single-key / keyset / FOR UPDATE rationale.+func (q *Queries) ListTaskIDsByAgentFirstPage(ctx context.Context, arg ListTaskIDsByAgentFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByAgentFirstPage, arg.AgentID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskIDsByAgentPage = `-- name: ListTaskIDsByAgentPage :many+SELECT id FROM agent_task_queue+WHERE agent_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE+`++type ListTaskIDsByAgentPageParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// One owner key per call, one keyset-paged chunk per call.+//+// Single-key equality is deliberate. All three ownership paths must stay (nothing+// enforces that a task's agent/runtime/issue share a workspace), but expressing+// them as `OR agent_id IN (subquery) OR …` — or as a UNION of joins, or as+// `= ANY($1::uuid[])` over a whole workspace's agents — makes the planner+// estimate a proportional share of the global table and fall back to a Seq Scan+// on agent_task_queue. A single-key equality is the only form whose row estimate+// stays small enough to be index-driven regardless of how the workspace's tasks+// are distributed (MUL-5999).+//+// `id > $2 ORDER BY id LIMIT $3` against idx_agent_task_queue_agent_id_keyset+// (migration 278) bounds the SCAN, not just the result: each page is an index+// range scan that starts where the previous one stopped. Bounding only the result+// — `ORDER BY id LIMIT n` against the (agent_id, status) index — puts a Sort over+// the agent's entire task set in front of every page, so a busy agent costs+// roughly O(N² / page) for the sweep.+//+// FOR UPDATE is load-bearing for correctness, not throughput. It locks the rows+// this page is about to delete, and under READ COMMITTED PostgreSQL re-checks the+// WHERE clause after acquiring each lock: a task a concurrent committed UPDATE+// has already moved to another owner no longer matches and is skipped, and one we+// did lock cannot be moved away before we delete it.+func (q *Queries) ListTaskIDsByAgentPage(ctx context.Context, arg ListTaskIDsByAgentPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByAgentPage, arg.AgentID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskIDsByIssueFirstPage = `-- name: ListTaskIDsByIssueFirstPage :many+SELECT id FROM agent_task_queue+WHERE issue_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE+`++type ListTaskIDsByIssueFirstPageParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+// a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+// the single-key / keyset / FOR UPDATE rationale.+func (q *Queries) ListTaskIDsByIssueFirstPage(ctx context.Context, arg ListTaskIDsByIssueFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByIssueFirstPage, arg.IssueID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskIDsByIssuePage = `-- name: ListTaskIDsByIssuePage :many+SELECT id FROM agent_task_queue+WHERE issue_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE+`++type ListTaskIDsByIssuePageParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// Uses idx_agent_task_queue_issue_id_keyset (migration 279). See+// ListTaskIDsByAgentPage for the single-key / keyset / FOR UPDATE rationale.+func (q *Queries) ListTaskIDsByIssuePage(ctx context.Context, arg ListTaskIDsByIssuePageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByIssuePage, arg.IssueID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskIDsByRuntimeFirstPage = `-- name: ListTaskIDsByRuntimeFirstPage :many+SELECT id FROM agent_task_queue+WHERE runtime_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE+`++type ListTaskIDsByRuntimeFirstPageParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+// a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+// the single-key / keyset / FOR UPDATE rationale.+func (q *Queries) ListTaskIDsByRuntimeFirstPage(ctx context.Context, arg ListTaskIDsByRuntimeFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByRuntimeFirstPage, arg.RuntimeID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskIDsByRuntimePage = `-- name: ListTaskIDsByRuntimePage :many+SELECT id FROM agent_task_queue+WHERE runtime_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE+`++type ListTaskIDsByRuntimePageParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// Uses idx_agent_task_queue_runtime_id (migration 273, (runtime_id, id)); before+// it every runtime_id index was partial, so this path had none at all. See+// ListTaskIDsByAgentPage for the single-key / keyset / FOR UPDATE rationale.+func (q *Queries) ListTaskIDsByRuntimePage(ctx context.Context, arg ListTaskIDsByRuntimePageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listTaskIDsByRuntimePage, arg.RuntimeID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceAgentIDFirstPage = `-- name: ListWorkspaceAgentIDFirstPage :many+SELECT id FROM agent+WHERE agent.workspace_id = $1+ORDER BY id+LIMIT $2+`++type ListWorkspaceAgentIDFirstPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk. Split from the keyset query rather than seeded+// with the all-zero uuid, because that value is itself a valid uuid: a row whose+// id happened to be all zeros would be skipped forever by `id > $2`.+func (q *Queries) ListWorkspaceAgentIDFirstPage(ctx context.Context, arg ListWorkspaceAgentIDFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceAgentIDFirstPage, arg.WorkspaceID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceAgentIDPage = `-- name: ListWorkspaceAgentIDPage :many+SELECT id FROM agent+WHERE agent.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3+`++type ListWorkspaceAgentIDPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// Owner enumeration in bounded, keyset-paged chunks. The rows are already locked+// by LockWorkspaceTaskOwnerAgents above; this only walks them.+//+// Keyset on id, not on a natural key: the cursor column must be immutable, and+// renaming an agent mid-teardown would otherwise let it sort behind the cursor+// and escape the sweep. Uses idx_agent_workspace_id_keyset (migration 281), which+// exists so this page does not sort the whole owner set.+func (q *Queries) ListWorkspaceAgentIDPage(ctx context.Context, arg ListWorkspaceAgentIDPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceAgentIDPage, arg.WorkspaceID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceIssueIDFirstPage = `-- name: ListWorkspaceIssueIDFirstPage :many+SELECT id FROM issue+WHERE issue.workspace_id = $1+ORDER BY id+LIMIT $2+`++type ListWorkspaceIssueIDFirstPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk. Split from the keyset query rather than seeded+// with the all-zero uuid, because that value is itself a valid uuid: a row whose+// id happened to be all zeros would be skipped forever by `id > $2`.+func (q *Queries) ListWorkspaceIssueIDFirstPage(ctx context.Context, arg ListWorkspaceIssueIDFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceIssueIDFirstPage, arg.WorkspaceID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceIssueIDPage = `-- name: ListWorkspaceIssueIDPage :many+SELECT id FROM issue+WHERE issue.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3+`++type ListWorkspaceIssueIDPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// Uses idx_issue_workspace_id_keyset (migration 282).+func (q *Queries) ListWorkspaceIssueIDPage(ctx context.Context, arg ListWorkspaceIssueIDPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceIssueIDPage, arg.WorkspaceID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceRuntimeIDFirstPage = `-- name: ListWorkspaceRuntimeIDFirstPage :many+SELECT id FROM agent_runtime+WHERE agent_runtime.workspace_id = $1+ORDER BY id+LIMIT $2+`++type ListWorkspaceRuntimeIDFirstPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int32 `json:"limit"`+}++// First page of the same walk. Split from the keyset query rather than seeded+// with the all-zero uuid, because that value is itself a valid uuid: a row whose+// id happened to be all zeros would be skipped forever by `id > $2`.+func (q *Queries) ListWorkspaceRuntimeIDFirstPage(ctx context.Context, arg ListWorkspaceRuntimeIDFirstPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceRuntimeIDFirstPage, arg.WorkspaceID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceRuntimeIDPage = `-- name: ListWorkspaceRuntimeIDPage :many+SELECT id FROM agent_runtime+WHERE agent_runtime.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3+`++type ListWorkspaceRuntimeIDPageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ID pgtype.UUID `json:"id"`+ Limit int32 `json:"limit"`+}++// Uses idx_agent_runtime_workspace_id_keyset (migration 283).+func (q *Queries) ListWorkspaceRuntimeIDPage(ctx context.Context, arg ListWorkspaceRuntimeIDPageParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listWorkspaceRuntimeIDPage, arg.WorkspaceID, arg.ID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockTaskUsageRollupForWorkspaceDelete = `-- name: LockTaskUsageRollupForWorkspaceDelete :execSELECT pg_advisory_xact_lock(4246)`@@ -484,35 +984,52 @@ func (q *Queries) LockTaskUsageRollupForWorkspaceDelete(ctx context.Context) errreturn err}+const lockWorkspaceTaskOwnerAgents = `-- name: LockWorkspaceTaskOwnerAgents :exec+SELECT 1 FROM agent WHERE agent.workspace_id = $1 FOR UPDATE+`++// The three LockWorkspaceTaskOwner* statements are a write fence, not a lookup —+// they deliberately return nothing, so a workspace with a huge owner set costs+// the API process no memory at all.+//+// agent_task_queue has no workspace_id, so a task becomes this workspace's+// problem through agent_id, issue_id or runtime_id — and inserting such a task+// requires FOR KEY SHARE on the referenced owner row, which conflicts with+// FOR UPDATE. Holding these locks for the rest of the teardown transaction+// therefore blocks any enqueue (or reassignment) that would add a task to this+// workspace after we have swept it, which row locks on the tasks alone cannot+// do. Same technique the handler already uses on the workspace row to keep+// CreateChatSession out of the delete window.+//+// This fence is defence in depth, not the only guarantee: deleteWorkspaceTasks+// re-verifies every owner after sweeping it and fails closed if tasks keep+// appearing, so teardown does not silently leak rows even if the fence is ever+// weakened (for example by removing the legacy FKs this one leans on).+func (q *Queries) LockWorkspaceTaskOwnerAgents(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkspaceTaskOwnerAgents, workspaceID)+ return err+}++const lockWorkspaceTaskOwnerIssues = `-- name: LockWorkspaceTaskOwnerIssues :exec+SELECT 1 FROM issue WHERE issue.workspace_id = $1 FOR UPDATE+`++func (q *Queries) LockWorkspaceTaskOwnerIssues(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkspaceTaskOwnerIssues, workspaceID)+ return err+}++const lockWorkspaceTaskOwnerRuntimes = `-- name: LockWorkspaceTaskOwnerRuntimes :exec+SELECT 1 FROM agent_runtime WHERE agent_runtime.workspace_id = $1 FOR UPDATE+`++func (q *Queries) LockWorkspaceTaskOwnerRuntimes(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkspaceTaskOwnerRuntimes, workspaceID)+ return err+}+const prepareWorkspaceDeletionLinks = `-- name: PrepareWorkspaceDeletionLinks :execWITH-ws_agents AS MATERIALIZED (- SELECT id FROM agent WHERE agent.workspace_id = $1-),-ws_runtimes AS MATERIALIZED (- SELECT id FROM agent_runtime WHERE agent_runtime.workspace_id = $1-),-ws_issues AS MATERIALIZED (- SELECT id FROM issue WHERE issue.workspace_id = $1-),-ws_tasks AS MATERIALIZED (- -- Keep all three ownership paths until the application enforces that a- -- task's agent/runtime/issue always belong to the same workspace. The OR- -- can scan globally, but simplifying it before that invariant exists- -- would turn a performance optimization into a tenant-cleanup bug.- SELECT id- FROM agent_task_queue- WHERE agent_id IN (SELECT id FROM ws_agents)- OR issue_id IN (SELECT id FROM ws_issues)- OR runtime_id IN (SELECT id FROM ws_runtimes)-),-detached_tasks AS (- UPDATE agent_task_queue- SET parent_task_id = NULL,- autopilot_run_id = NULL- WHERE id IN (SELECT id FROM ws_tasks)- AND (parent_task_id IS NOT NULL OR autopilot_run_id IS NOT NULL)-),detached_comments AS (UPDATE commentSET parent_id = NULL@@ -534,6 +1051,9 @@ WHERE webhook_delivery.workspace_id = $1// Break self-references and the task/run cycle explicitly before deleting// either side. This keeps their ordering in the application-owned graph// instead of relying on ON DELETE SET NULL actions.+//+// The task half of this step now lives in DetachTaskBatchReferences, which runs+// once per bounded batch instead of once for a whole workspace's task set.func (q *Queries) PrepareWorkspaceDeletionLinks(ctx context.Context, workspaceID pgtype.UUID) error {_, err := q.db.Exec(ctx, prepareWorkspaceDeletionLinks, workspaceID)return errdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 1872a49048..e4e99a013b 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -278,6 +278,10 @@ WHERE agent_id = $1ORDER BY created_at DESC;-- name: CreateAgentTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- head_sha stamps the commit under review into the task's context JSONB so the-- reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run-- against an OLD head apart from a fresh request against a NEW head (TEN-356).@@ -291,7 +295,7 @@ INSERT INTO agent_task_queue (squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),@@ -314,10 +318,14 @@ VALUES (sqlc.narg(rerun_of_task_id),sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id)-)+WHERE lock_task_owner_rows($1, $3, $2)RETURNING *;-- name: CreateDeferredChannelIssueTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Channel /issue media resolves after issue creation. Persist the assigned-- issue task up front for crash safety, but keep it inert until attachment-- binding settles or the fire_at fallback is promoted by the normal sweeper.@@ -328,7 +336,7 @@ INSERT INTO agent_task_queue (originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,trigger_evidence_kind, trigger_evidence_ref_id, fire_at)-VALUES (+SELECT$1, $2, $3, 'deferred', $4, sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),@@ -351,7 +359,7 @@ VALUES (sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),@fire_at-)+WHERE lock_task_owner_rows($1, $3, $2)RETURNING *;-- name: PromoteDeferredChannelIssueTask :one@@ -376,6 +384,10 @@ WHERE id = @idAND originator_user_id IS NOT DISTINCT FROM sqlc.narg(expected_originator_user_id)::uuid;-- name: CreateQuickCreateTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Quick-create tasks have no issue / chat / autopilot link; the entire job-- description (prompt, requester, workspace) lives in context JSONB. The-- daemon detects this variant via context.type == "quick_create".@@ -387,7 +399,7 @@ INSERT INTO agent_task_queue (accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, NULL, 'queued', $3, $4,sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),@@ -396,10 +408,14 @@ VALUES (sqlc.narg(originator_source),sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id)-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING *;-- name: CreateDeferredAgentTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them-- to queued. Used for comment-routing escalation: a thread-owner primary task-- gets a delayed assignee fallback without waking both agents at t=0.@@ -413,7 +429,7 @@ INSERT INTO agent_task_queue (originator_user_id, accountable_user_id, originator_source,delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT@agent_id, @runtime_id, @issue_id, 'deferred', @priority,sqlc.narg(trigger_comment_id),sqlc.narg(trigger_summary),@@ -427,10 +443,14 @@ VALUES (sqlc.narg(delegated_from_task_id),sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id)-)+WHERE lock_task_owner_rows($1, $3, $2)RETURNING *;-- name: LinkTaskToIssue :exec+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Attaches the issue a quick-create task produced back to the task row, once-- the agent has finished and the issue exists. Guarded by `issue_id IS NULL`-- so this never overwrites an issue id that was set at task creation (only@@ -438,9 +458,14 @@ RETURNING *;-- "Creating issue" forever after completion.UPDATE agent_task_queueSET issue_id = $2-WHERE id = $1 AND issue_id IS NULL;+WHERE id = $1 AND issue_id IS NULL+ AND lock_task_owner_rows(NULL, $2, NULL);-- name: CreateRetryTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Clones a parent task into a fresh queued attempt. Carries forward the-- agent's resume context (session_id/work_dir) so the child can continue-- the conversation when the backend supports it. Resume-unsafe failures are@@ -523,6 +548,7 @@ SELECTp.chat_input_task_id, sqlc.narg(fire_at)FROM agent_task_queue pWHERE p.id = $1+ AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)RETURNING *;-- name: CancelAgentTasksByIssue :manydiff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 57c5bcab15..52895c3151 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -436,6 +436,10 @@ ORDER BY t.id;-- =====================-- name: CreateAutopilotTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- run_only autopilot dispatch. Attribution depends on the trigger:-- * schedule / webhook / api: no human authorized the run, so originator_user_id-- stays NULL and accountable_user_id is the rule_owner (the publisher of the@@ -452,7 +456,7 @@ INSERT INTO agent_task_queue (originator_user_id, accountable_user_id, rule_version_id,originator_source, trigger_evidence_kind, trigger_evidence_ref_id)-VALUES (+SELECT$1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),@@ -460,7 +464,7 @@ VALUES (sqlc.narg(originator_source),sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id)-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING *;-- name: GetAutopilotTaskByRun :onediff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 4a98ea7c40..c81e89f28d 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -905,6 +905,10 @@ SELECT * FROM chat_messageWHERE id = $1;-- name: CreateChatTask :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- The chat sender (initiator) is a direct_human originator and accountable;-- attribution provenance is stamped so this path is not a NULL-source enqueue-- bypass (MUL-4302 §2).@@ -914,7 +918,7 @@ INSERT INTO agent_task_queue (runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,fire_at)-VALUES (+SELECT$1, $2, NULL,CASE WHEN sqlc.narg('fire_at')::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,$3, $4, $5,@@ -927,7 +931,7 @@ VALUES (sqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),sqlc.narg('fire_at')::timestamptz-)+WHERE lock_task_owner_rows($1, NULL, $2)RETURNING *;-- name: PromoteChannelChatTasksIfMediaReady :manydiff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 007639ed18..528e2f9c0f 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -366,13 +366,71 @@ UPDATE agentSET runtime_id = @new_runtime_idWHERE runtime_id = @old_runtime_id;--- name: ReassignTasksToRuntime :execrows+-- name: LockWorkspaceForRuntimeMerge :exec+-- Step 1 of the legacy runtime merge's fence, and the same first step every task+-- write takes (lock_task_owner_rows, migration 284): the workspace row, FOR KEY+-- SHARE. Taking it here rather than relying on the fence inside the reassignment+-- keeps the merge's lock order identical to the writers' — workspaces before owner+-- rows — so the two can never hold each other's next lock (MUL-5999).+SELECT 1 FROM workspace w+WHERE w.id IN (+ SELECT r.workspace_id FROM agent_runtime r WHERE r.id = ANY(@runtime_ids::uuid[])+)+ORDER BY w.id+FOR KEY SHARE;++-- name: LockRuntimesForMerge :many+-- Step 2: the runtime rows themselves, FOR UPDATE, in id order.+--+-- FOR UPDATE is the point. A task write's fence takes FOR KEY SHARE on the runtime+-- it references, and KEY SHARE conflicts with UPDATE but not with another KEY+-- SHARE — so while the merge held only the workspace's KEY SHARE, a concurrent+-- enqueue against the OLD runtime went straight through after the task scan and was+-- then silently removed by ON DELETE CASCADE when the old runtime was deleted.+-- Holding FOR UPDATE on both runtimes from before the scan until COMMIT means a+-- late writer either commits first (and the scan sees its task) or waits and finds+-- the runtime gone, which its fence reports as "no row written".+--+-- Both runtimes are locked in one ordered statement so two merges running in+-- opposite directions cannot take the same pair in opposite orders.+--+-- Returns the ids it actually locked: a caller that asked for two and got fewer+-- knows a runtime disappeared before it got there and must abandon the merge.+SELECT id FROM agent_runtime+WHERE id = ANY(@runtime_ids::uuid[])+ORDER BY id+FOR UPDATE;++-- name: ReassignTasksToRuntime :one+-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)+-- locks the owners' workspace rows in the writer's own transaction and returns+-- false once they are gone, so this statement writes no row instead of stranding+-- a task in a workspace that has just been deleted (MUL-5999).-- Re-points every queued/running/completed task referencing old_runtime_id.-- Required before deleting the old runtime row because agent_task_queue has-- an ON DELETE CASCADE FK that would otherwise drop historical tasks.-UPDATE agent_task_queue-SET runtime_id = @new_runtime_id-WHERE runtime_id = @old_runtime_id;+--+-- Returns the fence verdict separately from the row count on purpose. "0 rows"+-- is ambiguous — it means either "the old runtime had no tasks" or "the fence+-- refused" — and a caller that cannot tell them apart would go on to delete the+-- old runtime, letting that same ON DELETE CASCADE drop the very history this+-- statement exists to preserve. FenceOk = false must abort the merge.+WITH fence AS MATERIALIZED (+ -- Once per statement rather than once per row: the predicate is VOLATILE, so+ -- calling it from the WHERE clause of a bulk UPDATE would re-run it for every+ -- candidate row.+ SELECT lock_task_owner_rows(NULL, NULL, @new_runtime_id) AS ok+),+reassigned AS (+ UPDATE agent_task_queue+ SET runtime_id = @new_runtime_id+ WHERE runtime_id = @old_runtime_id+ AND (SELECT ok FROM fence)+ RETURNING id+)+SELECT+ (SELECT ok FROM fence) AS fence_ok,+ (SELECT count(*) FROM reassigned) AS reassigned_tasks;-- name: RecordRuntimeLegacyDaemonID :exec-- Remembers the most recent hostname-derived daemon_id that was merged intodiff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 05deef869a..e5847a600f 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -16,38 +16,230 @@ SELECT set_config('multica.workspace_teardown', 'on', true);-- minutes, and an unbounded wait here hangs the delete request (MUL-5983).SELECT pg_advisory_xact_lock(4246);--- name: PrepareWorkspaceDeletionLinks :exec--- Break self-references and the task/run cycle explicitly before deleting--- either side. This keeps their ordering in the application-owned graph--- instead of relying on ON DELETE SET NULL actions.+-- name: LockWorkspaceTaskOwnerAgents :exec+-- The three LockWorkspaceTaskOwner* statements are a write fence, not a lookup —+-- they deliberately return nothing, so a workspace with a huge owner set costs+-- the API process no memory at all.+--+-- agent_task_queue has no workspace_id, so a task becomes this workspace's+-- problem through agent_id, issue_id or runtime_id — and inserting such a task+-- requires FOR KEY SHARE on the referenced owner row, which conflicts with+-- FOR UPDATE. Holding these locks for the rest of the teardown transaction+-- therefore blocks any enqueue (or reassignment) that would add a task to this+-- workspace after we have swept it, which row locks on the tasks alone cannot+-- do. Same technique the handler already uses on the workspace row to keep+-- CreateChatSession out of the delete window.+--+-- This fence is defence in depth, not the only guarantee: deleteWorkspaceTasks+-- re-verifies every owner after sweeping it and fails closed if tasks keep+-- appearing, so teardown does not silently leak rows even if the fence is ever+-- weakened (for example by removing the legacy FKs this one leans on).+SELECT 1 FROM agent WHERE agent.workspace_id = $1 FOR UPDATE;++-- name: LockWorkspaceTaskOwnerIssues :exec+SELECT 1 FROM issue WHERE issue.workspace_id = $1 FOR UPDATE;++-- name: LockWorkspaceTaskOwnerRuntimes :exec+SELECT 1 FROM agent_runtime WHERE agent_runtime.workspace_id = $1 FOR UPDATE;++-- name: ListWorkspaceAgentIDFirstPage :many+-- First page of the same walk. Split from the keyset query rather than seeded+-- with the all-zero uuid, because that value is itself a valid uuid: a row whose+-- id happened to be all zeros would be skipped forever by `id > $2`.+SELECT id FROM agent+WHERE agent.workspace_id = $1+ORDER BY id+LIMIT $2;++-- name: ListWorkspaceAgentIDPage :many+-- Owner enumeration in bounded, keyset-paged chunks. The rows are already locked+-- by LockWorkspaceTaskOwnerAgents above; this only walks them.+--+-- Keyset on id, not on a natural key: the cursor column must be immutable, and+-- renaming an agent mid-teardown would otherwise let it sort behind the cursor+-- and escape the sweep. Uses idx_agent_workspace_id_keyset (migration 281), which+-- exists so this page does not sort the whole owner set.+SELECT id FROM agent+WHERE agent.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3;++-- name: ListWorkspaceIssueIDFirstPage :many+-- First page of the same walk. Split from the keyset query rather than seeded+-- with the all-zero uuid, because that value is itself a valid uuid: a row whose+-- id happened to be all zeros would be skipped forever by `id > $2`.+SELECT id FROM issue+WHERE issue.workspace_id = $1+ORDER BY id+LIMIT $2;++-- name: ListWorkspaceIssueIDPage :many+-- Uses idx_issue_workspace_id_keyset (migration 282).+SELECT id FROM issue+WHERE issue.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3;++-- name: ListWorkspaceRuntimeIDFirstPage :many+-- First page of the same walk. Split from the keyset query rather than seeded+-- with the all-zero uuid, because that value is itself a valid uuid: a row whose+-- id happened to be all zeros would be skipped forever by `id > $2`.+SELECT id FROM agent_runtime+WHERE agent_runtime.workspace_id = $1+ORDER BY id+LIMIT $2;++-- name: ListWorkspaceRuntimeIDPage :many+-- Uses idx_agent_runtime_workspace_id_keyset (migration 283).+SELECT id FROM agent_runtime+WHERE agent_runtime.workspace_id = $1 AND id > $2+ORDER BY id+LIMIT $3;++-- name: ListTaskIDsByAgentFirstPage :many+-- First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+-- a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+-- the single-key / keyset / FOR UPDATE rationale.+SELECT id FROM agent_task_queue+WHERE agent_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE;++-- name: ListTaskIDsByAgentPage :many+-- One owner key per call, one keyset-paged chunk per call.+--+-- Single-key equality is deliberate. All three ownership paths must stay (nothing+-- enforces that a task's agent/runtime/issue share a workspace), but expressing+-- them as `OR agent_id IN (subquery) OR …` — or as a UNION of joins, or as+-- `= ANY($1::uuid[])` over a whole workspace's agents — makes the planner+-- estimate a proportional share of the global table and fall back to a Seq Scan+-- on agent_task_queue. A single-key equality is the only form whose row estimate+-- stays small enough to be index-driven regardless of how the workspace's tasks+-- are distributed (MUL-5999).+--+-- `id > $2 ORDER BY id LIMIT $3` against idx_agent_task_queue_agent_id_keyset+-- (migration 278) bounds the SCAN, not just the result: each page is an index+-- range scan that starts where the previous one stopped. Bounding only the result+-- — `ORDER BY id LIMIT n` against the (agent_id, status) index — puts a Sort over+-- the agent's entire task set in front of every page, so a busy agent costs+-- roughly O(N² / page) for the sweep.+--+-- FOR UPDATE is load-bearing for correctness, not throughput. It locks the rows+-- this page is about to delete, and under READ COMMITTED PostgreSQL re-checks the+-- WHERE clause after acquiring each lock: a task a concurrent committed UPDATE+-- has already moved to another owner no longer matches and is skipped, and one we+-- did lock cannot be moved away before we delete it.+SELECT id FROM agent_task_queue+WHERE agent_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE;++-- name: ListTaskIDsByIssueFirstPage :many+-- First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+-- a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+-- the single-key / keyset / FOR UPDATE rationale.+SELECT id FROM agent_task_queue+WHERE issue_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE;++-- name: ListTaskIDsByIssuePage :many+-- Uses idx_agent_task_queue_issue_id_keyset (migration 279). See+-- ListTaskIDsByAgentPage for the single-key / keyset / FOR UPDATE rationale.+SELECT id FROM agent_task_queue+WHERE issue_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE;++-- name: ListTaskIDsByRuntimeFirstPage :many+-- First page of the same walk; see ListWorkspaceAgentIDFirstPage for why this is+-- a separate query rather than a zero-uuid cursor, and ListTaskIDsByAgentPage for+-- the single-key / keyset / FOR UPDATE rationale.+SELECT id FROM agent_task_queue+WHERE runtime_id = $1+ORDER BY id+LIMIT $2+FOR UPDATE;++-- name: ListTaskIDsByRuntimePage :many+-- Uses idx_agent_task_queue_runtime_id (migration 273, (runtime_id, id)); before+-- it every runtime_id index was partial, so this path had none at all. See+-- ListTaskIDsByAgentPage for the single-key / keyset / FOR UPDATE rationale.+SELECT id FROM agent_task_queue+WHERE runtime_id = $1 AND id > $2+ORDER BY id+LIMIT $3+FOR UPDATE;++-- name: DetachTaskBatchReferences :exec+-- Break inbound references to a task batch before deleting it, in the+-- application layer rather than through the FKs' ON DELETE SET NULL. Both+-- referencing columns are indexed (idx_agent_task_queue_parent from migration+-- 055, idx_autopilot_run_task_id from migration 277) so this stays a per-batch+-- index scan instead of the per-row full scan the FK action would do.+--+-- Kept separate from DeleteTaskBatch: a task can be both a member of the batch+-- and the parent of another member, and updating plus deleting the same row+-- inside one statement is not well defined.+WITH detached_runs AS (+ UPDATE autopilot_run+ SET task_id = NULL+ WHERE task_id = ANY(@task_ids::uuid[])+)+UPDATE agent_task_queue+SET parent_task_id = NULL+WHERE parent_task_id = ANY(@task_ids::uuid[]);++-- name: DeleteTaskBatch :exec+-- Deletes one bounded batch of tasks together with everything that hangs off+-- them, every arm keyed by task_id against an existing index, then the task rows+-- by primary key. The legacy FK cascades stay a safety net only: this statement+-- is what actually removes the rows, so teardown keeps working when they go.WITH-ws_agents AS MATERIALIZED (- SELECT id FROM agent WHERE agent.workspace_id = $1+batch AS MATERIALIZED (+ SELECT id FROM unnest(@task_ids::uuid[]) AS t(id)),-ws_runtimes AS MATERIALIZED (- SELECT id FROM agent_runtime WHERE agent_runtime.workspace_id = $1+deleted_task_usage AS (+ DELETE FROM task_usage WHERE task_id IN (SELECT id FROM batch)),-ws_issues AS MATERIALIZED (- SELECT id FROM issue WHERE issue.workspace_id = $1-),-ws_tasks AS MATERIALIZED (- -- Keep all three ownership paths until the application enforces that a- -- task's agent/runtime/issue always belong to the same workspace. The OR- -- can scan globally, but simplifying it before that invariant exists- -- would turn a performance optimization into a tenant-cleanup bug.- SELECT id- FROM agent_task_queue- WHERE agent_id IN (SELECT id FROM ws_agents)- OR issue_id IN (SELECT id FROM ws_issues)- OR runtime_id IN (SELECT id FROM ws_runtimes)+deleted_task_messages AS (+ DELETE FROM task_message WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_tokens AS (+ DELETE FROM task_token WHERE task_id IN (SELECT id FROM batch)+),+deleted_channel_outbound_cards AS (+ DELETE FROM channel_outbound_card_message WHERE task_id IN (SELECT id FROM batch)),-detached_tasks AS (- UPDATE agent_task_queue- SET parent_task_id = NULL,- autopilot_run_id = NULL- WHERE id IN (SELECT id FROM ws_tasks)- AND (parent_task_id IS NOT NULL OR autopilot_run_id IS NOT NULL)+deleted_lark_outbound_cards AS (+ DELETE FROM lark_outbound_card_message WHERE task_id IN (SELECT id FROM batch)),+deleted_draft_restores AS (+ DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)+)+DELETE FROM agent_task_queue WHERE id IN (SELECT id FROM batch);++-- name: DeleteTaskTokensByAgent :exec+-- The third explicit task_token path. workspace_id (in DeleteWorkspaceLeafData)+-- and task_id (in DeleteTaskBatch) do not cover a token whose own workspace_id+-- points at a neighbour while its agent lives here, and teardown must not fall+-- back on the agent_id cascade for it. Uses idx_task_token_agent_id+-- (migration 275); one agent key per call for the same planner reason as+-- ListTaskIDsByAgentBatch.+DELETE FROM task_token WHERE agent_id = $1;++-- name: PrepareWorkspaceDeletionLinks :exec+-- Break self-references and the task/run cycle explicitly before deleting+-- either side. This keeps their ordering in the application-owned graph+-- instead of relying on ON DELETE SET NULL actions.+--+-- The task half of this step now lives in DetachTaskBatchReferences, which runs+-- once per bounded batch instead of once for a whole workspace's task set.+WITHdetached_comments AS (UPDATE commentSET parent_id = NULL@@ -66,13 +258,13 @@ WHERE webhook_delivery.workspace_id = $1AND replayed_from_delivery_id IS NOT NULL;-- name: DeleteWorkspaceLeafData :exec+-- Everything task-keyed moved to DeleteTaskBatch, which runs in bounded batches+-- before this step; what is left is keyed by the workspace or by one of the+-- workspace-scoped id sets below.WITHws_agents AS MATERIALIZED (SELECT id FROM agent WHERE workspace_id = $1),-ws_runtimes AS MATERIALIZED (- SELECT id FROM agent_runtime WHERE workspace_id = $1-),ws_issues AS MATERIALIZED (SELECT id FROM issue WHERE workspace_id = $1),@@ -85,13 +277,6 @@ ws_skills AS MATERIALIZED (ws_squads AS MATERIALIZED (SELECT id FROM squad WHERE workspace_id = $1),-ws_tasks AS MATERIALIZED (- SELECT id- FROM agent_task_queue- WHERE agent_id IN (SELECT id FROM ws_agents)- OR issue_id IN (SELECT id FROM ws_issues)- OR runtime_id IN (SELECT id FROM ws_runtimes)-),ws_sessions AS MATERIALIZED (SELECT id FROM chat_session WHERE workspace_id = $1),@@ -113,19 +298,15 @@ ws_channel_installations AS MATERIALIZED (ws_lark_installations AS MATERIALIZED (SELECT id FROM lark_installation WHERE workspace_id = $1),-deleted_task_usage AS (- DELETE FROM task_usage- WHERE task_id IN (SELECT id FROM ws_tasks)-),-deleted_task_messages AS (- DELETE FROM task_message- WHERE task_id IN (SELECT id FROM ws_tasks)-),+-- One of three explicit task_token paths. This is the workspace-keyed one;+-- DeleteTaskBatch covers task_id and DeleteTaskTokensByAgent covers agent_id, so+-- a token whose workspace_id points at a neighbour while its task or agent lives+-- here is still removed by this teardown rather than by the FK cascade. The+-- former single statement combined all three with OR, which cost a full scan of+-- task_token (MUL-5999); split, each path is an index scan.deleted_task_tokens AS (DELETE FROM task_tokenWHERE workspace_id = $1- OR task_id IN (SELECT id FROM ws_tasks)- OR agent_id IN (SELECT id FROM ws_agents)),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1@@ -139,17 +320,14 @@ deleted_attachments AS (deleted_channel_outbound_cards AS (DELETE FROM channel_outbound_card_messageWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),deleted_lark_outbound_cards AS (DELETE FROM lark_outbound_card_messageWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),deleted_draft_restores AS (DELETE FROM chat_draft_restoreWHERE chat_session_id IN (SELECT id FROM ws_sessions)- OR task_id IN (SELECT id FROM ws_tasks)),-- Same no-FK chore as chat_draft_restore above. Matched on workspace_id rather-- than the session set because that column exists precisely so this statement@@ -306,12 +484,6 @@ SET state = CASElast_error = NULLWHERE channel_media_pending_object.workspace_id = $1;--- name: DeleteWorkspaceTasks :exec-DELETE FROM agent_task_queue-WHERE agent_id IN (SELECT id FROM agent WHERE agent.workspace_id = $1)- OR issue_id IN (SELECT id FROM issue WHERE issue.workspace_id = $1)- OR runtime_id IN (SELECT id FROM agent_runtime WHERE agent_runtime.workspace_id = $1);--- name: DeleteWorkspaceChatMessages :execDELETE FROM chat_messageWHERE chat_session_id IN (