Skip to content

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

Go

fix(migrate): cover every concurrent index build with retry cleanup (MUL-6288) (#7073)

Bohan Jiang1e1321a9c331
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index ba3c5a112d..6af5c911c7 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -74,9 +74,84 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error
// 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.
+//
+// MUL-6288: registration used to be opt-in per batch, so 316 / 317 / 326 / 328 /
+// 330 / 331 shipped without a hook and the hazard came back. The map is now
+// total — every up migration that builds an index concurrently is listed, the
+// same invariant `concurrentDownIndexCleanups` already holds for rollbacks — and
+// TestEveryConcurrentUpBuildHasCleanup fails the build if a new migration is
+// added without its entry. Registering the already-applied historical
+// migrations costs one to_regclass lookup each, and only on a database where
+// they are still pending: a fresh self-hosted install, which is exactly where an
+// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "035_task_queue_issue_id_index": "idx_agent_task_queue_issue_id",
+ "067_task_queue_claim_candidate_index": "idx_agent_task_queue_claim_candidates",
+ "074_task_usage_updated_at_index": "idx_task_usage_updated_at",
+ "075_task_usage_created_at_index": "idx_task_usage_created_at",
+ "078_task_usage_created_at_legacy_index": "idx_task_usage_created_at_legacy",
+ "080_agent_task_queue_queued_index": "idx_agent_task_queue_queued_created_at",
+ "106_member_user_workspace_index": "idx_member_user_workspace",
+ "114_agent_task_queue_running_started_at_index": "idx_agent_task_queue_running_started_at",
+ "115_agent_runtime_last_seen_at_index": "idx_agent_runtime_last_seen_at",
+ "119_user_created_at_index": "idx_user_created_at",
+ "125_agent_task_queue_dispatched_prepare_index": "idx_agent_task_queue_dispatched_prepare",
+ "135_comment_workspace_index": "idx_comment_workspace",
+ "138_issue_title_trgm_index": "idx_issue_title_trgm",
+ "139_issue_description_trgm_index": "idx_issue_description_trgm",
+ "140_comment_content_trgm_index": "idx_comment_content_trgm",
+ "141_project_title_trgm_index": "idx_project_title_trgm",
+ "142_project_description_trgm_index": "idx_project_description_trgm",
+ "143_agent_task_queue_chat_pending_v2": "idx_agent_task_queue_chat_pending_v2",
+ "153_chat_pinned_agent_user_ws_index": "idx_chat_pinned_agent_user_ws",
+ "156_chat_session_pinned_index": "idx_chat_session_pinned",
+ "160_chat_message_input_owner_index": "idx_chat_message_input_owner",
+ "165_attachment_task_id_index": "idx_attachment_task",
+ "167_resource_label_namespace_index": "issue_label_workspace_type_name_lower_idx",
+ "168_resource_label_type_index": "issue_label_workspace_type_idx",
+ "169_agent_label_lookup_index": "agent_to_label_label_idx",
+ "170_skill_label_lookup_index": "skill_to_label_label_idx",
+ "172_agent_system_identity_index": "agent_system_identity_unique",
+ "177_autopilot_run_webhook_delivery_index": "uq_autopilot_run_webhook_delivery",
+ "178_webhook_delivery_queue_index": "idx_webhook_delivery_queue",
+ "181_task_chat_finalize_deferred_index": "idx_task_chat_finalize_deferred",
+ "183_chat_draft_restore_index": "idx_chat_draft_restore_session",
+ "187_autopilot_rule_version_index": "idx_autopilot_rule_version_active",
+ "192_issue_properties_gin_index": "idx_issue_properties_gin",
+ "194_issue_property_workspace_name_index": "idx_issue_property_ws_name",
+ "195_issue_property_workspace_index": "idx_issue_property_workspace",
+ "200_inbox_archived_listing_index": "idx_inbox_recipient_archived_created",
+ "201_inbox_active_by_issue_index": "idx_inbox_active_by_issue",
+ "203_issue_workspace_assignee_index": "idx_issue_workspace_assignee",
+ "204_issue_workspace_parent_index": "idx_issue_workspace_parent",
+ "205_issue_workspace_position_index": "idx_issue_workspace_position",
+ "208_client_usage_daily_unique_index": "client_usage_daily_identity_date_uidx",
+ "210_client_usage_daily_query_index": "client_usage_daily_activity_client_user_idx",
+ "211_client_usage_daily_workspace_index": "client_usage_daily_workspace_idx",
+ "215_chat_session_project_index": "idx_chat_session_project",
+ "217_vcs_connection_workspace_index": "idx_vcs_connection_workspace",
+ "218_vcs_pull_request_workspace_index": "idx_vcs_pull_request_workspace",
+ "219_vcs_pull_request_connection_index": "idx_vcs_pull_request_connection",
+ "220_issue_vcs_pull_request_pr_index": "idx_issue_vcs_pull_request_pr",
+ "221_vcs_commit_status_lookup_index": "idx_vcs_commit_status_lookup",
+ "223_github_pr_check_run_pr_ordinal_index": "github_pull_request_check_run_pr_ordinal_idx",
+ "228_channel_media_pending_object_key_index": "channel_media_pending_object_storage_key_uidx",
+ "230_channel_media_pending_object_claim_index": "idx_channel_media_pending_object_claim",
+ "231_agent_task_queue_terminal_completed_at_index": "idx_agent_task_queue_terminal_completed_at",
+ "232_channel_media_pending_object_due_index": "idx_channel_media_pending_object_due",
+ "233_agent_task_queue_agent_terminal_latest_index": "idx_agent_task_queue_agent_terminal_latest",
+ "238_quick_action_workspace_index": "idx_quick_action_workspace_status_usage",
+ "241_comment_parent_lookup_index": "idx_comment_workspace_issue_parent",
+ "244_issue_dependency_issue_index": "idx_issue_dependency_issue_id",
+ "245_issue_dependency_depends_on_index": "idx_issue_dependency_depends_on_issue_id",
+ "246_inbox_item_issue_index": "idx_inbox_item_issue_id",
+ "247_comment_parent_index": "idx_comment_parent_id",
+ "248_agent_task_trigger_comment_index": "idx_agent_task_queue_trigger_comment_id",
+ "255_agent_task_queue_chat_pending_deferred_v3": "idx_agent_task_queue_chat_pending_v3",
"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",
+ "266_issue_view_owner_index": "idx_issue_view_owner",
+ "267_issue_view_shared_index": "idx_issue_view_shared",
"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",
@@ -103,12 +178,19 @@ var concurrentIndexCleanups = map[string]string{
"305_dingtalk_group_route_installation_conversation_unique": "idx_dingtalk_group_route_installation_conversation",
"306_dingtalk_group_route_workspace_index": "idx_dingtalk_group_route_workspace",
"307_dingtalk_group_route_id_unique": "idx_dingtalk_group_route_id_unique",
+ "309_agent_runtime_id_index": "idx_agent_runtime_id",
"311_plugin_identity_scoped_key_index": "idx_plugin_identity_scoped_key",
+ "316_workspace_mcp_server_name_unique": "idx_workspace_mcp_server_workspace_name",
+ "317_agent_mcp_server_server_index": "idx_agent_mcp_server_server",
"320_plugin_installation_config_revision_index": "idx_plugin_installation_config_contribution_revision",
"321_plugin_installation_config_workspace_index": "idx_plugin_installation_config_workspace",
"322_plugin_remote_mcp_secret_revision_index": "idx_plugin_remote_mcp_secret_revision",
"323_plugin_remote_mcp_secret_workspace_index": "idx_plugin_remote_mcp_secret_workspace",
"324_plugin_remote_mcp_one_active_secret_index": "idx_plugin_remote_mcp_one_active_secret",
+ "326_plugin_remote_mcp_oauth_state_expiry_index": "plugin_remote_mcp_oauth_state_expiry_idx",
+ "328_workspace_share_link_id_uidx": "workspace_share_link_pkey_uidx",
+ "330_workspace_share_link_active_ws_uidx": "workspace_share_link_active_ws_uidx",
+ "331_workspace_share_link_code_uidx": "workspace_share_link_code_uidx",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/migrate/migrate_invalid_index_test.go b/server/cmd/migrate/migrate_invalid_index_test.go
index 1f58ac971e..3f18c7c1f8 100644
--- a/server/cmd/migrate/migrate_invalid_index_test.go
+++ b/server/cmd/migrate/migrate_invalid_index_test.go
@@ -524,6 +524,132 @@ func TestRunMigrationsRepairsInvalidTerminalCompletedAtIndex(t *testing.T) {
}
}
+// TestRunMigrationsRepairsShareLinkIndexesBeforeRetry covers the MUL-6288 batch
+// (migrations 327–331) against the real migration files and the real registered
+// hooks, run inside a private schema so the unqualified index names in
+// production resolve through search_path.
+//
+// Two retry windows matter here, and the share-link chain is where both bite:
+//
+// 1. Interrupted build. 328 backs workspace_share_link's primary key, so an
+// INVALID leftover does not just cost a lookup — 329 cannot attach the
+// constraint at all, and the migrator stops on a half-created table.
+// 2. Build committed, version never recorded. Before this batch got
+// IF NOT EXISTS, the retry failed on "already exists" every single time,
+// which wedges the release rather than degrading it.
+func TestRunMigrationsRepairsShareLinkIndexesBeforeRetry(t *testing.T) {
+ adminPool := 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_share_link_" + suffix
+ schemaIdent := pgx.Identifier{schema}.Sanitize()
+ if _, err := adminPool.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 := adminPool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {
+ t.Logf("drop schema %s: %v", schema, err)
+ }
+ })
+
+ pool := openTestPoolWithSearchPath(t, schema)
+ migrationsTable := pgx.Identifier{schema, "schema_migrations"}.Sanitize()
+ opts := runOptions{
+ Direction: "up",
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ // The production hook map, not a test-local one: this is the
+ // registration the batch was missing.
+ Hooks: hooksForDirection("up"),
+ }
+
+ opts.Files = realMigrationFiles(t, []string{"327_workspace_share_link"}, "up")
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("create share link table: %v", err)
+ }
+
+ // Duplicate ids make the concurrent UNIQUE build fail after Postgres has
+ // registered the relation — the same INVALID leftover an interrupted
+ // production build leaves behind.
+ if _, err := pool.Exec(ctx, `INSERT INTO workspace_share_link (id, workspace_id, code, created_by) VALUES
+ ('00000000-0000-0000-0000-0000000000a1', gen_random_uuid(), 'code-1', gen_random_uuid()),
+ ('00000000-0000-0000-0000-0000000000a1', gen_random_uuid(), 'code-2', gen_random_uuid())`); err != nil {
+ t.Fatalf("seed duplicate share links: %v", err)
+ }
+ if _, err := pool.Exec(ctx, "CREATE UNIQUE INDEX CONCURRENTLY workspace_share_link_pkey_uidx ON workspace_share_link (id)"); err == nil {
+ t.Fatal("failure injection unexpectedly built the primary key index")
+ }
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_pkey_uidx", false)
+ if _, err := pool.Exec(ctx, "DELETE FROM workspace_share_link WHERE ctid = (SELECT max(ctid) FROM workspace_share_link)"); err != nil {
+ t.Fatalf("remove duplicate share link before retry: %v", err)
+ }
+
+ // The hook has to drop the leftover before 328 retries, otherwise 329 has
+ // no usable index to promote.
+ opts.Files = realMigrationFiles(t, []string{
+ "328_workspace_share_link_id_uidx",
+ "329_workspace_share_link_primary_key",
+ }, "up")
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("retry share link primary key with invalid-index cleanup: %v", err)
+ }
+ // ADD CONSTRAINT ... USING INDEX renames the backing index to the
+ // constraint name, so the promoted index is what must be valid now.
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_pkey", true)
+ var hasPrimaryKey bool
+ if err := adminPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1 FROM pg_constraint c
+ JOIN pg_class t ON t.oid = c.conrelid
+ JOIN pg_namespace n ON n.oid = t.relnamespace
+ WHERE n.nspname = $1 AND t.relname = 'workspace_share_link' AND c.contype = 'p'
+ )
+ `, schema).Scan(&hasPrimaryKey); err != nil {
+ t.Fatalf("check share link primary key: %v", err)
+ }
+ if !hasPrimaryKey {
+ t.Fatal("migration 329 did not attach the primary key")
+ }
+
+ // Second window: 330 and 331 build successfully, then the runner dies
+ // before recording them. The next run must be a clean no-op, not a wedge.
+ versions := []string{
+ "330_workspace_share_link_active_ws_uidx",
+ "331_workspace_share_link_code_uidx",
+ }
+ opts.Files = realMigrationFiles(t, versions, "up")
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("apply share link unique indexes: %v", err)
+ }
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_active_ws_uidx", true)
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_code_uidx", true)
+
+ if _, err := adminPool.Exec(ctx, "DELETE FROM "+migrationsTable+" WHERE version = ANY($1)", versions); err != nil {
+ t.Fatalf("simulate missing migration records: %v", err)
+ }
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("retry share link unique indexes with valid indexes present: %v", err)
+ }
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_active_ws_uidx", true)
+ assertIndexReadyAndValid(t, adminPool, schema, "workspace_share_link_code_uidx", true)
+ for _, version := range versions {
+ var recorded bool
+ if err := adminPool.QueryRow(ctx,
+ "SELECT EXISTS (SELECT 1 FROM "+migrationsTable+" WHERE version = $1)",
+ version,
+ ).Scan(&recorded); err != nil {
+ t.Fatalf("read retried migration version: %v", err)
+ }
+ if !recorded {
+ t.Fatalf("%s was not recorded on retry", version)
+ }
+ }
+}
+
func assertIndexValidity(t *testing.T, pool interface {
QueryRow(context.Context, string, ...any) pgx.Row
}, schema, index string, want bool) {
diff --git a/server/cmd/migrate/migrate_mul5999_index_retry_test.go b/server/cmd/migrate/migrate_mul5999_index_retry_test.go
index 98988f7832..eec875a222 100644
--- a/server/cmd/migrate/migrate_mul5999_index_retry_test.go
+++ b/server/cmd/migrate/migrate_mul5999_index_retry_test.go
@@ -71,12 +71,29 @@ func TestConcurrentIndexCleanupsMatchTheirMigrations(t *testing.T) {
// that builds an index concurrently must be registered. This prevents a new or
// historical down migration from silently missing retry cleanup.
func TestEveryConcurrentDownBuildHasCleanup(t *testing.T) {
- paths, err := filepath.Glob(filepath.Join("..", "..", "migrations", "*.down.sql"))
+ assertEveryConcurrentBuildHasCleanup(t, "down", concurrentDownIndexCleanups)
+}
+
+// TestEveryConcurrentUpBuildHasCleanup is the up-direction counterpart, added
+// for MUL-6288. Only the down direction was covered before, so registration for
+// up migrations was effectively opt-in: 316, 317, 326, 328, 330 and 331 all
+// shipped without a hook and nothing failed. An unregistered build is invisible
+// until a real interrupted migration turns into either a permanently INVALID
+// index recorded as success (`IF NOT EXISTS`) or a wedged migrator (bare
+// `CREATE`), so the check belongs here rather than in review.
+func TestEveryConcurrentUpBuildHasCleanup(t *testing.T) {
+ assertEveryConcurrentBuildHasCleanup(t, "up", concurrentIndexCleanups)
+}
+
+func assertEveryConcurrentBuildHasCleanup(t *testing.T, direction string, cleanups map[string]string) {
+ t.Helper()
+ suffix := "." + direction + ".sql"
+ paths, err := filepath.Glob(filepath.Join("..", "..", "migrations", "*"+suffix))
if err != nil {
- t.Fatalf("glob down migrations: %v", err)
+ t.Fatalf("glob %s migrations: %v", direction, err)
}
if len(paths) == 0 {
- t.Fatal("no down migrations found")
+ t.Fatalf("no %s migrations found", direction)
}
for _, path := range paths {
@@ -89,19 +106,19 @@ func TestEveryConcurrentDownBuildHasCleanup(t *testing.T) {
if len(matches) == 0 {
continue
}
- version := strings.TrimSuffix(filepath.Base(path), ".down.sql")
+ version := strings.TrimSuffix(filepath.Base(path), suffix)
if len(matches) != 1 {
t.Errorf("%s: has %d concurrent index builds; cleanup registration supports exactly one", version, len(matches))
continue
}
indexName := string(matches[0][1])
- registered, ok := concurrentDownIndexCleanups[version]
+ registered, ok := cleanups[version]
if !ok {
- t.Errorf("%s: builds %q concurrently on rollback but has no down cleanup", version, indexName)
+ t.Errorf("%s: builds %q concurrently on %s but has no %s cleanup", version, indexName, direction, direction)
continue
}
if registered != indexName {
- t.Errorf("%s: down cleanup registers %q, migration builds %q", version, registered, indexName)
+ t.Errorf("%s: %s cleanup registers %q, migration builds %q", version, direction, registered, indexName)
}
}
}
diff --git a/server/migrations/328_workspace_share_link_id_uidx.up.sql b/server/migrations/328_workspace_share_link_id_uidx.up.sql
index e515bc2009..ae464a2003 100644
--- a/server/migrations/328_workspace_share_link_id_uidx.up.sql
+++ b/server/migrations/328_workspace_share_link_id_uidx.up.sql
@@ -1,5 +1,13 @@
--- Backing index for workspace_share_link's primary key, attached in 316 via
+-- Backing index for workspace_share_link's primary key, attached in 329 via
-- PRIMARY KEY USING INDEX. Own single-statement migration so CONCURRENTLY runs
-- outside an implicit transaction (repo convention).
-CREATE UNIQUE INDEX CONCURRENTLY workspace_share_link_pkey_uidx
+--
+-- IF NOT EXISTS covers the retry where the build committed but the runner died
+-- before recording the version: a bare CREATE would fail on "already exists"
+-- every time, and because 329 cannot attach a primary key without this index,
+-- the migrator would stay wedged there instead of moving on. The INVALID
+-- leftover of a genuinely interrupted build is removed first by the cleanup
+-- hook registered for this migration in cmd/migrate, so IF NOT EXISTS can never
+-- skip past a half-built index.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS workspace_share_link_pkey_uidx
ON workspace_share_link (id);
diff --git a/server/migrations/330_workspace_share_link_active_ws_uidx.up.sql b/server/migrations/330_workspace_share_link_active_ws_uidx.up.sql
index ed65b6d15a..cc8505f7cc 100644
--- a/server/migrations/330_workspace_share_link_active_ws_uidx.up.sql
+++ b/server/migrations/330_workspace_share_link_active_ws_uidx.up.sql
@@ -1,5 +1,8 @@
-- Enforce at most one active share link per workspace. Partial unique index so
-- only active rows are constrained; revoked/expired links remain in place for
-- audit without blocking a new link.
-CREATE UNIQUE INDEX CONCURRENTLY workspace_share_link_active_ws_uidx
+-- IF NOT EXISTS keeps a retry idempotent when the build committed but the
+-- version was never recorded; an interrupted build's INVALID leftover is
+-- dropped first by this migration's cleanup hook in cmd/migrate.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS workspace_share_link_active_ws_uidx
ON workspace_share_link (workspace_id) WHERE is_active = true;
diff --git a/server/migrations/331_workspace_share_link_code_uidx.up.sql b/server/migrations/331_workspace_share_link_code_uidx.up.sql
index 4f5d28273d..44d1dab534 100644
--- a/server/migrations/331_workspace_share_link_code_uidx.up.sql
+++ b/server/migrations/331_workspace_share_link_code_uidx.up.sql
@@ -1,3 +1,7 @@
-- Lookup index for joins/previews by invite code.
-CREATE UNIQUE INDEX CONCURRENTLY workspace_share_link_code_uidx
+--
+-- IF NOT EXISTS keeps a retry idempotent when the build committed but the
+-- version was never recorded; an interrupted build's INVALID leftover is
+-- dropped first by this migration's cleanup hook in cmd/migrate.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS workspace_share_link_code_uidx
ON workspace_share_link (code);