Skip to content

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

Go

MUL-6456: make comment search indexes mutually exclusive (#7288)

Multica Evefa805238f551
diff --git a/CLAUDE.md b/CLAUDE.md
index ebf0cfed95..10ca86a14f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -106,6 +106,7 @@ These are hard requirements for every new or modified database design and produc
- Do not add database foreign keys (`FOREIGN KEY` / `REFERENCES`), cascading deletes, or cascading updates. Resolve relationships, validation, and dependent cleanup explicitly in application code. Use an application transaction when cleanup and the parent operation must commit or roll back atomically.
- Every index created by a migration must use `CREATE INDEX CONCURRENTLY` or `CREATE UNIQUE INDEX CONCURRENTLY`, including indexes on newly created tables. PostgreSQL rejects concurrent index creation inside a transaction or a multi-command string, so keep each concurrent index build in its own single-statement migration file. The repository migration runner executes migration files outside an explicit transaction to support this.
+- A conditionally skipped migration is still recorded in `schema_migrations`, so the ledger proves ordering, not that every migration's SQL executed. Later migrations that touch conditionally present objects must use idempotent DDL such as `IF EXISTS` / `IF NOT EXISTS`, and the introducing change must document recovery when losing the selected object would break runtime behavior.
## Coding Rules
diff --git a/server/cmd/migrate/README.md b/server/cmd/migrate/README.md
new file mode 100644
index 0000000000..9a175a1d29
--- /dev/null
+++ b/server/cmd/migrate/README.md
@@ -0,0 +1,39 @@
+# Migration runner operations
+
+## Recover the comment content search index
+
+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.
+
+First check whether either index is live, ready, and valid:
+
+```sql
+SELECT indexrelid::regclass AS index_name, indisvalid, indisready, indislive
+FROM pg_index
+WHERE indexrelid IN (
+ to_regclass('idx_comment_content_bigm'),
+ to_regclass('idx_comment_content_trgm')
+);
+```
+
+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.
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 2b96705599..ffc5551f21 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -28,6 +28,35 @@ import (
// retries the hook + migration.
type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error
+// migrationCondition decides whether a pending migration's SQL should execute.
+// A false result still records the migration as applied (or rolled back), which
+// lets one migration encode environment-specific DDL without blocking later
+// versions. Conditions must be read-only and idempotent; schema changes belong
+// in the migration file so they remain visible to review and rollback tooling.
+type migrationCondition func(ctx context.Context, conn *pgxpool.Conn) (apply bool, reason string, err error)
+
+// usableIndexRequirement describes the exact index shape that may replace a
+// fallback. Checking only extension or relation existence is unsafe: historical
+// pg_bigm migrations swallowed CREATE INDEX errors, and an interrupted
+// concurrent build can leave an INVALID relation with the expected name.
+type usableIndexRequirement struct {
+ IndexRegclass string
+ TableRegclass string
+ AccessMethod string
+ OperatorClass string
+ Expression string
+ Extension string
+}
+
+var commentContentBigramIndex = usableIndexRequirement{
+ IndexRegclass: "public.idx_comment_content_bigm",
+ TableRegclass: "public.comment",
+ AccessMethod: "gin",
+ OperatorClass: "gin_bigm_ops",
+ Expression: "lower(content)",
+ Extension: "pg_bigm",
+}
+
// preMigrationHooks wires migration version → hook. The version key is
// the file basename without the `.up.sql` suffix, matching what
// `migrations.ExtractVersion` returns.
@@ -227,6 +256,7 @@ var concurrentDownIndexCleanups = map[string]string{
"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",
"312_drop_global_plugin_identity_key_index": "idx_plugin_identity_key",
+ "371_comment_content_search_index_strategy": "idx_comment_content_trgm",
}
var preMigrationHooks = func() map[string]preMigrationHook {
@@ -248,6 +278,16 @@ var preRollbackHooks = func() map[string]preMigrationHook {
return hooks
}()
+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),
+ // 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.
+ "371_comment_content_search_index_strategy": whenIndexUsable(commentContentBigramIndex),
+}
+
func hooksForDirection(direction string) map[string]preMigrationHook {
switch direction {
case "up":
@@ -259,6 +299,98 @@ func hooksForDirection(direction string) map[string]preMigrationHook {
}
}
+func conditionsForDirection(direction string) map[string]migrationCondition {
+ if direction == "up" {
+ return upMigrationConditions
+ }
+ // 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 {
+ return func(ctx context.Context, conn *pgxpool.Conn) (bool, string, error) {
+ usable, err := indexIsUsable(ctx, conn, requirement)
+ if err != nil {
+ return false, "", err
+ }
+ if !usable {
+ return false, fmt.Sprintf("preferred index %s is unavailable or unusable", requirement.IndexRegclass), nil
+ }
+ return true, "", nil
+ }
+}
+
+func whenIndexNotUsable(requirement usableIndexRequirement) migrationCondition {
+ return func(ctx context.Context, conn *pgxpool.Conn) (bool, string, error) {
+ usable, err := indexIsUsable(ctx, conn, requirement)
+ if err != nil {
+ return false, "", err
+ }
+ if usable {
+ return false, fmt.Sprintf("preferred index %s is ready", requirement.IndexRegclass), 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 expression
+// index owned by the expected extension. A same-named stale or drifted index is
+// treated as unusable, preserving the fallback.
+func indexIsUsable(ctx context.Context, conn *pgxpool.Conn, requirement usableIndexRequirement) (bool, error) {
+ var usable bool
+ err := conn.QueryRow(ctx, `
+ SELECT COALESCE(
+ idx.relkind = 'i'
+ AND i.indisvalid
+ AND i.indisready
+ AND i.indislive
+ AND NOT i.indisunique
+ AND i.indpred IS NULL
+ AND i.indexprs IS NOT NULL
+ AND i.indrelid = to_regclass($2)
+ AND i.indnkeyatts = 1
+ AND i.indnatts = 1
+ AND am.amname = $3
+ AND opc.opcname = $4
+ AND pg_get_indexdef(i.indexrelid, 1, FALSE) = $5
+ AND EXISTS (
+ SELECT 1
+ FROM pg_depend dep
+ JOIN pg_extension ext ON ext.oid = dep.refobjid
+ WHERE dep.classid = 'pg_opclass'::regclass
+ AND dep.objid = opc.oid
+ AND dep.refclassid = 'pg_extension'::regclass
+ AND dep.deptype = 'e'
+ AND ext.extname = $6
+ ),
+ FALSE
+ )
+ FROM pg_class idx
+ LEFT JOIN pg_index i ON i.indexrelid = idx.oid
+ LEFT JOIN pg_am am ON am.oid = idx.relam
+ -- pg_index.indclass is an int2vector, whose subscripts start at zero.
+ LEFT JOIN pg_opclass opc ON opc.oid = i.indclass[0]
+ WHERE idx.oid = to_regclass($1)
+ `,
+ requirement.IndexRegclass,
+ requirement.TableRegclass,
+ requirement.AccessMethod,
+ requirement.OperatorClass,
+ requirement.Expression,
+ requirement.Extension,
+ ).Scan(&usable)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, fmt.Errorf("inspect preferred index %q: %w", requirement.IndexRegclass, err)
+ }
+ return usable, 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
@@ -374,6 +506,11 @@ type runOptions struct {
// passes the direction-specific hook map; tests leave this nil unless they
// exercise a hook.
Hooks map[string]preMigrationHook
+ // Conditions maps migration version → a read-only gate that decides
+ // whether the SQL file should execute. A false result still advances the
+ // migration ledger, allowing later migrations to run in environments where
+ // this version's DDL is intentionally unnecessary.
+ Conditions map[string]migrationCondition
}
func main() {
@@ -415,9 +552,10 @@ func main() {
}
if err := runMigrations(ctx, pool, runOptions{
- Direction: direction,
- Files: files,
- Hooks: hooksForDirection(direction),
+ Direction: direction,
+ Files: files,
+ Hooks: hooksForDirection(direction),
+ Conditions: conditionsForDirection(direction),
}); err != nil {
slog.Error("migration run failed", "error", err)
os.Exit(1)
@@ -542,8 +680,19 @@ func runMigrations(ctx context.Context, pool *pgxpool.Pool, opts runOptions) err
}
}
- if _, err := conn.Exec(ctx, string(sql)); err != nil {
- return fmt.Errorf("apply migration %q: %w", file, err)
+ applySQL := true
+ conditionReason := ""
+ if condition, ok := opts.Conditions[version]; ok && condition != nil {
+ applySQL, conditionReason, err = condition(ctx, conn)
+ if err != nil {
+ return fmt.Errorf("evaluate migration condition for %q (%s): %w", version, opts.Direction, err)
+ }
+ }
+
+ if applySQL {
+ if _, err := conn.Exec(ctx, string(sql)); err != nil {
+ return fmt.Errorf("apply migration %q: %w", file, err)
+ }
}
if opts.Direction == "up" {
@@ -555,7 +704,11 @@ func runMigrations(ctx context.Context, pool *pgxpool.Pool, opts runOptions) err
return fmt.Errorf("record migration %q: %w", version, err)
}
- fmt.Printf(" %s %s\n", opts.Direction, version)
+ if applySQL {
+ fmt.Printf(" %s %s\n", opts.Direction, version)
+ } else {
+ fmt.Printf(" %s %s (SQL skipped: %s)\n", opts.Direction, version, conditionReason)
+ }
}
return nil
diff --git a/server/cmd/migrate/migrate_comment_search_index_strategy_test.go b/server/cmd/migrate/migrate_comment_search_index_strategy_test.go
new file mode 100644
index 0000000000..64f9e2396c
--- /dev/null
+++ b/server/cmd/migrate/migrate_comment_search_index_strategy_test.go
@@ -0,0 +1,228 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+)
+
+func TestCommentSearchIndexStrategyChoosesOneUsableIndexPerEnvironment(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)
+ }
+
+ tests := []struct {
+ name string
+ createPreferred string
+ createFallback bool
+ versions []string
+ wantFallbackAfter bool
+ }{
+ {
+ name: "self-host without preferred index builds and keeps fallback",
+ versions: []string{"140_comment_content_trgm_index", "371_comment_content_search_index_strategy"},
+ wantFallbackAfter: true,
+ },
+ {
+ name: "fresh pg_bigm-like environment skips fallback build",
+ createPreferred: `CREATE INDEX idx_comment_content_bigm
+ ON comment USING gin (LOWER(content) public.gin_trgm_ops)`,
+ versions: []string{"140_comment_content_trgm_index", "371_comment_content_search_index_strategy"},
+ },
+ {
+ name: "existing deployment with both indexes drops fallback",
+ createPreferred: `CREATE INDEX idx_comment_content_bigm
+ ON comment USING gin (LOWER(content) public.gin_trgm_ops)`,
+ createFallback: true,
+ versions: []string{"371_comment_content_search_index_strategy"},
+ },
+ {
+ name: "same-named but wrong preferred index preserves fallback",
+ createPreferred: `CREATE INDEX idx_comment_content_bigm
+ ON comment (LOWER(content))`,
+ versions: []string{"140_comment_content_trgm_index", "371_comment_content_search_index_strategy"},
+ wantFallbackAfter: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
+ schema := "migrate_comment_search_" + 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+", public")
+ if _, err := pool.Exec(ctx, `CREATE TABLE comment (
+ id BIGSERIAL PRIMARY KEY,
+ content TEXT NOT NULL
+ )`); err != nil {
+ t.Fatalf("create comment fixture: %v", err)
+ }
+ if tt.createPreferred != "" {
+ if _, err := pool.Exec(ctx, tt.createPreferred); err != nil {
+ t.Fatalf("create preferred fixture index: %v", err)
+ }
+ }
+ if tt.createFallback {
+ if _, err := pool.Exec(ctx, `CREATE INDEX idx_comment_content_trgm
+ ON comment USING gin (LOWER(content) public.gin_trgm_ops)`); err != nil {
+ t.Fatalf("create fallback fixture index: %v", err)
+ }
+ }
+
+ requirement := usableIndexRequirement{
+ IndexRegclass: schema + ".idx_comment_content_bigm",
+ TableRegclass: schema + ".comment",
+ AccessMethod: "gin",
+ OperatorClass: "gin_trgm_ops",
+ Expression: "lower(content)",
+ Extension: "pg_trgm",
+ }
+ conditions := map[string]migrationCondition{
+ "140_comment_content_trgm_index": whenIndexNotUsable(requirement),
+ "371_comment_content_search_index_strategy": whenIndexUsable(requirement),
+ }
+ migrationsTable := schema + ".schema_migrations"
+ if err := runMigrations(ctx, pool, runOptions{
+ Direction: "up",
+ Files: realMigrationFiles(t, tt.versions, "up"),
+ SchemaMigrationsTable: migrationsTable,
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("up"),
+ Conditions: conditions,
+ }); err != nil {
+ t.Fatalf("apply search index strategy: %v", err)
+ }
+
+ assertIndexExists(t, pool, schema, "idx_comment_content_trgm", tt.wantFallbackAfter)
+ if tt.createPreferred != "" {
+ assertIndexExists(t, pool, schema, "idx_comment_content_bigm", true)
+ }
+ for _, version := range tt.versions {
+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, true)
+ }
+
+ // Rollback always restores the portable fallback. On a self-hosted
+ // database where it was retained, IF NOT EXISTS makes this a no-op.
+ if err := runMigrations(ctx, pool, runOptions{
+ Direction: "down",
+ Files: realMigrationFiles(t, []string{"371_comment_content_search_index_strategy"}, "down"),
+ SchemaMigrationsTable: migrationsTable,
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("down"),
+ }); err != nil {
+ t.Fatalf("roll back search index strategy: %v", err)
+ }
+ assertIndexValidity(t, pool, schema, "idx_comment_content_trgm", true)
+ assertMigrationVersionRecorded(t, ctx, pool, schema, "371_comment_content_search_index_strategy", false)
+ })
+ }
+}
+
+func TestCommentContentBigramRequirementMatchesRealPGBigm(t *testing.T) {
+ adminPool := openTestPool(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+
+ var available bool
+ if err := adminPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_available_extensions
+ WHERE name = 'pg_bigm'
+ )
+ `).Scan(&available); err != nil {
+ t.Fatalf("inspect pg_bigm availability: %v", err)
+ }
+ if !available {
+ t.Skip("Postgres does not provide pg_bigm; install it to run the real-opclass integration test")
+ }
+ if _, err := adminPool.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS pg_bigm"); err != nil {
+ t.Fatalf("install pg_bigm test dependency: %v", err)
+ }
+
+ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
+ schema := "migrate_comment_bigm_" + 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+", public")
+ if _, err := pool.Exec(ctx, `CREATE TABLE comment (
+ id BIGSERIAL PRIMARY KEY,
+ content TEXT NOT NULL
+ )`); err != nil {
+ t.Fatalf("create comment fixture: %v", err)
+ }
+ 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 real pg_bigm fixture index: %v", err)
+ }
+
+ requirement := commentContentBigramIndex
+ requirement.IndexRegclass = schema + ".idx_comment_content_bigm"
+ requirement.TableRegclass = schema + ".comment"
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+
+ usable, err := indexIsUsable(ctx, conn, requirement)
+ if err != nil {
+ t.Fatalf("inspect real pg_bigm index: %v", err)
+ }
+ if !usable {
+ t.Fatal("production pg_bigm requirement did not match a real gin_bigm_ops index")
+ }
+}
+
+func assertMigrationVersionRecorded(
+ t *testing.T,
+ ctx context.Context,
+ pool interface {
+ QueryRow(context.Context, string, ...any) pgx.Row
+ },
+ schema string,
+ version string,
+ want bool,
+) {
+ t.Helper()
+ var recorded bool
+ migrationsTable := pgx.Identifier{schema, "schema_migrations"}.Sanitize()
+ if err := pool.QueryRow(ctx,
+ "SELECT EXISTS (SELECT 1 FROM "+migrationsTable+" WHERE version = $1)",
+ version,
+ ).Scan(&recorded); err != nil {
+ t.Fatalf("read migration version %s: %v", version, err)
+ }
+ if recorded != want {
+ t.Fatalf("migration %s recorded = %v, want %v", version, recorded, want)
+ }
+}
diff --git a/server/migrations/371_comment_content_search_index_strategy.down.sql b/server/migrations/371_comment_content_search_index_strategy.down.sql
new file mode 100644
index 0000000000..27549529fa
--- /dev/null
+++ b/server/migrations/371_comment_content_search_index_strategy.down.sql
@@ -0,0 +1,4 @@
+-- Restore the portable fallback when rolling back the mutually exclusive
+-- comment search index strategy.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_content_trgm
+ ON comment USING gin (LOWER(content) gin_trgm_ops);
diff --git a/server/migrations/371_comment_content_search_index_strategy.up.sql b/server/migrations/371_comment_content_search_index_strategy.up.sql
new file mode 100644
index 0000000000..3c4a3399fb
--- /dev/null
+++ b/server/migrations/371_comment_content_search_index_strategy.up.sql
@@ -0,0 +1,8 @@
+-- The migration runner executes this only when the CJK-friendly
+-- idx_comment_content_bigm index has the exact valid and ready shape used by
+-- SearchIssues. pg_bigm-less self-hosted deployments skip this statement and
+-- retain the trigram fallback.
+-- If the preferred index later becomes unusable, follow the recovery procedure
+-- in server/cmd/migrate/README.md; this migration is already recorded and will
+-- not recreate the fallback automatically.
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_content_trgm;