Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(db): retire obsolete comment content search indexes (#8148)
Multica Evede5eaf51f9c3
diff --git a/server/cmd/migrate/README.md b/server/cmd/migrate/README.mdindex 12ae3209a3..e758913bd8 100644--- a/server/cmd/migrate/README.md+++ b/server/cmd/migrate/README.md@@ -1,14 +1,42 @@# Migration runner operations-## Recover the comment content search index+## Comment content search index retirement++Migrations 454 and 455 retire both historical comment-content search indexes:+`idx_comment_content_bigm` on pg_bigm deployments and the portable+`idx_comment_content_trgm` fallback. `SearchIssues` now scans comments through+`idx_comment_workspace` and evaluates content matches during aggregation, so it+no longer reads either global content GIN. Fresh installs also skip migration+140's historical fallback build. Do not repair or recreate these indexes after+applying migrations 454 and 455.++The down migrations restore exactly one historical index with+`CREATE INDEX CONCURRENTLY`: migration 454 restores the pg_bigm index where+`gin_bigm_ops` is available, while migration 455 restores the pg_trgm fallback+everywhere else.+Both restore the original `LOWER(content)` expression and retry safely after an+interrupted concurrent build.++These migrations run during backend startup. A concurrent drop waits for old+transactions, and the Helm startup probe allows ten minutes before restarting+the pod. For the multi-gigabyte production index, prefer a low-traffic window:+check for long-running transactions, then run each statement separately and+outside a transaction before deploying:-Migration 371 keeps exactly one comment-content search index per environment:-`idx_comment_content_bigm` when `pg_bigm` is usable, otherwise the portable-`idx_comment_content_trgm` fallback. A conditionally skipped migration is still-recorded in `schema_migrations`, so rerunning `migrate up` does not recreate the-fallback if the selected bigram index is later dropped or becomes invalid.+```sql+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_bigm;+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_trgm;+```-First check whether either index is live, ready, and valid:+The subsequent migrations become fast no-ops. If startup performs the drop and+is interrupted instead, `IF EXISTS` makes the next run retry safely; one index+may remain until that retry completes. Dropping the large relation can also+produce a short I/O spike as storage is reclaimed.++An application rollback remains functionally correct without either index, but+legacy search can be much slower. Database rollback must rebuild the selected+GIN and is not immediate; verify the restored index is live, ready, and valid+before relying on the old query's performance:```sqlSELECT indexrelid::regclass AS index_name, indisvalid, indisready, indislive@@ -19,25 +47,6 @@ WHERE indexrelid IN ();```-If neither index is usable, restore the portable fallback before serving search-traffic. Run each statement separately and outside a transaction so the-concurrent index build is valid:--```sql-CREATE EXTENSION IF NOT EXISTS pg_trgm;-DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_trgm;-CREATE INDEX CONCURRENTLY idx_comment_content_trgm- ON comment USING gin (LOWER(content) gin_trgm_ops);-```--Verify that `idx_comment_content_trgm` reports all three flags as `true` before-resuming traffic. If `idx_comment_content_bigm` is repaired later, keep the-fallback until the bigram index also reports all three flags as `true` **and**-has the exact migration 036 shape: a non-unique, non-partial GIN index on-`LOWER(content)` using the `pg_bigm`-owned `gin_bigm_ops` operator class. Only-then can the fallback be dropped with `DROP INDEX CONCURRENTLY` during a-maintenance window.-## Build the issue properties bigram index after installing pg_bigmMigration 446 builds `idx_issue_properties_bigm`, the index behind the prefilterdiff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex a4a7dc7d4c..e99311670d 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -72,11 +72,11 @@ type extensionOperatorClass struct {Extension string}-// issuePropertiesBigramOperatorClass gates migration 446. pg_bigm ships with-// neither core Postgres nor the pgvector image CI and self-hosted deployments-// run, so the index it builds is best-effort; the contains prefilter it-// accelerates stays correct without it.-var issuePropertiesBigramOperatorClass = extensionOperatorClass{+// pgBigmOperatorClass gates migrations that build optional pg_bigm indexes.+// pg_bigm ships with neither core Postgres nor the pgvector image CI and+// self-hosted deployments run, so those migrations must remain safe when the+// operator class is unavailable.+var pgBigmOperatorClass = extensionOperatorClass{AccessMethod: "gin",OperatorClass: "gin_bigm_ops",Extension: "pg_bigm",@@ -324,6 +324,8 @@ var concurrentDownIndexCleanups = map[string]string{"437_drop_agent_runtime_last_seen_at_index": "idx_agent_runtime_last_seen_at","450_drop_comment_delegated_failure_pending_index": "idx_comment_delegated_failure_pending","453_drop_pending_issue_agent_unique": "idx_one_pending_task_per_issue_agent_v2",+ "454_drop_comment_content_bigm_index": "idx_comment_content_bigm",+ "455_drop_comment_content_trgm_index": "idx_comment_content_trgm",}var preMigrationHooks = func() map[string]preMigrationHook {@@ -397,9 +399,9 @@ func refuseChannelChatRouteHistoryRollbackWith(ctx context.Context, query rowQue}var upMigrationConditions = map[string]migrationCondition{- // Fresh databases that successfully built the CJK-friendly bigram index do- // not need to build the trigram fallback only to remove it at migration 371.- "140_comment_content_trgm_index": whenIndexNotUsable(commentContentBigramIndex),+ // Current search no longer consumes a comment-content GIN. Fresh installs+ // should not build the historical fallback only to retire it at migration 455.+ "140_comment_content_trgm_index": skipMigration("comment content search indexes are retired by migration 455"),// Existing pg_bigm deployments already have both indexes. Remove the// fallback only after proving the preferred index has the exact usable shape;// pg_bigm-less self-hosted databases keep trgm and record 371 as a no-op.@@ -408,7 +410,15 @@ var upMigrationConditions = map[string]migrationCondition{// requirement: build it where pg_bigm exists and record a no-op everywhere// else, rather than failing the run (and with it backend startup) on every// database without the extension.- "446_issue_properties_bigm_index": whenOperatorClassAvailable(issuePropertiesBigramOperatorClass),+ "446_issue_properties_bigm_index": whenOperatorClassAvailable(pgBigmOperatorClass),+}++// Migrations 454 and 455 restore the mutually exclusive comment search index+// selected before its retirement: pg_bigm deployments get the preferred bigram+// index, while pg_bigm-less self-hosted deployments get the trigram fallback.+var downMigrationConditions = map[string]migrationCondition{+ "454_drop_comment_content_bigm_index": whenOperatorClassAvailable(pgBigmOperatorClass),+ "455_drop_comment_content_trgm_index": whenOperatorClassUnavailable(pgBigmOperatorClass),}func hooksForDirection(direction string) map[string]preMigrationHook {@@ -438,12 +448,20 @@ func ensureSourceContextRollbackSafe(ctx context.Context, pool *pgxpool.Pool) er}func conditionsForDirection(direction string) map[string]migrationCondition {- if direction == "up" {+ switch direction {+ case "up":return upMigrationConditions+ case "down":+ return downMigrationConditions+ default:+ return nil+ }+}++func skipMigration(reason string) migrationCondition {+ return func(context.Context, *pgxpool.Conn) (bool, string, error) {+ return false, reason, nil}- // Rollbacks intentionally ignore environment gates: they restore the- // portable pre-migration schema regardless of which up SQL actually ran.- return nil}func whenIndexUsable(requirement usableIndexRequirement) migrationCondition {@@ -508,6 +526,20 @@ func whenOperatorClassAvailable(opclass extensionOperatorClass) migrationConditi}}+func whenOperatorClassUnavailable(opclass extensionOperatorClass) migrationCondition {+ availableCondition := whenOperatorClassAvailable(opclass)+ return func(ctx context.Context, conn *pgxpool.Conn) (bool, string, error) {+ available, _, err := availableCondition(ctx, conn)+ if err != nil {+ return false, "", err+ }+ if available {+ return false, fmt.Sprintf("operator class %s (%s) is installed", opclass.OperatorClass, opclass.Extension), nil+ }+ return true, "", nil+ }+}+// indexIsUsable fails closed: every property needed by the search query must// match before a fallback index may be skipped or removed. In particular, the// preferred relation must be a live, ready, valid, non-partial GIN expressiondiff --git a/server/cmd/migrate/migrate_comment_content_search_indexes_retirement_test.go b/server/cmd/migrate/migrate_comment_content_search_indexes_retirement_test.gonew file mode 100644index 0000000000..b0bcba9cdb--- /dev/null+++ b/server/cmd/migrate/migrate_comment_content_search_indexes_retirement_test.go@@ -0,0 +1,140 @@+package main++import (+ "context"+ "math/rand/v2"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgxpool"+)++func TestCommentContentSearchIndexesRetirement(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()++ if _, err := adminPool.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS pg_trgm"); err != nil {+ t.Fatalf("install pg_trgm test dependency: %v", err)+ }+ pgBigmUsable := installExtensionIfAvailable(t, ctx, adminPool, "pg_bigm")+ schema := createScratchSchema(t, ctx, adminPool, "migrate_comment_content_indexes_retirement_")+ pool := openTestPoolWithSearchPath(t, schema+", public")+ applyFallback, reason, err := upMigrationConditions["140_comment_content_trgm_index"](ctx, nil)+ if err != nil {+ t.Fatalf("evaluate retired fallback gate: %v", err)+ }+ if applyFallback || reason == "" {+ t.Fatalf("historical fallback gate = (%v, %q), want a documented skip", applyFallback, reason)+ }++ for _, statement := range []string{+ `CREATE TABLE schema_migrations (+ version TEXT PRIMARY KEY,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )`,+ `CREATE TABLE comment (+ id BIGSERIAL PRIMARY KEY,+ content TEXT NOT NULL+ )`,+ } {+ if _, err := pool.Exec(ctx, statement); err != nil {+ t.Fatalf("apply fixture statement: %v", err)+ }+ }++ if pgBigmUsable {+ if _, err := pool.Exec(ctx, `CREATE INDEX idx_comment_content_bigm+ ON comment USING gin (LOWER(content) gin_bigm_ops)`); err != nil {+ t.Fatalf("create pg_bigm fixture index: %v", err)+ }+ } else {+ // The up migration retires any same-named index defensively. A B-tree+ // stand-in keeps that path covered when CI does not provide pg_bigm.+ if _, err := pool.Exec(ctx, `CREATE INDEX idx_comment_content_bigm+ ON comment (LOWER(content))`); err != nil {+ t.Fatalf("create stand-in fixture index: %v", err)+ }+ }+ if _, err := pool.Exec(ctx, `CREATE INDEX idx_comment_content_trgm+ ON comment USING gin (LOWER(content) gin_trgm_ops)`); err != nil {+ t.Fatalf("create pg_trgm fixture index: %v", err)+ }++ versions := []string{+ "454_drop_comment_content_bigm_index",+ "455_drop_comment_content_trgm_index",+ }+ options := runOptions{+ Direction: "up",+ Files: realMigrationFiles(t, versions, "up"),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("up"),+ Conditions: conditionsForDirection("up"),+ }+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("apply comment content index retirement: %v", err)+ }+ assertIndexExists(t, pool, schema, "idx_comment_content_bigm", false)+ assertIndexExists(t, pool, schema, "idx_comment_content_trgm", false)+ for _, version := range versions {+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, true)+ }++ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("repeat comment content index retirement: %v", err)+ }+ assertIndexExists(t, pool, schema, "idx_comment_content_bigm", false)+ assertIndexExists(t, pool, schema, "idx_comment_content_trgm", false)++ options.Direction = "down"+ options.Files = realMigrationFiles(t, reversed(versions), "down")+ options.Hooks = hooksForDirection("down")+ options.Conditions = conditionsForDirection("down")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("roll back comment content index retirement: %v", err)+ }+ assertIndexExists(t, pool, schema, "idx_comment_content_bigm", pgBigmUsable)+ assertIndexExists(t, pool, schema, "idx_comment_content_trgm", !pgBigmUsable)+ if pgBigmUsable {+ assertUsableCommentContentIndex(t, ctx, pool, schema, "idx_comment_content_bigm", "gin_bigm_ops", "pg_bigm")+ } else {+ assertUsableCommentContentIndex(t, ctx, pool, schema, "idx_comment_content_trgm", "gin_trgm_ops", "pg_trgm")+ }+ for _, version := range versions {+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, false)+ }+}++func assertUsableCommentContentIndex(+ t *testing.T,+ ctx context.Context,+ pool *pgxpool.Pool,+ schema string,+ indexName string,+ opclass string,+ extension string,+) {+ t.Helper()+ conn, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatalf("acquire connection: %v", err)+ }+ defer conn.Release()++ usable, err := indexIsUsable(ctx, conn, usableIndexRequirement{+ IndexRegclass: schema + "." + indexName,+ TableRegclass: schema + ".comment",+ AccessMethod: "gin",+ OperatorClass: opclass,+ Expression: "lower(content)",+ Extension: extension,+ })+ if err != nil {+ t.Fatalf("inspect %s: %v", indexName, err)+ }+ if !usable {+ t.Fatalf("restored index %s does not match the historical search index shape", indexName)+ }+}diff --git a/server/cmd/migrate/migrate_issue_properties_bigm_index_test.go b/server/cmd/migrate/migrate_issue_properties_bigm_index_test.goindex 8e897b0749..cc768bd1e0 100644--- a/server/cmd/migrate/migrate_issue_properties_bigm_index_test.go+++ b/server/cmd/migrate/migrate_issue_properties_bigm_index_test.go@@ -285,7 +285,7 @@ func TestOperatorClassAvailabilityFailsClosed(t *testing.T) {{"wrong owning extension", extensionOperatorClass{"gin", "gin_trgm_ops", "pg_bigm"}, false},{"wrong access method", extensionOperatorClass{"btree", "gin_trgm_ops", "pg_trgm"}, false},{"unknown opclass", extensionOperatorClass{"gin", "gin_nonexistent_ops", "pg_trgm"}, false},- {"migration 446 gate", issuePropertiesBigramOperatorClass, pgBigmUsable},+ {"pg_bigm migration gate", pgBigmOperatorClass, pgBigmUsable},} {t.Run(tc.name, func(t *testing.T) {apply, reason, err := whenOperatorClassAvailable(tc.opclass)(ctx, conn)@@ -300,6 +300,17 @@ func TestOperatorClassAvailabilityFailsClosed(t *testing.T) {}})}++ apply, reason, err := whenOperatorClassUnavailable(pgBigmOperatorClass)(ctx, conn)+ if err != nil {+ t.Fatalf("evaluate unavailable condition: %v", err)+ }+ if apply != !pgBigmUsable {+ t.Fatalf("unavailable apply=%v (%s), want %v", apply, reason, !pgBigmUsable)+ }+ if !apply && reason == "" {+ t.Fatal("an unavailable-condition skip must report why")+ }}// installExtensionIfAvailable installs name when the server ships it anddiff --git a/server/cmd/migrate/migrate_mul5999_index_retry_test.go b/server/cmd/migrate/migrate_mul5999_index_retry_test.goindex eec875a222..0707ce817a 100644--- a/server/cmd/migrate/migrate_mul5999_index_retry_test.go+++ b/server/cmd/migrate/migrate_mul5999_index_retry_test.go@@ -18,6 +18,9 @@ import (var concurrentIndexNamePattern = regexp.MustCompile(`(?i)CREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-z0-9_]+)`)+var pgBigmConcurrentIndexPattern = regexp.MustCompile(+ `(?is)CREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\b[^;]*\bgin_bigm_ops\b`)+// stripSQLLineComments drops `--` comment lines so prose that mentions SQL is// not mistaken for SQL.func stripSQLLineComments(body []byte) []byte {@@ -85,6 +88,30 @@ func TestEveryConcurrentUpBuildHasCleanup(t *testing.T) {assertEveryConcurrentBuildHasCleanup(t, "up", concurrentIndexCleanups)}+// pg_bigm is optional, so every rollback that names its operator class in a+// concurrent build must be gated. Otherwise a pg_bigm-less self-hosted database+// can fail during startup merely because an operator class is unavailable.+func TestEveryPGBigmConcurrentDownBuildHasCondition(t *testing.T) {+ paths, err := filepath.Glob(filepath.Join("..", "..", "migrations", "*.down.sql"))+ if err != nil {+ t.Fatalf("glob down migrations: %v", err)+ }+ for _, path := range paths {+ body, err := os.ReadFile(path)+ if err != nil {+ t.Errorf("%s: read: %v", path, err)+ continue+ }+ if !pgBigmConcurrentIndexPattern.Match(stripSQLLineComments(body)) {+ continue+ }+ version := strings.TrimSuffix(filepath.Base(path), ".down.sql")+ if downMigrationConditions[version] == nil {+ t.Errorf("%s: builds a pg_bigm index concurrently on down but has no down condition", version)+ }+ }+}+func assertEveryConcurrentBuildHasCleanup(t *testing.T, direction string, cleanups map[string]string) {t.Helper()suffix := "." + direction + ".sql"diff --git a/server/migrations/454_drop_comment_content_bigm_index.down.sql b/server/migrations/454_drop_comment_content_bigm_index.down.sqlnew file mode 100644index 0000000000..0fdfe7fe65--- /dev/null+++ b/server/migrations/454_drop_comment_content_bigm_index.down.sql@@ -0,0 +1,4 @@+-- Restore migration 036's preferred comment search index where pg_bigm is+-- available. The migration runner skips this statement in other environments.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_content_bigm+ ON comment USING gin (LOWER(content) gin_bigm_ops);diff --git a/server/migrations/454_drop_comment_content_bigm_index.up.sql b/server/migrations/454_drop_comment_content_bigm_index.up.sqlnew file mode 100644index 0000000000..5731ac275d--- /dev/null+++ b/server/migrations/454_drop_comment_content_bigm_index.up.sql@@ -0,0 +1,3 @@+-- SearchIssues now scans comments by workspace and evaluates content matches+-- during aggregation, so this global content GIN is no longer read.+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_bigm;diff --git a/server/migrations/455_drop_comment_content_trgm_index.down.sql b/server/migrations/455_drop_comment_content_trgm_index.down.sqlnew file mode 100644index 0000000000..1d8029acdc--- /dev/null+++ b/server/migrations/455_drop_comment_content_trgm_index.down.sql@@ -0,0 +1,4 @@+-- pg_bigm deployments restore the preferred index in migration 454 instead.+-- The runner executes this only where pg_bigm is unavailable.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_content_trgm+ ON comment USING gin (LOWER(content) gin_trgm_ops);diff --git a/server/migrations/455_drop_comment_content_trgm_index.up.sql b/server/migrations/455_drop_comment_content_trgm_index.up.sqlnew file mode 100644index 0000000000..1999b5661b--- /dev/null+++ b/server/migrations/455_drop_comment_content_trgm_index.up.sql@@ -0,0 +1,3 @@+-- Retire the portable fallback for the same workspace-first SearchIssues path.+-- Keep this separate because concurrent index DDL must be the only statement.+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_trgm;