Skip to content

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

Go

MUL-6108: 清理首批冗余数据库索引 (#6878)

Multica Evecb8ce085ab68
diff --git a/docs/database-index-audit.md b/docs/database-index-audit.md
new file mode 100644
index 0000000000..47f7700480
--- /dev/null
+++ b/docs/database-index-audit.md
@@ -0,0 +1,88 @@
+# Database index audit
+
+This report captures the MUL-6108 baseline generated from PostgreSQL 17.10 at
+the branch base `254a02a79` after migrations 001–299. Re-run
+`scripts/audit-redundant-indexes.sql` against a freshly migrated isolated
+database before acting on it; prefix coverage is a candidate signal, not a drop
+decision.
+
+## Baseline
+
+- Public-schema indexes: 346 before this change, 342 after migrations 300–303.
+- Catalog candidates: 24 distinct indexes (32 candidate/covering pairs).
+- Additional B-tree reverse-scan candidate: 1 (`idx_sys_cron_exec_job_plan`).
+- First batch: remove 3 exact duplicates plus the verified reverse-scan
+ candidate. Keep all 21 strict-prefix candidates for later production-plan and
+ usage analysis.
+- Keep `idx_task_usage_created_at_legacy`: it has a distinct
+ `WHERE updated_at IS NULL` predicate and still supports the legacy branch of
+ `rollup_task_usage_hourly_window`.
+
+The catalog query requires matching access method, leading keys, opclasses,
+collations, sort options, predicate and index expressions. `exact` rows match on
+the full key; `prefix` rows match only on the candidate's complete left prefix.
+All 24 catalog candidates below are B-tree indexes with no predicate or
+expression; their candidate key columns use the same opclasses, collations and
+sort options as the covering prefix. The `sys_cron` row is the sole ordering
+exception and is documented separately below.
+
+## Complete candidate list
+
+| Table | Candidate | Relation | Covered by | Decision |
+| --- | --- | --- | --- | --- |
+| `agent` | `idx_agent_workspace` | prefix | `agent_workspace_name_unique`, `idx_agent_workspace_id_keyset` | keep pending evidence |
+| `agent_invocation_target` | `agent_invocation_target_agent_id_idx` | prefix | `agent_invocation_target_agent_id_target_type_target_id_key` | keep pending evidence |
+| `agent_runtime` | `idx_agent_runtime_workspace` | prefix | `idx_agent_runtime_status`, `idx_agent_runtime_workspace_id_keyset` | keep pending evidence |
+| `agent_skill` | `idx_agent_skill_agent` | prefix | `agent_skill_pkey` | keep pending evidence |
+| `agent_task_queue` | `idx_agent_task_queue_issue_id` | prefix | `idx_agent_task_queue_issue_id_keyset` | keep pending evidence |
+| `channel_chat_session_binding` | `idx_channel_chat_session_binding_session` | exact | `channel_chat_session_binding_chat_session_id_key` | drop in 302 |
+| `channel_installation` | `idx_channel_installation_workspace` | prefix | `channel_installation_workspace_id_agent_id_channel_type_key` | keep pending evidence |
+| `comment_reaction` | `idx_comment_reaction_comment_id` | prefix | `comment_reaction_comment_id_actor_type_actor_id_emoji_key` | keep pending evidence |
+| `github_installation` | `idx_github_installation_workspace` | prefix | `github_installation_workspace_id_installation_id_key` | keep pending evidence |
+| `github_pull_request` | `idx_github_pull_request_workspace` | prefix | `github_pull_request_workspace_id_repo_owner_repo_name_pr_nu_key` | keep pending evidence |
+| `issue` | `idx_issue_workspace` | prefix | `idx_issue_status`, `idx_issue_workspace_assignee`, `idx_issue_workspace_id_keyset`, `idx_issue_workspace_number`, `idx_issue_workspace_parent`, `idx_issue_workspace_position`, `uq_issue_workspace_number` | keep pending evidence |
+| `issue` | `idx_issue_workspace_number` | exact | `uq_issue_workspace_number` | drop in 300 |
+| `issue_reaction` | `idx_issue_reaction_issue_id` | prefix | `issue_reaction_issue_id_actor_type_actor_id_emoji_key` | keep pending evidence |
+| `lark_chat_session_binding` | `idx_lark_chat_session_binding_session` | exact | `lark_chat_session_binding_chat_session_id_key` | drop in 303 |
+| `lark_installation` | `idx_lark_installation_workspace` | prefix | `lark_installation_workspace_id_agent_id_key` | keep pending evidence |
+| `member` | `idx_member_workspace` | prefix | `member_workspace_id_user_id_key` | keep pending evidence |
+| `runtime_profile` | `idx_runtime_profile_workspace` | prefix | `runtime_profile_workspace_id_display_name_key` | keep pending evidence |
+| `skill` | `idx_skill_workspace` | prefix | `skill_workspace_id_name_key` | keep pending evidence |
+| `skill_file` | `idx_skill_file_skill` | prefix | `skill_file_skill_id_path_key` | keep pending evidence |
+| `squad_member` | `idx_squad_member_squad` | prefix | `squad_member_squad_id_member_type_member_id_key` | keep pending evidence |
+| `task_usage` | `idx_task_usage_task_id` | prefix | `task_usage_task_id_provider_model_key` | keep pending evidence |
+| `vcs_commit_status` | `idx_vcs_commit_status_lookup` | prefix | `vcs_commit_status_pkey` | keep pending evidence |
+| `vcs_connection` | `idx_vcs_connection_workspace` | prefix | `vcs_connection_workspace_id_instance_url_key` | keep pending evidence |
+| `vcs_pull_request` | `idx_vcs_pull_request_connection` | prefix | `vcs_pull_request_connection_id_repo_owner_repo_name_pr_numb_key` | keep pending evidence |
+| `sys_cron_executions` | `idx_sys_cron_exec_job_plan` | reverse scan | `uq_sys_cron_execution` | drop in 301 |
+
+`idx_sys_cron_exec_job_plan` is intentionally outside the strict catalog
+matches: its final key is `plan_time DESC`, while `uq_sys_cron_execution` uses
+the default ascending order. The scheduler constrains the preceding three keys
+by equality, so PostgreSQL can satisfy `ORDER BY plan_time DESC LIMIT 1` with an
+`Index Scan Backward` over the unique index. The migration regression test
+asserts that plan explicitly.
+
+## Rollout and rollback evidence
+
+Each drop is a standalone `DROP INDEX CONCURRENTLY` migration. Its down file is
+a standalone `CREATE INDEX CONCURRENTLY` with the original definition. The
+migration runner now executes a down-direction INVALID-index cleanup hook before
+retrying those creates, so an interrupted rollback cannot be recorded while
+leaving an unusable index.
+
+The isolated regression fixture records the structural before/after comparison:
+
+| Measure | Before | After |
+| --- | ---: | ---: |
+| Public-schema index count | 346 | 342 |
+| Redundant B-tree maintenance per affected insert/indexed-key update | 1 | 0 |
+| Covering/constraint indexes retained | 4 | 4 |
+
+Disk reclaimed in an environment is the sum of `pg_relation_size` for the four
+dropped indexes; it depends on row count and value distribution. The migration
+test measures this sum on its seeded fixture before the drops and verifies that
+all four relations disappear afterward. Production should record those sizes
+before rollout rather than extrapolating a synthetic byte count; the reusable
+audit script intentionally does not hardcode a batch that disappears after the
+cleanup lands.
diff --git a/scripts/audit-redundant-indexes.sql b/scripts/audit-redundant-indexes.sql
new file mode 100644
index 0000000000..fe9d14ccac
--- /dev/null
+++ b/scripts/audit-redundant-indexes.sql
@@ -0,0 +1,68 @@
+-- Find valid, non-constraint-backed indexes whose complete key is identical to
+-- or a strict left prefix of another index on the same public-schema table.
+--
+-- This deliberately compares access method, columns/expressions, opclasses,
+-- collations, sort options and predicates. It does not decide that a prefix
+-- candidate should be dropped: a narrower index can still be materially
+-- smaller or have better production usage.
+WITH idx AS (
+ SELECT
+ i.indexrelid,
+ i.indrelid,
+ c.relname AS idxname,
+ t.relname AS tblname,
+ c.relam AS am,
+ i.indisunique,
+ i.indisprimary,
+ (
+ SELECT con.conname
+ FROM pg_constraint con
+ WHERE con.conindid = i.indexrelid
+ LIMIT 1
+ ) AS conname,
+ i.indnkeyatts AS nkey,
+ i.indkey::int2[] AS keys,
+ i.indcollation::oid[] AS colls,
+ i.indclass::oid[] AS opcls,
+ i.indoption::int2[] AS opts,
+ pg_get_expr(i.indpred, i.indrelid) AS pred,
+ pg_get_expr(i.indexprs, i.indrelid) AS exprs,
+ pg_get_indexdef(i.indexrelid) AS def
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_class t ON t.oid = i.indrelid
+ JOIN pg_namespace n ON n.oid = t.relnamespace
+ WHERE n.nspname = 'public'
+ AND c.relkind = 'i'
+ AND i.indisvalid
+)
+SELECT
+ a.tblname,
+ a.idxname AS redundant_index,
+ CASE WHEN a.nkey = b.nkey THEN 'exact' ELSE 'prefix' END AS relation,
+ b.idxname AS covered_by,
+ CASE
+ WHEN b.indisprimary THEN 'pkey'
+ WHEN b.conname IS NOT NULL THEN 'constraint'
+ WHEN b.indisunique THEN 'unique_idx'
+ ELSE 'plain_idx'
+ END AS covering_kind,
+ a.def AS candidate_definition,
+ b.def AS covering_definition
+FROM idx a
+JOIN idx b
+ ON a.indrelid = b.indrelid
+ AND a.indexrelid <> b.indexrelid
+ AND a.am = b.am
+WHERE NOT a.indisunique
+ AND a.conname IS NULL
+ AND a.nkey <= b.nkey
+ AND a.keys[0:a.nkey - 1] = b.keys[0:a.nkey - 1]
+ AND a.opcls[0:a.nkey - 1] = b.opcls[0:a.nkey - 1]
+ AND a.colls[0:a.nkey - 1] = b.colls[0:a.nkey - 1]
+ AND a.opts[0:a.nkey - 1] = b.opts[0:a.nkey - 1]
+ AND COALESCE(a.pred, '') = COALESCE(b.pred, '')
+ -- Expression columns have indkey=0, so compare the expressions too. Without
+ -- this guard, unrelated expression indexes can be reported as duplicates.
+ AND COALESCE(a.exprs, '') = COALESCE(b.exprs, '')
+ORDER BY a.tblname, a.idxname, b.idxname;
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 37270856b4..72bc57f6c6 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -16,16 +16,16 @@ import (
"github.com/multica-ai/multica/server/internal/taskusagebackfill"
)
-// preMigrationHook runs work that must happen before a specific
-// migration is applied during `migrate up`. Hooks are idempotent and
+// preMigrationHook runs work that must happen before a specific migration is
+// applied in the direction whose hook map selected it. Hooks are idempotent and
// must not depend on the migration loop's session-pinned advisory lock
// — they run on the pool, not on the loop's pinned conn, so they can
// safely acquire other session-level locks (e.g. advisory lock 4246
// for the task_usage hourly rollup).
//
-// Returning an error aborts the migration run. The corresponding
-// migration is NOT recorded in schema_migrations, so the next run will
-// retry the hook + migration.
+// Returning an error aborts the migration run. The corresponding migration is
+// not added to (up) or removed from (down) schema_migrations, so the next run
+// retries the hook + migration.
type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error
// preMigrationHooks wires migration version → hook. The version key is
@@ -63,7 +63,7 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error
// 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
+// The mapping is data rather than individual 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.
@@ -102,6 +102,23 @@ var concurrentIndexCleanups = map[string]string{
"299_agent_task_plugin_manifest_index": "idx_agent_task_plugin_execution_manifest",
}
+// concurrentDownIndexCleanups covers every migration whose down direction
+// rebuilds an index with CREATE INDEX CONCURRENTLY. An interrupted rollback
+// can leave an INVALID relation behind. IF NOT EXISTS would then silently skip
+// the retry, while a bare CREATE would stay wedged on "already exists"; both
+// cases need direction-specific cleanup before the rollback can retry safely.
+var concurrentDownIndexCleanups = map[string]string{
+ "144_drop_agent_task_queue_chat_pending_v1": "idx_agent_task_queue_chat_pending",
+ "171_drop_legacy_label_namespace_index": "issue_label_workspace_name_lower_idx",
+ "256_drop_agent_task_queue_chat_pending_v2": "idx_agent_task_queue_chat_pending_v2",
+ "258_drop_pending_issue_agent_v1": "idx_one_pending_task_per_issue_agent",
+ "262_drop_agent_task_queue_terminal_completed_at_v1": "idx_agent_task_queue_terminal_completed_at",
+ "300_drop_redundant_issue_workspace_number_index": "idx_issue_workspace_number",
+ "301_drop_redundant_sys_cron_job_plan_index": "idx_sys_cron_exec_job_plan",
+ "302_drop_redundant_channel_chat_session_binding_index": "idx_channel_chat_session_binding_session",
+ "303_drop_redundant_lark_chat_session_binding_index": "idx_lark_chat_session_binding_session",
+}
+
var preMigrationHooks = func() map[string]preMigrationHook {
hooks := map[string]preMigrationHook{
"103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,
@@ -113,6 +130,25 @@ var preMigrationHooks = func() map[string]preMigrationHook {
return hooks
}()
+var preRollbackHooks = func() map[string]preMigrationHook {
+ hooks := make(map[string]preMigrationHook, len(concurrentDownIndexCleanups))
+ for version, index := range concurrentDownIndexCleanups {
+ hooks[version] = cleanupInvalidConcurrentIndexHook(index)
+ }
+ return hooks
+}()
+
+func hooksForDirection(direction string) map[string]preMigrationHook {
+ switch direction {
+ case "up":
+ return preMigrationHooks
+ case "down":
+ return preRollbackHooks
+ default:
+ return nil
+ }
+}
+
// 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 leftover
@@ -225,7 +261,8 @@ type runOptions struct {
// receives the pool (not the loop's pinned conn) so it can take
// its own session-level locks. nil or missing entries mean "no
// hook" and the migration runs straight through. Production main()
- // passes preMigrationHooks; tests leave this nil.
+ // passes the direction-specific hook map; tests leave this nil unless they
+ // exercise a hook.
Hooks map[string]preMigrationHook
}
@@ -270,7 +307,7 @@ func main() {
if err := runMigrations(ctx, pool, runOptions{
Direction: direction,
Files: files,
- Hooks: preMigrationHooks,
+ Hooks: hooksForDirection(direction),
}); err != nil {
slog.Error("migration run failed", "error", err)
os.Exit(1)
@@ -388,12 +425,10 @@ func runMigrations(ctx context.Context, pool *pgxpool.Pool, opts runOptions) err
// colliding with migrationAdvisoryLockKey. Hook failures
// abort the run before schema_migrations is updated, so the
// same version retries cleanly on the next invocation.
- if opts.Direction == "up" {
- if hook, ok := opts.Hooks[version]; ok && hook != nil {
- slog.Info("running pre-migration hook", "version", version)
- if err := hook(ctx, pool); err != nil {
- return fmt.Errorf("pre-migration hook for %q: %w", version, err)
- }
+ if hook, ok := opts.Hooks[version]; ok && hook != nil {
+ slog.Info("running pre-migration hook", "version", version, "direction", opts.Direction)
+ if err := hook(ctx, pool); err != nil {
+ return fmt.Errorf("pre-migration hook for %q (%s): %w", version, opts.Direction, err)
}
}
diff --git a/server/cmd/migrate/migrate_concurrent_test.go b/server/cmd/migrate/migrate_concurrent_test.go
index 32b5e9ea02..c264354f70 100644
--- a/server/cmd/migrate/migrate_concurrent_test.go
+++ b/server/cmd/migrate/migrate_concurrent_test.go
@@ -61,6 +61,7 @@ import (
// during cleanup.
const (
+ defaultTestDatabaseURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
// concurrentRunners is the goroutine count for the race tests. Set
// large enough that a missing lock would reliably trip on a multi-
// core box with -race, but small enough to keep the suite fast on a
@@ -72,12 +73,16 @@ const (
raceTestTimeout = 60 * time.Second
)
+func testDatabaseURL() string {
+ if dbURL := os.Getenv("DATABASE_URL"); dbURL != "" {
+ return dbURL
+ }
+ return defaultTestDatabaseURL
+}
+
func openTestPool(t *testing.T) *pgxpool.Pool {
t.Helper()
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
- }
+ dbURL := testDatabaseURL()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pool, err := pgxpool.New(ctx, dbURL)
@@ -349,10 +354,7 @@ func TestRunMigrationsAdvisoryLockSerializes(t *testing.T) {
// connection re-enters". (pg_advisory_lock is reentrant on the same
// session, so re-acquiring on the same conn would not actually
// prove serialization.)
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
- }
+ dbURL := testDatabaseURL()
holder, err := pgx.Connect(ctx, dbURL)
if err != nil {
t.Fatalf("side connect: %v", err)
@@ -412,10 +414,7 @@ func TestRunMigrationsAdvisoryLockSerializes(t *testing.T) {
// this test will deadlock or produce SQL races. Pool size strictly
// less than runners is the interesting configuration.
func TestRunMigrationsConcurrentMixedPoolStress(t *testing.T) {
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
- }
+ dbURL := testDatabaseURL()
cfg, err := pgxpool.ParseConfig(dbURL)
if err != nil {
t.Skipf("parse DATABASE_URL: %v", err)
diff --git a/server/cmd/migrate/migrate_invalid_index_test.go b/server/cmd/migrate/migrate_invalid_index_test.go
index 769fd941d9..caae84f0a9 100644
--- a/server/cmd/migrate/migrate_invalid_index_test.go
+++ b/server/cmd/migrate/migrate_invalid_index_test.go
@@ -96,6 +96,126 @@ func TestRunMigrationsRepairsInvalidConcurrentIndexBeforeRetry(t *testing.T) {
}
}
+// TestRunMigrationsRepairsInvalidConcurrentIndexDuringRollback proves that
+// direction-specific hooks also protect CREATE INDEX CONCURRENTLY in down
+// migrations. Without the hook, an interrupted rollback leaves an INVALID
+// relation that IF NOT EXISTS accepts on retry, and the migration version is
+// removed even though the restored index remains unusable.
+func TestRunMigrationsRepairsInvalidConcurrentIndexDuringRollback(t *testing.T) {
+ pool := openTestPool(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
+ schema := "migrate_down_invalid_idx_" + 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 (
+ version = "300_drop_redundant_issue_workspace_number_index"
+ indexName = "idx_issue_workspace_number"
+ )
+ tableName := pgx.Identifier{schema, "issue"}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE TABLE "+tableName+` (
+ id BIGSERIAL PRIMARY KEY,
+ workspace_id UUID NOT NULL,
+ number INTEGER NOT NULL
+ )`); err != nil {
+ t.Fatalf("create issue table: %v", err)
+ }
+
+ qualifiedIndex := pgx.Identifier{schema, indexName}.Sanitize()
+ createIndex := "CREATE INDEX CONCURRENTLY IF NOT EXISTS " + pgx.Identifier{indexName}.Sanitize() +
+ " ON " + tableName + " (workspace_id, number)"
+
+ 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+" (workspace_id, number) VALUES (gen_random_uuid(), 1)"); 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)
+ 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 rollback build unexpectedly succeeded")
+ }
+ _ = blockerTx.Rollback(ctx)
+ blocker.Release()
+
+ assertIndexValidity(t, pool, schema, indexName, false)
+
+ migrationsTable := pgx.Identifier{schema, "schema_migrations"}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE TABLE "+migrationsTable+` (
+ version TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )`); err != nil {
+ t.Fatalf("create migrations table: %v", err)
+ }
+ if _, err := pool.Exec(ctx, "INSERT INTO "+migrationsTable+" (version) VALUES ($1)", version); err != nil {
+ t.Fatalf("record applied migration: %v", err)
+ }
+
+ downPath := filepath.Join(t.TempDir(), version+".down.sql")
+ if err := os.WriteFile(downPath, []byte(createIndex+";\n"), 0o600); err != nil {
+ t.Fatalf("write rollback migration: %v", err)
+ }
+ if preRollbackHooks[version] == nil {
+ t.Fatalf("production rollback hook is not registered for %s", version)
+ }
+ opts := runOptions{
+ Direction: "down",
+ Files: []string{downPath},
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: map[string]preMigrationHook{
+ version: cleanupInvalidConcurrentIndexHook(qualifiedIndex),
+ },
+ }
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatalf("retry rollback with invalid-index cleanup: %v", err)
+ }
+
+ assertIndexValidity(t, pool, schema, indexName, true)
+ var recorded bool
+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM "+migrationsTable+" WHERE version = $1)", version).Scan(&recorded); err != nil {
+ t.Fatalf("read migration version: %v", err)
+ }
+ if recorded {
+ t.Fatal("rolled-back migration version is still recorded")
+ }
+}
+
// TestRunMigrationsRepairsInvalidTerminalCompletedAtIndex is the MUL-5823
// counterpart of the test above, for the 261/262 partial-index swap.
//
diff --git a/server/cmd/migrate/migrate_mul5999_index_retry_test.go b/server/cmd/migrate/migrate_mul5999_index_retry_test.go
index a94c712252..98988f7832 100644
--- a/server/cmd/migrate/migrate_mul5999_index_retry_test.go
+++ b/server/cmd/migrate/migrate_mul5999_index_retry_test.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"regexp"
+ "strings"
"testing"
"time"
@@ -36,8 +37,84 @@ func stripSQLLineComments(body []byte) []byte {
// 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")
+ assertConcurrentIndexCleanupsMatchTheirMigrations(
+ t,
+ concurrentIndexCleanups,
+ preMigrationHooks,
+ "up",
+ )
+ assertConcurrentIndexCleanupsMatchTheirMigrations(
+ t,
+ concurrentDownIndexCleanups,
+ preRollbackHooks,
+ "down",
+ )
+
+ // 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)
+ }
+ }
+
+}
+
+// TestEveryConcurrentDownBuildHasCleanup works in the opposite direction from
+// TestConcurrentIndexCleanupsMatchTheirMigrations: every rollback migration
+// 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"))
+ if err != nil {
+ t.Fatalf("glob down migrations: %v", err)
+ }
+ if len(paths) == 0 {
+ t.Fatal("no down migrations found")
+ }
+
+ for _, path := range paths {
+ body, err := os.ReadFile(path)
+ if err != nil {
+ t.Errorf("%s: read: %v", path, err)
+ continue
+ }
+ matches := concurrentIndexNamePattern.FindAllSubmatch(stripSQLLineComments(body), -1)
+ if len(matches) == 0 {
+ continue
+ }
+ version := strings.TrimSuffix(filepath.Base(path), ".down.sql")
+ 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]
+ if !ok {
+ t.Errorf("%s: builds %q concurrently on rollback but has no down cleanup", version, indexName)
+ continue
+ }
+ if registered != indexName {
+ t.Errorf("%s: down cleanup registers %q, migration builds %q", version, registered, indexName)
+ }
+ }
+}
+
+func assertConcurrentIndexCleanupsMatchTheirMigrations(
+ t *testing.T,
+ cleanups map[string]string,
+ hooks map[string]preMigrationHook,
+ direction string,
+) {
+ t.Helper()
+ for version, indexName := range cleanups {
+ path := filepath.Join("..", "..", "migrations", version+"."+direction+".sql")
body, err := os.ReadFile(path)
if err != nil {
t.Errorf("%s: read migration: %v", version, err)
@@ -53,24 +130,10 @@ func TestConcurrentIndexCleanupsMatchTheirMigrations(t *testing.T) {
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 {
+ if hooks[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
diff --git a/server/cmd/migrate/migrate_redundant_indexes_test.go b/server/cmd/migrate/migrate_redundant_indexes_test.go
new file mode 100644
index 0000000000..bf39d83e68
--- /dev/null
+++ b/server/cmd/migrate/migrate_redundant_indexes_test.go
@@ -0,0 +1,325 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestRedundantIndexMigrationsPreserveCoveringQueryPlansAndRollback(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_redundant_idx_" + 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)
+ createRedundantIndexFixture(t, ctx, pool)
+
+ versions := []string{
+ "300_drop_redundant_issue_workspace_number_index",
+ "301_drop_redundant_sys_cron_job_plan_index",
+ "302_drop_redundant_channel_chat_session_binding_index",
+ "303_drop_redundant_lark_chat_session_binding_index",
+ }
+ indexNames := []string{
+ "idx_issue_workspace_number",
+ "idx_sys_cron_exec_job_plan",
+ "idx_channel_chat_session_binding_session",
+ "idx_lark_chat_session_binding_session",
+ }
+ indexCountBefore := countSchemaIndexes(t, pool, schema)
+ redundantBytesBefore := sumIndexSizes(t, pool, schema, indexNames)
+ if redundantBytesBefore <= 0 {
+ t.Fatalf("redundant index size before drops = %d, want positive", redundantBytesBefore)
+ }
+ t.Logf("seeded fixture before drops: indexes=%d redundant_bytes=%d", indexCountBefore, redundantBytesBefore)
+
+ if err := runMigrations(ctx, pool, runOptions{
+ Direction: "up",
+ Files: realMigrationFiles(t, versions, "up"),
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("up"),
+ }); err != nil {
+ t.Fatalf("apply redundant-index drops: %v", err)
+ }
+
+ for _, indexName := range indexNames {
+ assertIndexExists(t, pool, schema, indexName, false)
+ }
+ indexCountAfter := countSchemaIndexes(t, pool, schema)
+ if indexCountAfter != indexCountBefore-len(indexNames) {
+ t.Fatalf("schema index count after drops = %d, want %d", indexCountAfter, indexCountBefore-len(indexNames))
+ }
+ if got := sumIndexSizes(t, pool, schema, indexNames); got != 0 {
+ t.Fatalf("redundant index size after drops = %d, want 0", got)
+ }
+ t.Logf("seeded fixture after drops: indexes=%d redundant_bytes=0", indexCountAfter)
+ for _, indexName := range []string{
+ "uq_issue_workspace_number",
+ "uq_sys_cron_execution",
+ "channel_chat_session_binding_chat_session_id_key",
+ "lark_chat_session_binding_chat_session_id_key",
+ } {
+ assertIndexValidity(t, pool, schema, indexName, true)
+ }
+
+ assertPlanUsesIndex(t, pool,
+ `SELECT id FROM issue
+ WHERE workspace_id = '00000000-0000-0000-0000-000000000001'
+ AND number = 2500`,
+ "uq_issue_workspace_number",
+ )
+ assertPlanUsesIndex(t, pool,
+ `SELECT id FROM sys_cron_executions
+ WHERE job_name = 'job'
+ AND scope_kind = 'global'
+ AND scope_id = 'global'
+ ORDER BY plan_time DESC
+ LIMIT 1`,
+ "Index Scan Backward using uq_sys_cron_execution",
+ )
+ assertPlanUsesIndex(t, pool,
+ `SELECT id FROM channel_chat_session_binding
+ WHERE chat_session_id = '00000000-0000-0000-0000-000000001234'`,
+ "channel_chat_session_binding_chat_session_id_key",
+ )
+ assertPlanUsesIndex(t, pool,
+ `SELECT id FROM lark_chat_session_binding
+ WHERE chat_session_id = '00000000-0000-0000-0000-000000001234'`,
+ "lark_chat_session_binding_chat_session_id_key",
+ )
+
+ reversedVersions := append([]string(nil), versions...)
+ for left, right := 0, len(reversedVersions)-1; left < right; left, right = left+1, right-1 {
+ reversedVersions[left], reversedVersions[right] = reversedVersions[right], reversedVersions[left]
+ }
+ if err := runMigrations(ctx, pool, runOptions{
+ Direction: "down",
+ Files: realMigrationFiles(t, reversedVersions, "down"),
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("down"),
+ }); err != nil {
+ t.Fatalf("roll back redundant-index drops: %v", err)
+ }
+
+ for _, indexName := range indexNames {
+ assertIndexValidity(t, pool, schema, indexName, true)
+ }
+ var sysCronIndexDefinition string
+ if err := pool.QueryRow(ctx,
+ "SELECT pg_get_indexdef($1::regclass)",
+ pgx.Identifier{schema, "idx_sys_cron_exec_job_plan"}.Sanitize(),
+ ).Scan(&sysCronIndexDefinition); err != nil {
+ t.Fatalf("read restored sys_cron index definition: %v", err)
+ }
+ if !strings.Contains(sysCronIndexDefinition, "plan_time DESC") {
+ t.Fatalf("restored sys_cron index lost descending order: %s", sysCronIndexDefinition)
+ }
+}
+
+func openTestPoolWithSearchPath(t *testing.T, schema string) *pgxpool.Pool {
+ t.Helper()
+ config, err := pgxpool.ParseConfig(testDatabaseURL())
+ if err != nil {
+ t.Fatalf("parse test database URL: %v", err)
+ }
+ config.ConnConfig.RuntimeParams["search_path"] = schema
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatalf("open schema-scoped test pool: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Fatalf("ping schema-scoped test pool: %v", err)
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+func createRedundantIndexFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {
+ t.Helper()
+ statements := []string{
+ `CREATE TABLE schema_migrations (
+ version TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )`,
+ `CREATE TABLE issue (
+ id BIGSERIAL PRIMARY KEY,
+ workspace_id UUID NOT NULL,
+ number INTEGER NOT NULL,
+ CONSTRAINT uq_issue_workspace_number UNIQUE (workspace_id, number)
+ )`,
+ `CREATE INDEX idx_issue_workspace_number ON issue (workspace_id, number)`,
+ `CREATE TABLE sys_cron_executions (
+ id BIGSERIAL PRIMARY KEY,
+ job_name TEXT NOT NULL,
+ scope_kind TEXT NOT NULL,
+ scope_id TEXT NOT NULL,
+ plan_time TIMESTAMPTZ NOT NULL,
+ CONSTRAINT uq_sys_cron_execution UNIQUE (job_name, scope_kind, scope_id, plan_time)
+ )`,
+ `CREATE INDEX idx_sys_cron_exec_job_plan
+ ON sys_cron_executions (job_name, scope_kind, scope_id, plan_time DESC)`,
+ `CREATE TABLE channel_chat_session_binding (
+ id BIGSERIAL PRIMARY KEY,
+ chat_session_id UUID NOT NULL,
+ CONSTRAINT channel_chat_session_binding_chat_session_id_key UNIQUE (chat_session_id)
+ )`,
+ `CREATE INDEX idx_channel_chat_session_binding_session
+ ON channel_chat_session_binding (chat_session_id)`,
+ `CREATE TABLE lark_chat_session_binding (
+ id BIGSERIAL PRIMARY KEY,
+ chat_session_id UUID NOT NULL,
+ CONSTRAINT lark_chat_session_binding_chat_session_id_key UNIQUE (chat_session_id)
+ )`,
+ `CREATE INDEX idx_lark_chat_session_binding_session
+ ON lark_chat_session_binding (chat_session_id)`,
+ `INSERT INTO issue (workspace_id, number)
+ SELECT '00000000-0000-0000-0000-000000000001', n
+ FROM generate_series(1, 5000) AS n`,
+ `INSERT INTO sys_cron_executions (job_name, scope_kind, scope_id, plan_time)
+ SELECT 'job', 'global', 'global', now() - make_interval(secs => n)
+ FROM generate_series(1, 5000) AS n`,
+ `INSERT INTO channel_chat_session_binding (chat_session_id)
+ SELECT ('00000000-0000-0000-0000-' || lpad(n::text, 12, '0'))::uuid
+ FROM generate_series(1, 5000) AS n`,
+ `INSERT INTO lark_chat_session_binding (chat_session_id)
+ SELECT ('00000000-0000-0000-0000-' || lpad(n::text, 12, '0'))::uuid
+ FROM generate_series(1, 5000) AS n`,
+ `ANALYZE issue`,
+ `ANALYZE sys_cron_executions`,
+ `ANALYZE channel_chat_session_binding`,
+ `ANALYZE lark_chat_session_binding`,
+ }
+ for _, statement := range statements {
+ if _, err := pool.Exec(ctx, statement); err != nil {
+ t.Fatalf("apply fixture statement %q: %v", statement, err)
+ }
+ }
+}
+
+func realMigrationFiles(t *testing.T, versions []string, direction string) []string {
+ t.Helper()
+ files := make([]string, 0, len(versions))
+ for _, version := range versions {
+ path := filepath.Join("..", "..", "migrations", version+"."+direction+".sql")
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("stat migration %s: %v", path, err)
+ }
+ files = append(files, path)
+ }
+ return files
+}
+
+func assertIndexExists(
+ t *testing.T,
+ pool *pgxpool.Pool,
+ schema string,
+ indexName string,
+ want bool,
+) {
+ t.Helper()
+ var exists bool
+ if err := pool.QueryRow(context.Background(), `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = $1
+ AND c.relname = $2
+ AND c.relkind = 'i'
+ )
+ `, schema, indexName).Scan(&exists); err != nil {
+ t.Fatalf("read existence for %s.%s: %v", schema, indexName, err)
+ }
+ if exists != want {
+ t.Fatalf("index %s.%s existence = %v, want %v", schema, indexName, exists, want)
+ }
+}
+
+func countSchemaIndexes(t *testing.T, pool *pgxpool.Pool, schema string) int {
+ t.Helper()
+ var count int
+ if err := pool.QueryRow(context.Background(), `
+ SELECT count(*)
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = $1
+ AND c.relkind = 'i'
+ `, schema).Scan(&count); err != nil {
+ t.Fatalf("count indexes in schema %s: %v", schema, err)
+ }
+ return count
+}
+
+func sumIndexSizes(
+ t *testing.T,
+ pool *pgxpool.Pool,
+ schema string,
+ indexNames []string,
+) int64 {
+ t.Helper()
+ var bytes int64
+ if err := pool.QueryRow(context.Background(), `
+ SELECT COALESCE(sum(pg_relation_size(c.oid)), 0)::bigint
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = $1
+ AND c.relname = ANY($2::text[])
+ AND c.relkind = 'i'
+ `, schema, indexNames).Scan(&bytes); err != nil {
+ t.Fatalf("sum redundant index sizes in schema %s: %v", schema, err)
+ }
+ return bytes
+}
+
+func assertPlanUsesIndex(t *testing.T, pool *pgxpool.Pool, query, want string) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ rows, err := pool.Query(ctx, "EXPLAIN (COSTS OFF) "+query)
+ if err != nil {
+ t.Fatalf("explain query: %v", err)
+ }
+ defer rows.Close()
+ var planLines []string
+ for rows.Next() {
+ var line string
+ if err := rows.Scan(&line); err != nil {
+ t.Fatalf("scan explain row: %v", err)
+ }
+ planLines = append(planLines, line)
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("read explain rows: %v", err)
+ }
+ plan := strings.Join(planLines, "\n")
+ if !strings.Contains(plan, want) {
+ t.Fatalf("query plan does not use %q:\n%s", want, plan)
+ }
+}
diff --git a/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql
index 40d36decfa..0f5f8ca5f8 100644
--- a/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql
+++ b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql
@@ -1,7 +1,7 @@
-- Recreate v1 before migration 261's down step removes v2.
--- Do not use IF NOT EXISTS here: pre-migration hooks only run in the `up`
--- direction, so a leftover INVALID v1 must fail closed while the valid v2
--- index remains in place instead of being recorded as restored.
+-- Keep this as a bare CREATE so runners that do not provide the down-direction
+-- cleanup hook fail closed on a leftover INVALID v1 while the valid v2 index
+-- remains in place instead of recording the rollback as restored.
CREATE INDEX CONCURRENTLY idx_agent_task_queue_terminal_completed_at
ON agent_task_queue (completed_at)
WHERE status IN ('completed', 'failed');
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.sql
index 62f311aec9..d8f8895902 100644
--- 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.sql
@@ -7,9 +7,8 @@
-- (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.
+-- direction-aware INVALID-index cleanup, because the down path of such a drop
+-- is a CREATE INDEX CONCURRENTLY. 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/300_drop_redundant_issue_workspace_number_index.down.sql b/server/migrations/300_drop_redundant_issue_workspace_number_index.down.sql
new file mode 100644
index 0000000000..e91fcd7f23
--- /dev/null
+++ b/server/migrations/300_drop_redundant_issue_workspace_number_index.down.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_number
+ ON issue (workspace_id, number);
diff --git a/server/migrations/300_drop_redundant_issue_workspace_number_index.up.sql b/server/migrations/300_drop_redundant_issue_workspace_number_index.up.sql
new file mode 100644
index 0000000000..dd1f8e306a
--- /dev/null
+++ b/server/migrations/300_drop_redundant_issue_workspace_number_index.up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_number;
diff --git a/server/migrations/301_drop_redundant_sys_cron_job_plan_index.down.sql b/server/migrations/301_drop_redundant_sys_cron_job_plan_index.down.sql
new file mode 100644
index 0000000000..208f03bee0
--- /dev/null
+++ b/server/migrations/301_drop_redundant_sys_cron_job_plan_index.down.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_sys_cron_exec_job_plan
+ ON sys_cron_executions (job_name, scope_kind, scope_id, plan_time DESC);
diff --git a/server/migrations/301_drop_redundant_sys_cron_job_plan_index.up.sql b/server/migrations/301_drop_redundant_sys_cron_job_plan_index.up.sql
new file mode 100644
index 0000000000..063c082b83
--- /dev/null
+++ b/server/migrations/301_drop_redundant_sys_cron_job_plan_index.up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_sys_cron_exec_job_plan;
diff --git a/server/migrations/302_drop_redundant_channel_chat_session_binding_index.down.sql b/server/migrations/302_drop_redundant_channel_chat_session_binding_index.down.sql
new file mode 100644
index 0000000000..ec3fbcb426
--- /dev/null
+++ b/server/migrations/302_drop_redundant_channel_chat_session_binding_index.down.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_channel_chat_session_binding_session
+ ON channel_chat_session_binding (chat_session_id);
diff --git a/server/migrations/302_drop_redundant_channel_chat_session_binding_index.up.sql b/server/migrations/302_drop_redundant_channel_chat_session_binding_index.up.sql
new file mode 100644
index 0000000000..0e483a85c4
--- /dev/null
+++ b/server/migrations/302_drop_redundant_channel_chat_session_binding_index.up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_chat_session_binding_session;
diff --git a/server/migrations/303_drop_redundant_lark_chat_session_binding_index.down.sql b/server/migrations/303_drop_redundant_lark_chat_session_binding_index.down.sql
new file mode 100644
index 0000000000..1a709c55b9
--- /dev/null
+++ b/server/migrations/303_drop_redundant_lark_chat_session_binding_index.down.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_lark_chat_session_binding_session
+ ON lark_chat_session_binding (chat_session_id);
diff --git a/server/migrations/303_drop_redundant_lark_chat_session_binding_index.up.sql b/server/migrations/303_drop_redundant_lark_chat_session_binding_index.up.sql
new file mode 100644
index 0000000000..bcc10bb609
--- /dev/null
+++ b/server/migrations/303_drop_redundant_lark_chat_session_binding_index.up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_lark_chat_session_binding_session;