Skip to content

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

Go

MUL-5562: optimize application-owned workspace deletion (#6230)

Multica Evef48bd655bcc5
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 0cb02f6194..bf1638c353 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -794,18 +794,112 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
- if err := qtx.DeleteChatPinnedAgentsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {
- slog.Warn("delete workspace chat pins failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
- writeError(w, http.StatusInternalServerError, "failed to delete workspace")
- return
- }
-
- // At this point workspaceMember has resolved → workspaceID is a valid UUID
- // (the lookup would have errored otherwise), so reuse the resolved value.
- if err := qtx.DeleteWorkspace(r.Context(), requester.WorkspaceID); err != nil {
- slog.Warn("delete workspace failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
- writeError(w, http.StatusInternalServerError, "failed to delete workspace")
- return
+ // Keep the relationship graph in the application layer. Each step is a
+ // set-based delete scoped by workspace_id; the legacy cascades remain only
+ // as an expand-phase safety net until a later schema contract.
+ ctx := r.Context()
+ deleteSteps := []struct {
+ name string
+ run func() error
+ }{
+ {
+ name: "set teardown mode",
+ run: func() error { return qtx.SetWorkspaceTeardownMode(ctx) },
+ },
+ {
+ name: "prepare relationship graph",
+ run: func() error { return qtx.PrepareWorkspaceDeletionLinks(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete chat pins",
+ run: func() error { return qtx.DeleteChatPinnedAgentsByWorkspace(ctx, requester.WorkspaceID) },
+ },
+ {
+ // This is the first stage that touches usage rollups. Keep the
+ // global rollup lock out of relationship preparation so unrelated
+ // workspaces skip the shortest possible rollup window.
+ name: "lock task usage rollup",
+ run: func() error { return qtx.LockTaskUsageRollupForWorkspaceDelete(ctx) },
+ },
+ {
+ name: "delete leaf data",
+ run: func() error { return qtx.DeleteWorkspaceLeafData(ctx, requester.WorkspaceID) },
+ },
+ {
+ 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) },
+ },
+ {
+ name: "delete communication roots",
+ run: func() error { return qtx.DeleteWorkspaceCommunicationRoots(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete comments",
+ run: func() error { return qtx.DeleteWorkspaceComments(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete issue roots",
+ run: func() error { return qtx.DeleteWorkspaceIssueRoots(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete autopilot children",
+ run: func() error { return qtx.DeleteWorkspaceAutopilotChildren(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete autopilots",
+ run: func() error { return qtx.DeleteWorkspaceAutopilots(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete pull requests",
+ run: func() error { return qtx.DeleteWorkspacePullRequests(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete integrations",
+ run: func() error { return qtx.DeleteWorkspaceConnections(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete squads and skills",
+ run: func() error { return qtx.DeleteWorkspaceSquadsAndSkills(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete agents",
+ run: func() error { return qtx.DeleteWorkspaceAgents(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete runtimes and projects",
+ run: func() error { return qtx.DeleteWorkspaceRuntimesAndProjects(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete administration data",
+ run: func() error { return qtx.DeleteWorkspaceAdministration(ctx, requester.WorkspaceID) },
+ },
+ {
+ // At this point workspaceMember has resolved → workspaceID is a
+ // valid UUID, so reuse the resolved value. The existing final
+ // statement also sweeps any expand-phase compatibility leftovers.
+ name: "delete workspace",
+ run: func() error { return qtx.DeleteWorkspace(ctx, requester.WorkspaceID) },
+ },
+ }
+ for _, step := range deleteSteps {
+ if err := step.run(); err != nil {
+ slog.Warn("workspace delete step failed", append(
+ logger.RequestAttrs(r),
+ "error", err,
+ "workspace_id", workspaceID,
+ "step", step.name,
+ )...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ return
+ }
}
if err := tx.Commit(r.Context()); err != nil {
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
new file mode 100644
index 0000000000..fbfc28f168
--- /dev/null
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -0,0 +1,191 @@
+package handler
+
+import (
+ "context"
+ "sort"
+ "testing"
+)
+
+type workspaceDeleteAction string
+
+const (
+ workspaceDelete workspaceDeleteAction = "delete"
+ workspaceDeleteDetach workspaceDeleteAction = "detach"
+ workspaceDeleteKeep workspaceDeleteAction = "keep"
+ workspaceDeleteSettle workspaceDeleteAction = "settle"
+)
+
+// workspaceDeletionManifest is the schema coverage contract for workspace
+// teardown. Adding a table requires an explicit ownership decision here; the
+// handler deletion graph must then implement that decision before CI passes.
+var workspaceDeletionManifest = map[string]workspaceDeleteAction{
+ "activity_log": workspaceDelete,
+ "agent": workspaceDelete,
+ "agent_invocation_target": workspaceDelete,
+ "agent_runtime": workspaceDelete,
+ "agent_skill": workspaceDelete,
+ "agent_task_queue": workspaceDelete,
+ "agent_to_label": workspaceDelete,
+ "attachment": workspaceDelete,
+ "autopilot": workspaceDelete,
+ "autopilot_collaborator": workspaceDelete,
+ "autopilot_rule_version": workspaceDelete,
+ "autopilot_run": workspaceDelete,
+ "autopilot_subscriber": workspaceDelete,
+ "autopilot_trigger": workspaceDelete,
+ "channel_binding_token": workspaceDelete,
+ "channel_chat_session_binding": workspaceDelete,
+ "channel_inbound_audit": workspaceDelete,
+ "channel_inbound_message_dedup": workspaceDelete,
+ "channel_installation": workspaceDelete,
+ "channel_media_pending_object": workspaceDeleteSettle,
+ "channel_outbound_card_message": workspaceDelete,
+ "channel_user_binding": workspaceDelete,
+ "chat_draft_restore": workspaceDelete,
+ "chat_message": workspaceDelete,
+ "chat_pinned_agent": workspaceDelete,
+ "chat_session": workspaceDelete,
+ "client_usage_daily": workspaceDeleteDetach,
+ "comment": workspaceDelete,
+ "comment_reaction": workspaceDelete,
+ "contact_sales_inquiry": workspaceDeleteKeep,
+ "daemon_connection": workspaceDelete,
+ "daemon_token": workspaceDelete,
+ "feedback": workspaceDeleteDetach,
+ "github_installation": workspaceDelete,
+ "github_pending_check_suite": workspaceDelete,
+ "github_pending_installation": workspaceDeleteKeep,
+ "github_pull_request": workspaceDelete,
+ "github_pull_request_check_run": workspaceDelete,
+ "github_pull_request_check_suite": workspaceDelete,
+ "inbox_item": workspaceDelete,
+ "issue": workspaceDelete,
+ "issue_dependency": workspaceDelete,
+ "issue_label": workspaceDelete,
+ "issue_property": workspaceDelete,
+ "issue_pull_request": workspaceDelete,
+ "issue_reaction": workspaceDelete,
+ "issue_subscriber": workspaceDelete,
+ "issue_to_label": workspaceDelete,
+ "issue_vcs_pull_request": workspaceDelete,
+ "lark_binding_token": workspaceDelete,
+ "lark_chat_session_binding": workspaceDelete,
+ "lark_inbound_audit": workspaceDelete,
+ "lark_inbound_message_dedup": workspaceDelete,
+ "lark_installation": workspaceDelete,
+ "lark_outbound_card_message": workspaceDelete,
+ "lark_user_binding": workspaceDelete,
+ "member": workspaceDelete,
+ "notification_preference": workspaceDelete,
+ "personal_access_token": workspaceDeleteKeep,
+ "pinned_item": workspaceDelete,
+ "project": workspaceDelete,
+ "project_resource": workspaceDelete,
+ "quick_action": workspaceDelete,
+ "runtime_profile": workspaceDelete,
+ "schema_migrations": workspaceDeleteKeep,
+ "skill": workspaceDelete,
+ "skill_file": workspaceDelete,
+ "skill_to_label": workspaceDelete,
+ "squad": workspaceDelete,
+ "squad_member": workspaceDelete,
+ "sys_cron_executions": workspaceDeleteKeep,
+ "task_message": workspaceDelete,
+ "task_token": workspaceDelete,
+ "task_usage": workspaceDelete,
+ "task_usage_hourly": workspaceDelete,
+ "task_usage_hourly_dirty": workspaceDelete,
+ "task_usage_hourly_rollup_state": workspaceDeleteKeep,
+ "user": workspaceDeleteKeep,
+ "user_composio_connection": workspaceDeleteKeep,
+ "vcs_commit_status": workspaceDelete,
+ "vcs_connection": workspaceDelete,
+ "vcs_pull_request": workspaceDelete,
+ "verification_code": workspaceDeleteKeep,
+ "webhook_delivery": workspaceDelete,
+ "workspace": workspaceDelete,
+ "workspace_invitation": workspaceDelete,
+}
+
+func TestWorkspaceDeletionManifestCoversPublicSchema(t *testing.T) {
+ if testPool == nil {
+ t.Skip("database not available")
+ }
+
+ rows, err := testPool.Query(context.Background(), `
+SELECT tablename
+FROM pg_tables
+WHERE schemaname = 'public'
+ORDER BY tablename
+`)
+ if err != nil {
+ t.Fatalf("list public tables: %v", err)
+ }
+ defer rows.Close()
+
+ actual := make(map[string]struct{}, len(workspaceDeletionManifest))
+ for rows.Next() {
+ var table string
+ if err := rows.Scan(&table); err != nil {
+ t.Fatalf("scan public table: %v", err)
+ }
+ actual[table] = struct{}{}
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate public tables: %v", err)
+ }
+
+ var unclassified, missing []string
+ for table := range actual {
+ if _, ok := workspaceDeletionManifest[table]; !ok {
+ unclassified = append(unclassified, table)
+ }
+ }
+ for table := range workspaceDeletionManifest {
+ if _, ok := actual[table]; !ok {
+ missing = append(missing, table)
+ }
+ }
+ sort.Strings(unclassified)
+ sort.Strings(missing)
+ if len(unclassified) > 0 || len(missing) > 0 {
+ t.Fatalf("workspace deletion manifest drift: unclassified=%v missing=%v", unclassified, missing)
+ }
+
+ workspaceColumns, err := testPool.Query(context.Background(), `
+SELECT table_name
+FROM information_schema.columns
+WHERE table_schema = 'public'
+ AND column_name = 'workspace_id'
+`)
+ if err != nil {
+ t.Fatalf("list workspace_id columns: %v", err)
+ }
+ defer workspaceColumns.Close()
+
+ withWorkspaceID := make(map[string]struct{})
+ for workspaceColumns.Next() {
+ var table string
+ if err := workspaceColumns.Scan(&table); err != nil {
+ t.Fatalf("scan workspace_id table: %v", err)
+ }
+ withWorkspaceID[table] = struct{}{}
+ }
+ if err := workspaceColumns.Err(); err != nil {
+ t.Fatalf("iterate workspace_id tables: %v", err)
+ }
+
+ for table, action := range workspaceDeletionManifest {
+ _, hasWorkspaceID := withWorkspaceID[table]
+ switch action {
+ case workspaceDeleteKeep:
+ if hasWorkspaceID {
+ t.Errorf("KEEP table %s gained workspace_id; classify its teardown behavior", table)
+ }
+ case workspaceDeleteDetach, workspaceDeleteSettle:
+ if !hasWorkspaceID {
+ t.Errorf("%s table %s lost workspace_id; update its teardown selector", action, table)
+ }
+ }
+ }
+}
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index c8ba75b60b..0c1cb7ef95 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"sort"
+ "strings"
"testing"
)
@@ -246,6 +247,141 @@ RETURNING id
_, _ = testPool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, propertyID)
})
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO agent_runtime (
+ workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id
+)
+VALUES ($1, 'Workspace delete runtime', 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $2)
+RETURNING id
+`, wsID, testUserID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create workspace runtime: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO agent (
+ workspace_id, name, runtime_mode, runtime_config, runtime_id, owner_id
+)
+VALUES ($1, 'Workspace delete agent', 'cloud', '{}'::jsonb, $2, $3)
+RETURNING id
+`, wsID, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("create workspace agent: %v", err)
+ }
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO issue (workspace_id, title, creator_type, creator_id)
+VALUES ($1, 'Workspace delete issue', 'member', $2)
+RETURNING id
+`, wsID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create workspace issue: %v", err)
+ }
+
+ var autopilotID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO autopilot (
+ workspace_id, title, assignee_id, created_by_type, created_by_id
+)
+VALUES ($1, 'Workspace delete autopilot', $2, 'member', $3)
+RETURNING id
+`, wsID, agentID, testUserID).Scan(&autopilotID); err != nil {
+ t.Fatalf("create workspace autopilot: %v", err)
+ }
+
+ var autopilotRunID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO autopilot_run (autopilot_id, source, status, issue_id)
+VALUES ($1, 'manual', 'completed', $2)
+RETURNING id
+`, autopilotID, issueID).Scan(&autopilotRunID); err != nil {
+ t.Fatalf("create workspace autopilot run: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, autopilot_run_id
+)
+VALUES ($1, $2, $3, 'completed', 0, $4)
+RETURNING id
+`, agentID, runtimeID, issueID, autopilotRunID).Scan(&taskID); err != nil {
+ t.Fatalf("create workspace task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+UPDATE autopilot_run SET task_id = $2 WHERE id = $1
+`, autopilotRunID, taskID); err != nil {
+ t.Fatalf("link workspace autopilot run to task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)
+VALUES ($1, 'delete-test', 'workspace-delete', 10, 5)
+`, taskID); err != nil {
+ t.Fatalf("create workspace task usage: %v", err)
+ }
+
+ var rollupRuntimeID, rollupAgentID string
+ if err := testPool.QueryRow(ctx, `SELECT gen_random_uuid(), gen_random_uuid()`).Scan(&rollupRuntimeID, &rollupAgentID); err != nil {
+ t.Fatalf("create rollup fixture IDs: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO task_usage_hourly (
+ bucket_hour, workspace_id, runtime_id, agent_id, provider, model,
+ input_tokens, output_tokens, task_count, event_count
+)
+VALUES (date_trunc('hour', now()), $1, $2, $3, 'delete-test', 'workspace-rollup', 10, 5, 1, 1)
+`, wsID, rollupRuntimeID, rollupAgentID); err != nil {
+ t.Fatalf("create workspace hourly usage: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id, provider, model
+)
+VALUES (date_trunc('hour', now()), $1, $2, $3, 'delete-test', 'workspace-rollup')
+`, wsID, rollupRuntimeID, rollupAgentID); err != nil {
+ t.Fatalf("create workspace dirty usage: %v", err)
+ }
+
+ var runtimeProfileID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO runtime_profile (
+ workspace_id, display_name, protocol_family, command_name, created_by
+)
+VALUES ($1, 'Delete cleanup profile', 'codex', 'codex', $2)
+RETURNING id
+`, wsID, testUserID).Scan(&runtimeProfileID); err != nil {
+ t.Fatalf("create runtime profile: %v", err)
+ }
+
+ var ruleVersionID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO autopilot_rule_version (
+ autopilot_id, workspace_id, published_by_type, published_by_id
+)
+VALUES (gen_random_uuid(), $1, 'member', $2)
+RETURNING id
+`, wsID, testUserID).Scan(&ruleVersionID); err != nil {
+ t.Fatalf("create autopilot rule version: %v", err)
+ }
+
+ const pendingObjectKey = "workspace-delete-pending-object"
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO channel_media_pending_object (
+ storage_key, workspace_id, chat_message_id, storage_url
+)
+VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/pending-object')
+`, pendingObjectKey, wsID); err != nil {
+ t.Fatalf("create pending channel media object: %v", err)
+ }
+
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1`, wsID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly WHERE workspace_id = $1`, wsID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE id = $1`, runtimeProfileID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot_rule_version WHERE id = $1`, ruleVersionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_media_pending_object WHERE storage_key = $1`, pendingObjectKey)
+ })
+
w := httptest.NewRecorder()
req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)
req = withURLParam(req, "id", wsID)
@@ -286,6 +422,307 @@ RETURNING id
if propertyCount != 0 {
t.Fatalf("issue properties were not cleaned up for deleted workspace: %d", propertyCount)
}
+
+ for _, table := range []string{
+ "task_usage_hourly_dirty",
+ "task_usage_hourly",
+ "runtime_profile",
+ "autopilot_rule_version",
+ } {
+ var count int
+ if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM `+table+` WHERE workspace_id = $1`, wsID).Scan(&count); err != nil {
+ t.Fatalf("verify %s cleanup: %v", table, err)
+ }
+ if count != 0 {
+ t.Fatalf("%s rows survived workspace delete: %d", table, count)
+ }
+ }
+
+ var pendingObjectState string
+ if err := testPool.QueryRow(ctx, `
+SELECT state
+FROM channel_media_pending_object
+WHERE storage_key = $1
+`, pendingObjectKey).Scan(&pendingObjectState); err != nil {
+ t.Fatalf("verify pending channel media object handoff: %v", err)
+ }
+ if pendingObjectState != "deleting" {
+ t.Fatalf("pending channel media object state = %q, want deleting", pendingObjectState)
+ }
+}
+
+func TestDeleteWorkspace_DirtyTriggersHaveTeardownGuard(t *testing.T) {
+ ctx := context.Background()
+ for _, triggerName := range []string{
+ "trg_atq_dirty_hourly",
+ "trg_issue_delete_dirty_hourly",
+ "trg_tu_dirty_hourly",
+ } {
+ var definition string
+ if err := testPool.QueryRow(ctx, `
+SELECT pg_get_triggerdef(oid)
+FROM pg_trigger
+WHERE tgname = $1
+ AND NOT tgisinternal
+`, triggerName).Scan(&definition); err != nil {
+ t.Fatalf("read trigger %s: %v", triggerName, err)
+ }
+ if !strings.Contains(definition, "multica.workspace_teardown") {
+ t.Fatalf("trigger %s does not guard workspace teardown: %s", triggerName, definition)
+ }
+ }
+}
+
+func TestWorkspaceTeardownModeDoesNotLeakIntoOrdinaryDeletes(t *testing.T) {
+ ctx := context.Background()
+ conn, err := testPool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+
+ tx, err := conn.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin teardown marker transaction: %v", err)
+ }
+ if _, err := tx.Exec(ctx, `SELECT set_config('multica.workspace_teardown', 'on', true)`); err != nil {
+ _ = tx.Rollback(ctx)
+ t.Fatalf("set transaction-local teardown mode: %v", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit teardown marker transaction: %v", err)
+ }
+
+ var teardownMode string
+ if err := conn.QueryRow(ctx, `SELECT current_setting('multica.workspace_teardown', true)`).Scan(&teardownMode); err != nil {
+ t.Fatalf("read teardown mode after commit: %v", err)
+ }
+ if teardownMode != "" {
+ t.Fatalf("teardown mode leaked after commit: %q", teardownMode)
+ }
+
+ var runtimeID, agentID string
+ if err := conn.QueryRow(ctx, `
+SELECT runtime.id, agent.id
+FROM agent_runtime AS runtime
+JOIN agent ON agent.runtime_id = runtime.id
+WHERE runtime.workspace_id = $1
+LIMIT 1
+`, testWorkspaceID).Scan(&runtimeID, &agentID); err != nil {
+ t.Fatalf("load ordinary delete fixture agent: %v", err)
+ }
+
+ var issueID string
+ if err := conn.QueryRow(ctx, `
+INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+VALUES (
+ $1, 'ordinary delete after workspace teardown', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1)
+)
+RETURNING id
+`, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create ordinary delete issue: %v", err)
+ }
+ var taskID string
+ if err := conn.QueryRow(ctx, `
+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)
+VALUES ($1, $2, $3, 'completed')
+RETURNING id
+`, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("create ordinary delete task: %v", err)
+ }
+
+ const provider = "workspace-teardown-ordinary-delete"
+ _, _ = conn.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE provider = $1`, provider)
+ _, _ = conn.Exec(ctx, `DELETE FROM task_usage_hourly WHERE provider = $1`, provider)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE provider = $1`, provider)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly WHERE provider = $1`, provider)
+ })
+
+ var usageID string
+ if err := conn.QueryRow(ctx, `
+INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)
+VALUES ($1, $2, 'task-usage-delete', 10, 5)
+RETURNING id
+`, taskID, provider).Scan(&usageID); err != nil {
+ t.Fatalf("create ordinary task usage: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `DELETE FROM task_usage WHERE id = $1`, usageID); err != nil {
+ t.Fatalf("delete ordinary task usage: %v", err)
+ }
+
+ var dirtyCount int
+ if err := conn.QueryRow(ctx, `
+SELECT COUNT(*)
+FROM task_usage_hourly_dirty
+WHERE provider = $1 AND model = 'task-usage-delete'
+`, provider).Scan(&dirtyCount); err != nil {
+ t.Fatalf("count task-usage delete dirty keys: %v", err)
+ }
+ if dirtyCount != 1 {
+ t.Fatalf("ordinary task_usage DELETE dirty keys = %d, want 1", dirtyCount)
+ }
+
+ if _, err := conn.Exec(ctx, `
+INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)
+VALUES ($1, $2, 'issue-delete', 10, 5)
+`, taskID, provider); err != nil {
+ t.Fatalf("create ordinary issue-delete usage: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID); err != nil {
+ t.Fatalf("delete ordinary issue: %v", err)
+ }
+ if err := conn.QueryRow(ctx, `
+SELECT COUNT(*)
+FROM task_usage_hourly_dirty
+WHERE provider = $1 AND model = 'issue-delete'
+`, provider).Scan(&dirtyCount); err != nil {
+ t.Fatalf("count issue delete dirty keys: %v", err)
+ }
+ if dirtyCount != 1 {
+ t.Fatalf("ordinary issue DELETE dirty keys = %d, want 1", dirtyCount)
+ }
+}
+
+func TestDeleteWorkspace_PreservesOtherWorkspaceData(t *testing.T) {
+ ctx := context.Background()
+ const targetSlug = "handler-tests-delete-tenant-target"
+ const neighborSlug = "handler-tests-delete-tenant-neighbor"
+ const targetMediaKey = "workspace-delete-tenant-target-media"
+ const neighborMediaKey = "workspace-delete-tenant-neighbor-media"
+
+ _, _ = testPool.Exec(ctx, `DELETE FROM channel_media_pending_object WHERE storage_key IN ($1, $2)`, targetMediaKey, neighborMediaKey)
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug IN ($1, $2)`, targetSlug, neighborSlug)
+
+ var targetWorkspaceID, neighborWorkspaceID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO workspace (name, slug)
+VALUES ('Workspace delete tenant target', $1)
+RETURNING id
+`, targetSlug).Scan(&targetWorkspaceID); err != nil {
+ t.Fatalf("create target workspace: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO workspace (name, slug)
+VALUES ('Workspace delete tenant neighbor', $1)
+RETURNING id
+`, neighborSlug).Scan(&neighborWorkspaceID); err != nil {
+ t.Fatalf("create neighbor workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ for _, workspaceID := range []string{targetWorkspaceID, neighborWorkspaceID} {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1`, workspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE workspace_id = $1`, workspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_media_pending_object WHERE workspace_id = $1`, workspaceID)
+ }
+ })
+
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO member (workspace_id, user_id, role)
+VALUES ($1, $2, 'owner')
+`, targetWorkspaceID, testUserID); err != nil {
+ t.Fatalf("create target owner: %v", err)
+ }
+
+ type tenantFixture struct {
+ workspaceID string
+ mediaKey string
+ issueID string
+ }
+ fixtures := []*tenantFixture{
+ {workspaceID: targetWorkspaceID, mediaKey: targetMediaKey},
+ {workspaceID: neighborWorkspaceID, mediaKey: neighborMediaKey},
+ }
+ for _, fixture := range fixtures {
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO issue (workspace_id, title, creator_type, creator_id)
+VALUES ($1, 'Workspace delete tenant isolation', 'member', $2)
+RETURNING id
+`, fixture.workspaceID, testUserID).Scan(&fixture.issueID); err != nil {
+ t.Fatalf("create issue for workspace %s: %v", fixture.workspaceID, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+VALUES ($1, $2, 'member', $3, 'Workspace delete tenant isolation')
+`, fixture.issueID, fixture.workspaceID, testUserID); err != nil {
+ t.Fatalf("create comment for workspace %s: %v", fixture.workspaceID, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO inbox_item (
+ workspace_id, recipient_type, recipient_id, type, issue_id, title
+)
+VALUES ($1, 'member', $2, 'workspace-delete-test', $3, 'Workspace delete tenant isolation')
+`, fixture.workspaceID, testUserID, fixture.issueID); err != nil {
+ t.Fatalf("create inbox item for workspace %s: %v", fixture.workspaceID, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO runtime_profile (
+ workspace_id, display_name, protocol_family, command_name, created_by
+)
+VALUES ($1, 'Workspace delete tenant isolation', 'codex', 'codex', $2)
+`, fixture.workspaceID, testUserID); err != nil {
+ t.Fatalf("create runtime profile for workspace %s: %v", fixture.workspaceID, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id, provider, model
+)
+VALUES (date_trunc('hour', now()), $1, gen_random_uuid(), gen_random_uuid(), 'workspace-delete-tenant', 'isolation')
+`, fixture.workspaceID); err != nil {
+ t.Fatalf("create dirty usage for workspace %s: %v", fixture.workspaceID, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO channel_media_pending_object (
+ storage_key, workspace_id, chat_message_id, storage_url
+)
+VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/tenant-isolation')
+`, fixture.mediaKey, fixture.workspaceID); err != nil {
+ t.Fatalf("create media ledger for workspace %s: %v", fixture.workspaceID, err)
+ }
+ }
+
+ recorder := httptest.NewRecorder()
+ request := newRequest(http.MethodDelete, "/api/workspaces/"+targetWorkspaceID, nil)
+ request = withURLParam(request, "id", targetWorkspaceID)
+ testHandler.DeleteWorkspace(recorder, request)
+ if recorder.Code != http.StatusNoContent {
+ t.Fatalf("DeleteWorkspace returned %d: %s", recorder.Code, recorder.Body.String())
+ }
+
+ for table, predicate := range map[string]string{
+ "workspace": "id",
+ "issue": "workspace_id",
+ "comment": "workspace_id",
+ "inbox_item": "workspace_id",
+ "runtime_profile": "workspace_id",
+ "task_usage_hourly_dirty": "workspace_id",
+ "channel_media_pending_object": "workspace_id",
+ } {
+ var count int
+ if err := testPool.QueryRow(ctx, `
+SELECT COUNT(*) FROM `+table+` WHERE `+predicate+` = $1
+`, neighborWorkspaceID).Scan(&count); err != nil {
+ t.Fatalf("count neighbor %s rows: %v", table, err)
+ }
+ if count != 1 {
+ t.Fatalf("neighbor %s rows = %d, want 1", table, count)
+ }
+ }
+
+ var neighborMediaState string
+ if err := testPool.QueryRow(ctx, `
+SELECT state
+FROM channel_media_pending_object
+WHERE storage_key = $1
+`, neighborMediaKey).Scan(&neighborMediaState); err != nil {
+ t.Fatalf("read neighbor media state: %v", err)
+ }
+ if neighborMediaState != "pending" {
+ t.Fatalf("neighbor media state = %q, want pending", neighborMediaState)
+ }
}
// TestUpdateWorkspace_AvatarURL covers the avatar_url field added to
diff --git a/server/migrations/242_workspace_teardown_dirty_trigger_guard.down.sql b/server/migrations/242_workspace_teardown_dirty_trigger_guard.down.sql
new file mode 100644
index 0000000000..a0e927312f
--- /dev/null
+++ b/server/migrations/242_workspace_teardown_dirty_trigger_guard.down.sql
@@ -0,0 +1,17 @@
+DROP TRIGGER IF EXISTS trg_tu_dirty_hourly ON task_usage;
+CREATE TRIGGER trg_tu_dirty_hourly
+BEFORE DELETE ON task_usage
+FOR EACH ROW
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_tu();
+
+DROP TRIGGER IF EXISTS trg_issue_delete_dirty_hourly ON issue;
+CREATE TRIGGER trg_issue_delete_dirty_hourly
+BEFORE DELETE ON issue
+FOR EACH ROW
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete();
+
+DROP TRIGGER IF EXISTS trg_atq_dirty_hourly ON agent_task_queue;
+CREATE TRIGGER trg_atq_dirty_hourly
+BEFORE UPDATE OF runtime_id, issue_id OR DELETE ON agent_task_queue
+FOR EACH ROW
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_atq();
diff --git a/server/migrations/242_workspace_teardown_dirty_trigger_guard.up.sql b/server/migrations/242_workspace_teardown_dirty_trigger_guard.up.sql
new file mode 100644
index 0000000000..48eaea3686
--- /dev/null
+++ b/server/migrations/242_workspace_teardown_dirty_trigger_guard.up.sql
@@ -0,0 +1,25 @@
+-- Workspace teardown removes the raw and rolled-up usage for the entire
+-- workspace, so per-row dirty-key maintenance is pure overhead in that one
+-- transaction. Keep normal deletes unchanged while allowing the application
+-- deletion plan to opt out with a transaction-local setting.
+
+DROP TRIGGER IF EXISTS trg_atq_dirty_hourly ON agent_task_queue;
+CREATE TRIGGER trg_atq_dirty_hourly
+BEFORE UPDATE OF runtime_id, issue_id OR DELETE ON agent_task_queue
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_atq();
+
+DROP TRIGGER IF EXISTS trg_issue_delete_dirty_hourly ON issue;
+CREATE TRIGGER trg_issue_delete_dirty_hourly
+BEFORE DELETE ON issue
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete();
+
+DROP TRIGGER IF EXISTS trg_tu_dirty_hourly ON task_usage;
+CREATE TRIGGER trg_tu_dirty_hourly
+BEFORE DELETE ON task_usage
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_tu();
diff --git a/server/migrations/243_issue_dependency_issue_index.down.sql b/server/migrations/243_issue_dependency_issue_index.down.sql
new file mode 100644
index 0000000000..0fb8af8e56
--- /dev/null
+++ b/server/migrations/243_issue_dependency_issue_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_dependency_issue_id;
diff --git a/server/migrations/243_issue_dependency_issue_index.up.sql b/server/migrations/243_issue_dependency_issue_index.up.sql
new file mode 100644
index 0000000000..80595d3bda
--- /dev/null
+++ b/server/migrations/243_issue_dependency_issue_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_dependency_issue_id
+ ON issue_dependency(issue_id);
diff --git a/server/migrations/244_issue_dependency_depends_on_index.down.sql b/server/migrations/244_issue_dependency_depends_on_index.down.sql
new file mode 100644
index 0000000000..7ead784df7
--- /dev/null
+++ b/server/migrations/244_issue_dependency_depends_on_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_dependency_depends_on_issue_id;
diff --git a/server/migrations/244_issue_dependency_depends_on_index.up.sql b/server/migrations/244_issue_dependency_depends_on_index.up.sql
new file mode 100644
index 0000000000..17ba8e6ed3
--- /dev/null
+++ b/server/migrations/244_issue_dependency_depends_on_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_dependency_depends_on_issue_id
+ ON issue_dependency(depends_on_issue_id);
diff --git a/server/migrations/245_inbox_item_issue_index.down.sql b/server/migrations/245_inbox_item_issue_index.down.sql
new file mode 100644
index 0000000000..c6c4d94014
--- /dev/null
+++ b/server/migrations/245_inbox_item_issue_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_inbox_item_issue_id;
diff --git a/server/migrations/245_inbox_item_issue_index.up.sql b/server/migrations/245_inbox_item_issue_index.up.sql
new file mode 100644
index 0000000000..d816a5f13f
--- /dev/null
+++ b/server/migrations/245_inbox_item_issue_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inbox_item_issue_id
+ ON inbox_item(issue_id);
diff --git a/server/migrations/246_comment_parent_index.down.sql b/server/migrations/246_comment_parent_index.down.sql
new file mode 100644
index 0000000000..e193f96a34
--- /dev/null
+++ b/server/migrations/246_comment_parent_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_parent_id;
diff --git a/server/migrations/246_comment_parent_index.up.sql b/server/migrations/246_comment_parent_index.up.sql
new file mode 100644
index 0000000000..59a2074a98
--- /dev/null
+++ b/server/migrations/246_comment_parent_index.up.sql
@@ -0,0 +1,3 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_parent_id
+ ON comment(parent_id)
+ WHERE parent_id IS NOT NULL;
diff --git a/server/migrations/247_agent_task_trigger_comment_index.down.sql b/server/migrations/247_agent_task_trigger_comment_index.down.sql
new file mode 100644
index 0000000000..23393869f8
--- /dev/null
+++ b/server/migrations/247_agent_task_trigger_comment_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_trigger_comment_id;
diff --git a/server/migrations/247_agent_task_trigger_comment_index.up.sql b/server/migrations/247_agent_task_trigger_comment_index.up.sql
new file mode 100644
index 0000000000..ba51b53a80
--- /dev/null
+++ b/server/migrations/247_agent_task_trigger_comment_index.up.sql
@@ -0,0 +1,3 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_trigger_comment_id
+ ON agent_task_queue(trigger_comment_id)
+ WHERE trigger_comment_id IS NOT NULL;
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
new file mode 100644
index 0000000000..4f4095036b
--- /dev/null
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -0,0 +1,539 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: workspace_delete.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const deleteWorkspaceAdministration = `-- name: DeleteWorkspaceAdministration :exec
+WITH
+deleted_members AS (
+ DELETE FROM member WHERE member.workspace_id = $1
+),
+deleted_notification_preferences AS (
+ DELETE FROM notification_preference
+ WHERE notification_preference.workspace_id = $1
+),
+deleted_pins AS (
+ DELETE FROM pinned_item WHERE pinned_item.workspace_id = $1
+),
+deleted_daemon_tokens AS (
+ DELETE FROM daemon_token WHERE daemon_token.workspace_id = $1
+),
+detached_feedback AS (
+ UPDATE feedback
+ SET workspace_id = NULL
+ WHERE feedback.workspace_id = $1
+),
+detached_client_usage AS (
+ UPDATE client_usage_daily
+ SET workspace_id = NULL
+ WHERE client_usage_daily.workspace_id = $1
+)
+DELETE FROM workspace_invitation
+WHERE workspace_invitation.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAdministration(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAdministration, workspaceID)
+ return err
+}
+
+const deleteWorkspaceAgents = `-- name: DeleteWorkspaceAgents :exec
+DELETE FROM agent WHERE agent.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAgents(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAgents, workspaceID)
+ return err
+}
+
+const deleteWorkspaceAutopilotChildren = `-- name: DeleteWorkspaceAutopilotChildren :exec
+WITH
+deleted_triggers AS (
+ DELETE FROM autopilot_trigger
+ WHERE autopilot_id IN (
+ SELECT id FROM autopilot WHERE autopilot.workspace_id = $1
+ )
+)
+DELETE FROM autopilot_rule_version
+WHERE autopilot_rule_version.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAutopilotChildren(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAutopilotChildren, workspaceID)
+ return err
+}
+
+const deleteWorkspaceAutopilotRuns = `-- name: DeleteWorkspaceAutopilotRuns :exec
+DELETE FROM autopilot_run
+WHERE autopilot_id IN (
+ SELECT id FROM autopilot WHERE autopilot.workspace_id = $1
+)
+`
+
+func (q *Queries) DeleteWorkspaceAutopilotRuns(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAutopilotRuns, workspaceID)
+ return err
+}
+
+const deleteWorkspaceAutopilots = `-- name: DeleteWorkspaceAutopilots :exec
+DELETE FROM autopilot WHERE autopilot.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAutopilots(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAutopilots, workspaceID)
+ return err
+}
+
+const deleteWorkspaceChatMessages = `-- name: DeleteWorkspaceChatMessages :exec
+DELETE FROM chat_message
+WHERE chat_session_id IN (
+ SELECT id FROM chat_session WHERE chat_session.workspace_id = $1
+)
+`
+
+func (q *Queries) DeleteWorkspaceChatMessages(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceChatMessages, workspaceID)
+ return err
+}
+
+const deleteWorkspaceComments = `-- name: DeleteWorkspaceComments :exec
+DELETE FROM comment WHERE comment.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceComments(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceComments, workspaceID)
+ return err
+}
+
+const deleteWorkspaceCommunicationRoots = `-- name: DeleteWorkspaceCommunicationRoots :exec
+WITH
+deleted_sessions AS (
+ DELETE FROM chat_session WHERE chat_session.workspace_id = $1
+),
+deleted_channel_installations AS (
+ DELETE FROM channel_installation
+ WHERE channel_installation.workspace_id = $1
+)
+DELETE FROM lark_installation WHERE lark_installation.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceCommunicationRoots(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceCommunicationRoots, workspaceID)
+ return err
+}
+
+const deleteWorkspaceConnections = `-- name: DeleteWorkspaceConnections :exec
+WITH deleted_github_installations AS (
+ DELETE FROM github_installation
+ WHERE github_installation.workspace_id = $1
+)
+DELETE FROM vcs_connection WHERE vcs_connection.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceConnections(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceConnections, workspaceID)
+ return err
+}
+
+const deleteWorkspaceIssueRoots = `-- name: DeleteWorkspaceIssueRoots :exec
+WITH
+deleted_issues AS (
+ DELETE FROM issue WHERE issue.workspace_id = $1
+),
+deleted_labels AS (
+ DELETE FROM issue_label WHERE issue_label.workspace_id = $1
+),
+deleted_properties AS (
+ DELETE FROM issue_property WHERE issue_property.workspace_id = $1
+)
+DELETE FROM quick_action WHERE quick_action.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceIssueRoots(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceIssueRoots, workspaceID)
+ return err
+}
+
+const deleteWorkspaceLeafData = `-- name: DeleteWorkspaceLeafData :exec
+WITH
+ws_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
+),
+ws_labels AS MATERIALIZED (
+ SELECT id FROM issue_label WHERE workspace_id = $1
+),
+ws_skills AS MATERIALIZED (
+ SELECT id FROM skill WHERE workspace_id = $1
+),
+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
+),
+ws_autopilots AS MATERIALIZED (
+ SELECT id FROM autopilot WHERE workspace_id = $1
+),
+ws_github_prs AS MATERIALIZED (
+ SELECT id FROM github_pull_request WHERE workspace_id = $1
+),
+ws_vcs_prs AS MATERIALIZED (
+ SELECT id FROM vcs_pull_request WHERE workspace_id = $1
+),
+ws_vcs_connections AS MATERIALIZED (
+ SELECT id FROM vcs_connection WHERE workspace_id = $1
+),
+ws_channel_installations AS MATERIALIZED (
+ SELECT id FROM channel_installation WHERE workspace_id = $1
+),
+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_token
+ WHERE 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
+),
+deleted_hourly AS (
+ DELETE FROM task_usage_hourly WHERE workspace_id = $1
+),
+deleted_attachments AS (
+ DELETE FROM attachment WHERE workspace_id = $1
+),
+deleted_channel_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE 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_message
+ WHERE 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_restore
+ WHERE chat_session_id IN (SELECT id FROM ws_sessions)
+ OR task_id IN (SELECT id FROM ws_tasks)
+),
+deleted_comment_reactions AS (
+ DELETE FROM comment_reaction WHERE workspace_id = $1
+),
+deleted_issue_reactions AS (
+ DELETE FROM issue_reaction WHERE workspace_id = $1
+),
+deleted_activity AS (
+ DELETE FROM activity_log WHERE workspace_id = $1
+),
+deleted_inbox AS (
+ DELETE FROM inbox_item WHERE workspace_id = $1
+),
+deleted_issue_dependencies AS (
+ DELETE FROM issue_dependency
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR depends_on_issue_id IN (SELECT id FROM ws_issues)
+),
+deleted_issue_subscribers AS (
+ DELETE FROM issue_subscriber
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+),
+deleted_issue_labels AS (
+ DELETE FROM issue_to_label
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_agent_labels AS (
+ DELETE FROM agent_to_label
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_skill_labels AS (
+ DELETE FROM skill_to_label
+ WHERE skill_id IN (SELECT id FROM ws_skills)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_issue_github_links AS (
+ DELETE FROM issue_pull_request
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR pull_request_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_issue_vcs_links AS (
+ DELETE FROM issue_vcs_pull_request
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR pull_request_id IN (SELECT id FROM ws_vcs_prs)
+),
+deleted_agent_invocation_targets AS (
+ DELETE FROM agent_invocation_target
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+),
+deleted_agent_skills AS (
+ DELETE FROM agent_skill
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+ OR skill_id IN (SELECT id FROM ws_skills)
+),
+deleted_skill_files AS (
+ DELETE FROM skill_file
+ WHERE skill_id IN (SELECT id FROM ws_skills)
+),
+deleted_daemon_connections AS (
+ DELETE FROM daemon_connection
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+),
+deleted_squad_members AS (
+ DELETE FROM squad_member
+ WHERE squad_id IN (SELECT id FROM ws_squads)
+),
+deleted_project_resources AS (
+ DELETE FROM project_resource WHERE workspace_id = $1
+),
+deleted_autopilot_collaborators AS (
+ DELETE FROM autopilot_collaborator
+ WHERE autopilot_id IN (SELECT id FROM ws_autopilots)
+),
+deleted_autopilot_subscribers AS (
+ DELETE FROM autopilot_subscriber
+ WHERE autopilot_id IN (SELECT id FROM ws_autopilots)
+),
+deleted_webhook_deliveries AS (
+ DELETE FROM webhook_delivery WHERE workspace_id = $1
+),
+deleted_github_check_runs AS (
+ DELETE FROM github_pull_request_check_run
+ WHERE pr_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_github_check_suites AS (
+ DELETE FROM github_pull_request_check_suite
+ WHERE pr_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_pending_github_suites AS (
+ DELETE FROM github_pending_check_suite WHERE workspace_id = $1
+),
+deleted_vcs_commit_statuses AS (
+ DELETE FROM vcs_commit_status
+ WHERE connection_id IN (SELECT id FROM ws_vcs_connections)
+),
+deleted_channel_chat_bindings AS (
+ DELETE FROM channel_chat_session_binding
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
+deleted_channel_inbound_dedup AS (
+ DELETE FROM channel_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_inbound_audit AS (
+ DELETE FROM channel_inbound_audit
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_user_bindings AS (
+ DELETE FROM channel_user_binding WHERE workspace_id = $1
+),
+deleted_channel_binding_tokens AS (
+ DELETE FROM channel_binding_token WHERE workspace_id = $1
+),
+deleted_lark_chat_bindings AS (
+ DELETE FROM lark_chat_session_binding
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
+deleted_lark_inbound_dedup AS (
+ DELETE FROM lark_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+),
+deleted_lark_inbound_audit AS (
+ DELETE FROM lark_inbound_audit
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+),
+deleted_lark_user_bindings AS (
+ DELETE FROM lark_user_binding WHERE workspace_id = $1
+),
+deleted_lark_binding_tokens AS (
+ DELETE FROM lark_binding_token WHERE workspace_id = $1
+)
+UPDATE channel_media_pending_object
+SET state = CASE
+ WHEN state = 'tombstoned' THEN 'tombstoned'
+ ELSE 'deleting'
+ END,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now(),
+ last_error = NULL
+WHERE channel_media_pending_object.workspace_id = $1
+`
+
+// Keep the two-system cleanup ledger until object storage has been settled.
+// Moving every row out of pending also prevents a concurrent media bind from
+// attaching an object after the workspace teardown commits. The reconciler
+// performs the idempotent object delete and clears the row afterwards.
+func (q *Queries) DeleteWorkspaceLeafData(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceLeafData, workspaceID)
+ return err
+}
+
+const deleteWorkspacePullRequests = `-- name: DeleteWorkspacePullRequests :exec
+WITH deleted_github_prs AS (
+ DELETE FROM github_pull_request
+ WHERE github_pull_request.workspace_id = $1
+)
+DELETE FROM vcs_pull_request WHERE vcs_pull_request.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspacePullRequests(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspacePullRequests, workspaceID)
+ return err
+}
+
+const deleteWorkspaceRuntimesAndProjects = `-- name: DeleteWorkspaceRuntimesAndProjects :exec
+WITH
+deleted_runtimes AS (
+ DELETE FROM agent_runtime WHERE agent_runtime.workspace_id = $1
+),
+deleted_profiles AS (
+ DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1
+)
+DELETE FROM project WHERE project.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceRuntimesAndProjects(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceRuntimesAndProjects, workspaceID)
+ return err
+}
+
+const deleteWorkspaceSquadsAndSkills = `-- name: DeleteWorkspaceSquadsAndSkills :exec
+WITH deleted_squads AS (
+ DELETE FROM squad WHERE squad.workspace_id = $1
+)
+DELETE FROM skill WHERE skill.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceSquadsAndSkills(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceSquadsAndSkills, workspaceID)
+ return 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)
+`
+
+func (q *Queries) DeleteWorkspaceTasks(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceTasks, workspaceID)
+ return err
+}
+
+const lockTaskUsageRollupForWorkspaceDelete = `-- name: LockTaskUsageRollupForWorkspaceDelete :exec
+SELECT pg_advisory_xact_lock(4246)
+`
+
+// The hourly rollup uses session advisory lock 4246. The transaction-scoped
+// lock shares that namespace: an in-flight rollup finishes first, then no new
+// rollup can write the workspace's aggregates until this delete commits.
+func (q *Queries) LockTaskUsageRollupForWorkspaceDelete(ctx context.Context) error {
+ _, err := q.db.Exec(ctx, lockTaskUsageRollupForWorkspaceDelete)
+ return err
+}
+
+const prepareWorkspaceDeletionLinks = `-- name: PrepareWorkspaceDeletionLinks :exec
+WITH
+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 comment
+ SET parent_id = NULL
+ WHERE comment.workspace_id = $1
+ AND parent_id IS NOT NULL
+),
+detached_issues AS (
+ UPDATE issue
+ SET parent_issue_id = NULL
+ WHERE issue.workspace_id = $1
+ AND parent_issue_id IS NOT NULL
+)
+UPDATE webhook_delivery
+SET replayed_from_delivery_id = NULL
+WHERE webhook_delivery.workspace_id = $1
+ AND replayed_from_delivery_id IS NOT NULL
+`
+
+// 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.
+func (q *Queries) PrepareWorkspaceDeletionLinks(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, prepareWorkspaceDeletionLinks, workspaceID)
+ return err
+}
+
+const setWorkspaceTeardownMode = `-- name: SetWorkspaceTeardownMode :exec
+
+SELECT set_config('multica.workspace_teardown', 'on', true)
+`
+
+// Workspace deletion is application-owned. These statements form a fixed,
+// bottom-up deletion plan; the legacy foreign keys remain only as a
+// compatibility safety net during the expand phase.
+// The setting is transaction-local. Migration 242 makes only the three DELETE
+// dirty triggers skip their per-row work while this flag is on.
+func (q *Queries) SetWorkspaceTeardownMode(ctx context.Context) error {
+ _, err := q.db.Exec(ctx, setWorkspaceTeardownMode)
+ return err
+}
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
new file mode 100644
index 0000000000..20a68808b7
--- /dev/null
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -0,0 +1,418 @@
+-- Workspace deletion is application-owned. These statements form a fixed,
+-- bottom-up deletion plan; the legacy foreign keys remain only as a
+-- compatibility safety net during the expand phase.
+
+-- name: SetWorkspaceTeardownMode :exec
+-- The setting is transaction-local. Migration 242 makes only the three DELETE
+-- dirty triggers skip their per-row work while this flag is on.
+SELECT set_config('multica.workspace_teardown', 'on', true);
+
+-- name: LockTaskUsageRollupForWorkspaceDelete :exec
+-- The hourly rollup uses session advisory lock 4246. The transaction-scoped
+-- lock shares that namespace: an in-flight rollup finishes first, then no new
+-- rollup can write the workspace's aggregates until this delete commits.
+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.
+WITH
+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 comment
+ SET parent_id = NULL
+ WHERE comment.workspace_id = $1
+ AND parent_id IS NOT NULL
+),
+detached_issues AS (
+ UPDATE issue
+ SET parent_issue_id = NULL
+ WHERE issue.workspace_id = $1
+ AND parent_issue_id IS NOT NULL
+)
+UPDATE webhook_delivery
+SET replayed_from_delivery_id = NULL
+WHERE webhook_delivery.workspace_id = $1
+ AND replayed_from_delivery_id IS NOT NULL;
+
+-- name: DeleteWorkspaceLeafData :exec
+WITH
+ws_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
+),
+ws_labels AS MATERIALIZED (
+ SELECT id FROM issue_label WHERE workspace_id = $1
+),
+ws_skills AS MATERIALIZED (
+ SELECT id FROM skill WHERE workspace_id = $1
+),
+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
+),
+ws_autopilots AS MATERIALIZED (
+ SELECT id FROM autopilot WHERE workspace_id = $1
+),
+ws_github_prs AS MATERIALIZED (
+ SELECT id FROM github_pull_request WHERE workspace_id = $1
+),
+ws_vcs_prs AS MATERIALIZED (
+ SELECT id FROM vcs_pull_request WHERE workspace_id = $1
+),
+ws_vcs_connections AS MATERIALIZED (
+ SELECT id FROM vcs_connection WHERE workspace_id = $1
+),
+ws_channel_installations AS MATERIALIZED (
+ SELECT id FROM channel_installation WHERE workspace_id = $1
+),
+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_token
+ WHERE 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
+),
+deleted_hourly AS (
+ DELETE FROM task_usage_hourly WHERE workspace_id = $1
+),
+deleted_attachments AS (
+ DELETE FROM attachment WHERE workspace_id = $1
+),
+deleted_channel_outbound_cards AS (
+ DELETE FROM channel_outbound_card_message
+ WHERE 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_message
+ WHERE 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_restore
+ WHERE chat_session_id IN (SELECT id FROM ws_sessions)
+ OR task_id IN (SELECT id FROM ws_tasks)
+),
+deleted_comment_reactions AS (
+ DELETE FROM comment_reaction WHERE workspace_id = $1
+),
+deleted_issue_reactions AS (
+ DELETE FROM issue_reaction WHERE workspace_id = $1
+),
+deleted_activity AS (
+ DELETE FROM activity_log WHERE workspace_id = $1
+),
+deleted_inbox AS (
+ DELETE FROM inbox_item WHERE workspace_id = $1
+),
+deleted_issue_dependencies AS (
+ DELETE FROM issue_dependency
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR depends_on_issue_id IN (SELECT id FROM ws_issues)
+),
+deleted_issue_subscribers AS (
+ DELETE FROM issue_subscriber
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+),
+deleted_issue_labels AS (
+ DELETE FROM issue_to_label
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_agent_labels AS (
+ DELETE FROM agent_to_label
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_skill_labels AS (
+ DELETE FROM skill_to_label
+ WHERE skill_id IN (SELECT id FROM ws_skills)
+ OR label_id IN (SELECT id FROM ws_labels)
+),
+deleted_issue_github_links AS (
+ DELETE FROM issue_pull_request
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR pull_request_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_issue_vcs_links AS (
+ DELETE FROM issue_vcs_pull_request
+ WHERE issue_id IN (SELECT id FROM ws_issues)
+ OR pull_request_id IN (SELECT id FROM ws_vcs_prs)
+),
+deleted_agent_invocation_targets AS (
+ DELETE FROM agent_invocation_target
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+),
+deleted_agent_skills AS (
+ DELETE FROM agent_skill
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+ OR skill_id IN (SELECT id FROM ws_skills)
+),
+deleted_skill_files AS (
+ DELETE FROM skill_file
+ WHERE skill_id IN (SELECT id FROM ws_skills)
+),
+deleted_daemon_connections AS (
+ DELETE FROM daemon_connection
+ WHERE agent_id IN (SELECT id FROM ws_agents)
+),
+deleted_squad_members AS (
+ DELETE FROM squad_member
+ WHERE squad_id IN (SELECT id FROM ws_squads)
+),
+deleted_project_resources AS (
+ DELETE FROM project_resource WHERE workspace_id = $1
+),
+deleted_autopilot_collaborators AS (
+ DELETE FROM autopilot_collaborator
+ WHERE autopilot_id IN (SELECT id FROM ws_autopilots)
+),
+deleted_autopilot_subscribers AS (
+ DELETE FROM autopilot_subscriber
+ WHERE autopilot_id IN (SELECT id FROM ws_autopilots)
+),
+deleted_webhook_deliveries AS (
+ DELETE FROM webhook_delivery WHERE workspace_id = $1
+),
+deleted_github_check_runs AS (
+ DELETE FROM github_pull_request_check_run
+ WHERE pr_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_github_check_suites AS (
+ DELETE FROM github_pull_request_check_suite
+ WHERE pr_id IN (SELECT id FROM ws_github_prs)
+),
+deleted_pending_github_suites AS (
+ DELETE FROM github_pending_check_suite WHERE workspace_id = $1
+),
+deleted_vcs_commit_statuses AS (
+ DELETE FROM vcs_commit_status
+ WHERE connection_id IN (SELECT id FROM ws_vcs_connections)
+),
+deleted_channel_chat_bindings AS (
+ DELETE FROM channel_chat_session_binding
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
+deleted_channel_inbound_dedup AS (
+ DELETE FROM channel_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_inbound_audit AS (
+ DELETE FROM channel_inbound_audit
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_user_bindings AS (
+ DELETE FROM channel_user_binding WHERE workspace_id = $1
+),
+deleted_channel_binding_tokens AS (
+ DELETE FROM channel_binding_token WHERE workspace_id = $1
+),
+deleted_lark_chat_bindings AS (
+ DELETE FROM lark_chat_session_binding
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
+deleted_lark_inbound_dedup AS (
+ DELETE FROM lark_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+),
+deleted_lark_inbound_audit AS (
+ DELETE FROM lark_inbound_audit
+ WHERE installation_id IN (SELECT id FROM ws_lark_installations)
+),
+deleted_lark_user_bindings AS (
+ DELETE FROM lark_user_binding WHERE workspace_id = $1
+),
+deleted_lark_binding_tokens AS (
+ DELETE FROM lark_binding_token WHERE workspace_id = $1
+)
+-- Keep the two-system cleanup ledger until object storage has been settled.
+-- Moving every row out of pending also prevents a concurrent media bind from
+-- attaching an object after the workspace teardown commits. The reconciler
+-- performs the idempotent object delete and clears the row afterwards.
+UPDATE channel_media_pending_object
+SET state = CASE
+ WHEN state = 'tombstoned' THEN 'tombstoned'
+ ELSE 'deleting'
+ END,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now(),
+ last_error = NULL
+WHERE 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 :exec
+DELETE FROM chat_message
+WHERE chat_session_id IN (
+ SELECT id FROM chat_session WHERE chat_session.workspace_id = $1
+);
+
+-- name: DeleteWorkspaceCommunicationRoots :exec
+WITH
+deleted_sessions AS (
+ DELETE FROM chat_session WHERE chat_session.workspace_id = $1
+),
+deleted_channel_installations AS (
+ DELETE FROM channel_installation
+ WHERE channel_installation.workspace_id = $1
+)
+DELETE FROM lark_installation WHERE lark_installation.workspace_id = $1;
+
+-- name: DeleteWorkspaceComments :exec
+DELETE FROM comment WHERE comment.workspace_id = $1;
+
+-- name: DeleteWorkspaceIssueRoots :exec
+WITH
+deleted_issues AS (
+ DELETE FROM issue WHERE issue.workspace_id = $1
+),
+deleted_labels AS (
+ DELETE FROM issue_label WHERE issue_label.workspace_id = $1
+),
+deleted_properties AS (
+ DELETE FROM issue_property WHERE issue_property.workspace_id = $1
+)
+DELETE FROM quick_action WHERE quick_action.workspace_id = $1;
+
+-- name: DeleteWorkspaceAutopilotRuns :exec
+DELETE FROM autopilot_run
+WHERE autopilot_id IN (
+ SELECT id FROM autopilot WHERE autopilot.workspace_id = $1
+);
+
+-- name: DeleteWorkspaceAutopilotChildren :exec
+WITH
+deleted_triggers AS (
+ DELETE FROM autopilot_trigger
+ WHERE autopilot_id IN (
+ SELECT id FROM autopilot WHERE autopilot.workspace_id = $1
+ )
+)
+DELETE FROM autopilot_rule_version
+WHERE autopilot_rule_version.workspace_id = $1;
+
+-- name: DeleteWorkspaceAutopilots :exec
+DELETE FROM autopilot WHERE autopilot.workspace_id = $1;
+
+-- name: DeleteWorkspacePullRequests :exec
+WITH deleted_github_prs AS (
+ DELETE FROM github_pull_request
+ WHERE github_pull_request.workspace_id = $1
+)
+DELETE FROM vcs_pull_request WHERE vcs_pull_request.workspace_id = $1;
+
+-- name: DeleteWorkspaceConnections :exec
+WITH deleted_github_installations AS (
+ DELETE FROM github_installation
+ WHERE github_installation.workspace_id = $1
+)
+DELETE FROM vcs_connection WHERE vcs_connection.workspace_id = $1;
+
+-- name: DeleteWorkspaceSquadsAndSkills :exec
+WITH deleted_squads AS (
+ DELETE FROM squad WHERE squad.workspace_id = $1
+)
+DELETE FROM skill WHERE skill.workspace_id = $1;
+
+-- name: DeleteWorkspaceAgents :exec
+DELETE FROM agent WHERE agent.workspace_id = $1;
+
+-- name: DeleteWorkspaceRuntimesAndProjects :exec
+WITH
+deleted_runtimes AS (
+ DELETE FROM agent_runtime WHERE agent_runtime.workspace_id = $1
+),
+deleted_profiles AS (
+ DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1
+)
+DELETE FROM project WHERE project.workspace_id = $1;
+
+-- name: DeleteWorkspaceAdministration :exec
+WITH
+deleted_members AS (
+ DELETE FROM member WHERE member.workspace_id = $1
+),
+deleted_notification_preferences AS (
+ DELETE FROM notification_preference
+ WHERE notification_preference.workspace_id = $1
+),
+deleted_pins AS (
+ DELETE FROM pinned_item WHERE pinned_item.workspace_id = $1
+),
+deleted_daemon_tokens AS (
+ DELETE FROM daemon_token WHERE daemon_token.workspace_id = $1
+),
+detached_feedback AS (
+ UPDATE feedback
+ SET workspace_id = NULL
+ WHERE feedback.workspace_id = $1
+),
+detached_client_usage AS (
+ UPDATE client_usage_daily
+ SET workspace_id = NULL
+ WHERE client_usage_daily.workspace_id = $1
+)
+DELETE FROM workspace_invitation
+WHERE workspace_invitation.workspace_id = $1;