Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(search): pg_trgm index fallback + statement_timeout guard (MUL-4059) (#4925)
Multica Eve359ef61dc360
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex efcc1dd766..cdf842631e 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -16,6 +16,7 @@ import ("unicode""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/logger"@@ -421,20 +422,34 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,// --- WHERE clause ---var whereParts []string- // Full phrase match: title, description, or comment+ // Full phrase match: title, description, or comment.+ //+ // The comment EXISTS subquery is deliberately correlated on BOTH+ // c.issue_id = i.id AND c.workspace_id = wsParam. The workspace_id+ // filter is not strictly necessary for correctness (comment.workspace_id+ // is FK-consistent with its issue's workspace), but it is critical for+ // the planner. Without it, Postgres rewrites the correlated EXISTS+ // into a hashed subplan that materializes every comment in the entire+ // `comment` table matching the LIKE — for common tokens like "search"+ // this can be hundreds of thousands of rows, blowing out work_mem into+ // a lossy bitmap and taking 30+ seconds. With the workspace_id+ // constant duplicated into the subquery, the hashed set collapses to+ // this workspace's comments and the plan uses the supporting+ // idx_comment_workspace (migration 135). See MUL-4059 EXPLAIN reports.phraseMatch := fmt.Sprintf(- "(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s))",- phraseContainsParam, phraseContainsParam, phraseContainsParam,+ "(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND c.workspace_id = %s AND LOWER(c.content) LIKE %s))",+ phraseContainsParam, phraseContainsParam, wsParam, phraseContainsParam,)whereParts = append(whereParts, phraseMatch)- // Multi-word AND match (each term must appear somewhere)+ // Multi-word AND match (each term must appear somewhere). Same+ // workspace_id-in-subquery contract as above.if len(termContainsParams) > 1 {var termConditions []stringfor _, tp := range termContainsParams {termConditions = append(termConditions, fmt.Sprintf(- "(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s))",- tp, tp, tp,+ "(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND c.workspace_id = %s AND LOWER(c.content) LIKE %s))",+ tp, tp, wsParam, tp,))}whereParts = append(whereParts, "("+strings.Join(termConditions, " AND ")+")")@@ -492,8 +507,9 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 6", strings.Join(descTerms, " AND ")))}- // Tier 7: Comment contains phrase- rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s) THEN 7", phraseContainsParam))+ // Tier 7: Comment contains phrase. Same workspace_id-in-subquery+ // contract as the WHERE clause; see the phraseMatch comment above.+ rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND c.workspace_id = %s AND LOWER(c.content) LIKE %s) THEN 7", wsParam, phraseContainsParam))// Tier 8: Comment matches all words (multi-word only)if len(termContainsParams) > 1 {@@ -501,7 +517,7 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,for _, tp := range termContainsParams {commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))}- rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND (%s)) THEN 8", strings.Join(commentTerms, " AND ")))+ rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND c.workspace_id = %s AND (%s)) THEN 8", wsParam, strings.Join(commentTerms, " AND ")))}rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 9 END"@@ -548,12 +564,15 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,// --- matched_comment_content subquery ---// Always return matching comment content regardless of match_source,// so frontend can display comment snippet alongside title/description matches.+ // The c.workspace_id filter mirrors the WHERE clause: without it,+ // the planner can pick a global comment scan that ignores workspace+ // scoping.commentSubquery := fmt.Sprintf(`COALESCE((SELECT c.content FROM comment c- WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s+ WHERE c.issue_id = i.id AND c.workspace_id = %s AND LOWER(c.content) LIKE %sORDER BY c.created_at DESC LIMIT 1),''- )`, phraseContainsParam)+ )`, wsParam, phraseContainsParam)if len(termContainsParams) > 1 {var commentTerms []string@@ -562,10 +581,10 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,}commentSubquery = fmt.Sprintf(`COALESCE((SELECT c.content FROM comment c- WHERE c.issue_id = i.id AND (LOWER(c.content) LIKE %s OR (%s))+ WHERE c.issue_id = i.id AND c.workspace_id = %s AND (LOWER(c.content) LIKE %s OR (%s))ORDER BY c.created_at DESC LIMIT 1),''- )`, phraseContainsParam, strings.Join(commentTerms, " AND "))+ )`, wsParam, phraseContainsParam, strings.Join(commentTerms, " AND "))}limitParam := nextArg(nil) // placeholder@@ -636,50 +655,56 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {args[len(args)-2] = limitargs[len(args)-1] = offset- rows, err := h.DB.Query(ctx, sqlQuery, args...)- if err != nil {- slog.Warn("search issues failed", "error", err, "workspace_id", workspaceID, "query", q)- writeError(w, http.StatusInternalServerError, "failed to search issues")- return- }- defer rows.Close()-var results []searchResult- for rows.Next() {- var sr searchResult- if err := rows.Scan(- &sr.issue.ID,- &sr.issue.WorkspaceID,- &sr.issue.Title,- &sr.issue.Description,- &sr.issue.Status,- &sr.issue.Priority,- &sr.issue.AssigneeType,- &sr.issue.AssigneeID,- &sr.issue.CreatorType,- &sr.issue.CreatorID,- &sr.issue.ParentIssueID,- &sr.issue.AcceptanceCriteria,- &sr.issue.ContextRefs,- &sr.issue.Position,- &sr.issue.StartDate,- &sr.issue.DueDate,- &sr.issue.CreatedAt,- &sr.issue.UpdatedAt,- &sr.issue.Number,- &sr.issue.ProjectID,- &sr.totalCount,- &sr.matchSource,- &sr.matchedCommentContent,- ); err != nil {- slog.Warn("search issues scan failed", "error", err)- writeError(w, http.StatusInternalServerError, "failed to search issues")+ err := runSearchQuery(ctx, h.TxStarter, sqlQuery, args, func(rows pgx.Rows) error {+ for rows.Next() {+ var sr searchResult+ if err := rows.Scan(+ &sr.issue.ID,+ &sr.issue.WorkspaceID,+ &sr.issue.Title,+ &sr.issue.Description,+ &sr.issue.Status,+ &sr.issue.Priority,+ &sr.issue.AssigneeType,+ &sr.issue.AssigneeID,+ &sr.issue.CreatorType,+ &sr.issue.CreatorID,+ &sr.issue.ParentIssueID,+ &sr.issue.AcceptanceCriteria,+ &sr.issue.ContextRefs,+ &sr.issue.Position,+ &sr.issue.StartDate,+ &sr.issue.DueDate,+ &sr.issue.CreatedAt,+ &sr.issue.UpdatedAt,+ &sr.issue.Number,+ &sr.issue.ProjectID,+ &sr.totalCount,+ &sr.matchSource,+ &sr.matchedCommentContent,+ ); err != nil {+ return fmt.Errorf("scan: %w", err)+ }+ results = append(results, sr)+ }+ return rows.Err()+ })+ if err != nil {+ // Statement-timeout surfaces as SQLSTATE 57014. Return a 503+ // so the frontend can distinguish a timeout ("try a more+ // specific query") from a generic 500. This is the fail-fast+ // path when GIN search indexes are absent or the database is+ // overloaded; see runSearchQuery header for context.+ if isSearchStatementTimeout(err) {+ slog.Warn("search issues timed out",+ "workspace_id", workspaceID,+ "query", q,+ "timeout", searchStatementTimeout)+ writeError(w, http.StatusServiceUnavailable, "search timed out; please refine your query or try again")return}- results = append(results, sr)- }- if err := rows.Err(); err != nil {- slog.Warn("search issues rows error", "error", err)+ slog.Warn("search issues failed", "error", err, "workspace_id", workspaceID, "query", q)writeError(w, http.StatusInternalServerError, "failed to search issues")return}diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 68b21d30f5..11b93915fb 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -11,6 +11,7 @@ import ("strings""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -709,14 +710,6 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {args[len(args)-2] = limitargs[len(args)-1] = offset- rows, err := h.DB.Query(ctx, sqlQuery, args...)- if err != nil {- slog.Warn("search projects failed", "error", err, "workspace_id", workspaceID, "query", q)- writeError(w, http.StatusInternalServerError, "failed to search projects")- return- }- defer rows.Close()-type projectSearchRow struct {project db.ProjecttotalCount int64@@ -724,31 +717,42 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {}var results []projectSearchRow- for rows.Next() {- var row projectSearchRow- if err := rows.Scan(- &row.project.ID,- &row.project.WorkspaceID,- &row.project.Title,- &row.project.Description,- &row.project.Icon,- &row.project.Status,- &row.project.Priority,- &row.project.LeadType,- &row.project.LeadID,- &row.project.CreatedAt,- &row.project.UpdatedAt,- &row.totalCount,- &row.matchSource,- ); err != nil {- slog.Warn("search projects scan failed", "error", err)- writeError(w, http.StatusInternalServerError, "failed to search projects")+ err := runSearchQuery(ctx, h.TxStarter, sqlQuery, args, func(rows pgx.Rows) error {+ for rows.Next() {+ var row projectSearchRow+ if err := rows.Scan(+ &row.project.ID,+ &row.project.WorkspaceID,+ &row.project.Title,+ &row.project.Description,+ &row.project.Icon,+ &row.project.Status,+ &row.project.Priority,+ &row.project.LeadType,+ &row.project.LeadID,+ &row.project.CreatedAt,+ &row.project.UpdatedAt,+ &row.totalCount,+ &row.matchSource,+ ); err != nil {+ return fmt.Errorf("scan: %w", err)+ }+ results = append(results, row)+ }+ return rows.Err()+ })+ if err != nil {+ // Statement-timeout surfaces as SQLSTATE 57014 — same+ // fail-fast contract as SearchIssues (see runSearchQuery).+ if isSearchStatementTimeout(err) {+ slog.Warn("search projects timed out",+ "workspace_id", workspaceID,+ "query", q,+ "timeout", searchStatementTimeout)+ writeError(w, http.StatusServiceUnavailable, "search timed out; please refine your query or try again")return}- results = append(results, row)- }- if err := rows.Err(); err != nil {- slog.Warn("search projects rows error", "error", err)+ slog.Warn("search projects failed", "error", err, "workspace_id", workspaceID, "query", q)writeError(w, http.StatusInternalServerError, "failed to search projects")return}diff --git a/server/internal/handler/search.go b/server/internal/handler/search.gonew file mode 100644index 0000000000..84a194f30d--- /dev/null+++ b/server/internal/handler/search.go@@ -0,0 +1,121 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+)++// searchStatementTimeout bounds every /search request at the Postgres level.+//+// The two search handlers (SearchIssues, SearchProjects) run LOWER(col) LIKE+// '%pattern%' queries whose fast path depends on pg_bigm / pg_trgm GIN+// indexes (see migrations 032, 033, 036, 134). When those extensions are+// missing — as they were on every self-hosted deployment using the bundled+// pgvector/pgvector:pg17 image before migration 134 shipped — Postgres+// falls back to a Seq Scan on `issue` plus correlated Seq Scans on+// `comment`. On workspaces with thousands of rows the query takes long+// enough that the frontend Loader2 spinner appears to hang forever+// ("搜索卡死没有任何反应", MUL-4059).+//+// The 3 s cap is generous compared to a properly indexed search (typically+// <50 ms) and short enough that the frontend's implicit request timeout+// (browser default, ~30 s) never kicks in. On timeout the caller sees a+// 503 with a descriptive error rather than a stalled connection —+// SearchIssues / SearchProjects map SQLSTATE 57014 to+// http.StatusServiceUnavailable so the frontend can distinguish this+// from a generic 500.+const searchStatementTimeout = 3 * time.Second++// searchStatementTimeoutOverride, when non-zero, replaces+// searchStatementTimeout for the duration of a test. Never read outside+// of the runSearchQuery hot path — see search_timeout_test.go.+var searchStatementTimeoutOverride time.Duration++func effectiveSearchStatementTimeout() time.Duration {+ if searchStatementTimeoutOverride > 0 {+ return searchStatementTimeoutOverride+ }+ return searchStatementTimeout+}++// runSearchQuery executes a search SQL query inside a short-lived read-only+// transaction with SET LOCAL statement_timeout as the safety net. rowsFn+// receives each pgx.Rows result and is responsible for scanning /+// accumulating results before returning; runSearchQuery handles+// commit / rollback and returns the first error encountered.+//+// tx uses IsoLevel ReadCommitted (Postgres default) and AccessMode ReadOnly+// so a stuck search cannot hold row locks against writers.+func runSearchQuery(+ ctx context.Context,+ txStarter txStarter,+ sql string,+ args []any,+ rowsFn func(pgx.Rows) error,+) error {+ tx, err := txStarter.Begin(ctx)+ if err != nil {+ return fmt.Errorf("begin search tx: %w", err)+ }+ committed := false+ defer func() {+ if !committed {+ // Best-effort rollback with a fresh context so a caller+ // cancellation still lets the connection go back clean.+ _ = tx.Rollback(context.Background())+ }+ }()++ // SET LOCAL is transaction-scoped, so pgxpool can safely hand this+ // connection back out after COMMIT without the timeout leaking to+ // unrelated queries.+ timeoutMs := int(effectiveSearchStatementTimeout() / time.Millisecond)+ if _, err := tx.Exec(ctx, fmt.Sprintf("SET LOCAL statement_timeout = %d", timeoutMs)); err != nil {+ return fmt.Errorf("set search statement_timeout: %w", err)+ }+ // The read-only mode is applied here rather than via TxOptions so we+ // keep the txStarter interface signature (Begin only) intact. It's+ // belt-and-suspenders — the search queries only SELECT anyway.+ if _, err := tx.Exec(ctx, "SET LOCAL transaction_read_only = on"); err != nil {+ return fmt.Errorf("set search transaction_read_only: %w", err)+ }++ rows, err := tx.Query(ctx, sql, args...)+ if err != nil {+ return err+ }+ // Close rows before commit so pgx does not complain about a busy+ // connection during Commit.+ if err := rowsFn(rows); err != nil {+ rows.Close()+ return err+ }+ rows.Close()++ if err := tx.Commit(ctx); err != nil {+ return err+ }+ committed = true+ return nil+}++// isSearchStatementTimeout reports whether err is the canonical Postgres+// query_canceled error (SQLSTATE 57014). Both `SET LOCAL statement_timeout`+// firing and a client-side context cancellation surface as 57014 — the two+// are indistinguishable from the client side, which is intentional in the+// pgx layer.+func isSearchStatementTimeout(err error) bool {+ if err == nil {+ return false+ }+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) {+ return pgErr.Code == "57014"+ }+ return false+}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex e27af9abdc..f8309a7d5f 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -255,3 +255,42 @@ func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {t.Error("single-term query should not have tier 8 (comment all-terms)")}}++// TestBuildSearchQuery_CommentSubqueryWorkspaceScope regressions the+// MUL-4059 fix: every EXISTS / correlated subquery over `comment` MUST+// filter by c.workspace_id = $wsParam. Without this, Postgres rewrites+// the correlated subquery into a hashed subplan that materializes every+// comment in the entire table matching the LIKE — on prd this was+// 536k rows / 32.3 s for '%search%'. With the filter the hashed set+// collapses to this workspace's comments and the plan uses the+// idx_comment_workspace supporting btree.+//+// $4 is buildSearchQuery's canonical workspace_id placeholder (the+// caller writes wsUUID into args[3] before executing).+func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {+ singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)++ // Every occurrence of `FROM comment c` must be followed by the+ // c.workspace_id = $4 constraint. Counting is safer than a single+ // substring check because the WHERE, rank CASE, matched_comment_content+ // subqueries all touch `comment` and must each carry the filter.+ fromCount := strings.Count(singleQuery, "FROM comment c")+ scopedCount := strings.Count(singleQuery, "c.workspace_id = $4")+ if fromCount == 0 {+ t.Fatalf("single-term query has no comment subquery — did buildSearchQuery drop it?")+ }+ if scopedCount < fromCount {+ t.Errorf("single-term query has %d comment subqueries but only %d workspace_id filters — %d unscoped subquery(ies) will trigger the MUL-4059 global-hash plan",+ fromCount, scopedCount, fromCount-scopedCount)+ }++ // Multi-term uses one extra comment subquery in the WHERE and one in+ // the rank CASE for the all-terms match — same invariant applies.+ multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)+ fromCountMulti := strings.Count(multiQuery, "FROM comment c")+ scopedCountMulti := strings.Count(multiQuery, "c.workspace_id = $4")+ if scopedCountMulti < fromCountMulti {+ t.Errorf("multi-term query has %d comment subqueries but only %d workspace_id filters",+ fromCountMulti, scopedCountMulti)+ }+}diff --git a/server/internal/handler/search_timeout_test.go b/server/internal/handler/search_timeout_test.gonew file mode 100644index 0000000000..76ba23d05b--- /dev/null+++ b/server/internal/handler/search_timeout_test.go@@ -0,0 +1,83 @@+package handler++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+)++func TestIsSearchStatementTimeout(t *testing.T) {+ tests := []struct {+ name string+ err error+ want bool+ }{+ {"nil error", nil, false},+ {"57014 pgx error", &pgconn.PgError{Code: "57014", Message: "canceling statement due to statement timeout"}, true},+ {"57014 wrapped", errors.Join(errors.New("outer"), &pgconn.PgError{Code: "57014"}), true},+ {"different pg code", &pgconn.PgError{Code: "42P01"}, false},+ {"plain error", errors.New("boom"), false},+ {"context canceled", context.Canceled, false},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := isSearchStatementTimeout(tc.err); got != tc.want {+ t.Errorf("isSearchStatementTimeout(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++// TestRunSearchQuery_StatementTimeoutFires exercises the safety net end+// to end against a live Postgres, proving that a deliberately hung+// pg_sleep query is cut off by SET LOCAL statement_timeout (SQLSTATE+// 57014) before the 3 s search cap could ever be reached. Skips+// gracefully if the database is not reachable — mirrors the pattern in+// handler_test.go so CI without a DB stays green.+func TestRunSearchQuery_StatementTimeoutFires(t *testing.T) {+ if testPool == nil {+ t.Skip("DATABASE_URL not set; skipping live-Postgres search timeout test")+ }+ // Override the search timeout for this test only: 200 ms is short+ // enough that pg_sleep(2) is guaranteed to hit it, and this keeps+ // the test snappy. We restore the constant via t.Cleanup so other+ // tests keep the production value.+ oldTimeout := searchStatementTimeout+ setSearchStatementTimeoutForTest(t, 200*time.Millisecond)+ t.Cleanup(func() { setSearchStatementTimeoutForTest(t, oldTimeout) })++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ start := time.Now()+ err := runSearchQuery(ctx, testPool, "SELECT pg_sleep(2)", nil, func(rows pgx.Rows) error {+ for rows.Next() {+ // nothing to scan — but iterate so pgx surfaces the+ // server error once the statement_timeout fires+ }+ return rows.Err()+ })+ elapsed := time.Since(start)++ if err == nil {+ t.Fatal("expected statement_timeout error, got nil")+ }+ if !isSearchStatementTimeout(err) {+ t.Fatalf("expected SQLSTATE 57014 (statement_timeout), got: %v", err)+ }+ if elapsed > 1500*time.Millisecond {+ t.Errorf("statement_timeout did not cut hung query fast enough: elapsed=%s (want <1.5s)", elapsed)+ }+}++// setSearchStatementTimeoutForTest is a package-private hook used only+// by the live-Postgres timeout test above. Kept out of the public+// surface to prevent handlers from accidentally raising the cap.+func setSearchStatementTimeoutForTest(t *testing.T, v time.Duration) {+ t.Helper()+ searchStatementTimeoutOverride = v+}diff --git a/server/migrations/134_search_index_trgm_fallback.down.sql b/server/migrations/134_search_index_trgm_fallback.down.sqlnew file mode 100644index 0000000000..add5ef8493--- /dev/null+++ b/server/migrations/134_search_index_trgm_fallback.down.sql@@ -0,0 +1,10 @@+-- Drop the pg_trgm fallback GIN search indexes. Leaves the pg_trgm+-- extension in place because other future queries may depend on it and+-- dropping it has no benefit (extension idle overhead is essentially+-- zero). The pg_bigm indexes from migrations 036 / 039 are untouched.++DROP INDEX IF EXISTS idx_issue_title_trgm;+DROP INDEX IF EXISTS idx_issue_description_trgm;+DROP INDEX IF EXISTS idx_comment_content_trgm;+DROP INDEX IF EXISTS idx_project_title_trgm;+DROP INDEX IF EXISTS idx_project_description_trgm;diff --git a/server/migrations/134_search_index_trgm_fallback.up.sql b/server/migrations/134_search_index_trgm_fallback.up.sqlnew file mode 100644index 0000000000..c5350e58e6--- /dev/null+++ b/server/migrations/134_search_index_trgm_fallback.up.sql@@ -0,0 +1,85 @@+-- Fallback GIN search indexes using pg_trgm for environments where pg_bigm+-- is unavailable. Background:+--+-- Migration 032 (issue_search_index), 033 (comment_search_index), and+-- 039 (project_search_index) all wrap `CREATE EXTENSION pg_bigm` and+-- their GIN index creation in EXCEPTION handlers, silently skipping if+-- pg_bigm is not installed. This was intended as a CI guardrail (see+-- migration 032 header) so tests could run against a stock Postgres image.+--+-- The unintended consequence: the bundled self-host / dev / CI Postgres+-- image is `pgvector/pgvector:pg17`, which does NOT ship pg_bigm. On every+-- self-hosted deployment the three migrations silently no-op, no GIN+-- indexes get built, and search queries fall back to a Seq Scan on+-- `issue` / `project` + correlated Seq Scans on `comment` — verified with+-- EXPLAIN on the local dev DB, which had zero title/description/comment+-- search indexes before this change.+--+-- pg_trgm is part of PostgreSQL's contrib package and is shipped in every+-- image we support, including pgvector. It supports the same+-- `LOWER(col) LIKE '%pattern%'` pattern via GIN + gin_trgm_ops. For CJK+-- content pg_bigm remains the better choice (bigrams vs trigrams — a+-- 2-character CJK query indexes cleanly under pg_bigm but degrades to a+-- Seq Scan under pg_trgm) so we do NOT drop the pg_bigm indexes; the two+-- coexist and the planner picks whichever is cheaper.+--+-- Coverage MUST match the search handler surface: SearchIssues consults+-- issue.title / issue.description / comment.content; SearchProjects+-- consults project.title / project.description. Missing any one of them+-- leaves that branch on a Seq Scan and defeats the point of the fallback.+--+-- Guardrails:+-- 1. `CREATE EXTENSION IF NOT EXISTS pg_trgm` — safe on all supported+-- images. Wrapped in DO/EXCEPTION so a hypothetical minimal image+-- without pg_trgm still lets migrations finish (mirrors migration+-- 032 pg_bigm pattern).+-- 2. `CREATE INDEX IF NOT EXISTS` — idempotent on re-run.+-- 3. Same LOWER() expression signature as the search handlers' WHERE+-- clauses exactly, so the planner can match the index.+--+-- Lock impact: plain CREATE INDEX takes an AccessExclusive lock on the+-- table for the duration of the build. Cannot use CREATE INDEX+-- CONCURRENTLY here because it is disallowed inside a DO block (and+-- the extension-optional guardrail requires DO). Operators running very+-- large tables who want the concurrent variant can pre-create the five+-- indexes manually with CONCURRENTLY before applying the migration; the+-- IF NOT EXISTS check will then turn this migration into a no-op.++DO $$+BEGIN+ CREATE EXTENSION IF NOT EXISTS pg_trgm;+EXCEPTION WHEN OTHERS THEN+ RAISE NOTICE 'pg_trgm not available, skipping trigram search indexes';+END+$$;++DO $$+BEGIN+ CREATE INDEX IF NOT EXISTS idx_issue_title_trgm+ ON issue USING gin (LOWER(title) gin_trgm_ops);+ CREATE INDEX IF NOT EXISTS idx_issue_description_trgm+ ON issue USING gin (LOWER(COALESCE(description, '')) gin_trgm_ops);+EXCEPTION WHEN OTHERS THEN+ RAISE NOTICE 'skipping trigram indexes on issue (pg_trgm not installed)';+END+$$;++DO $$+BEGIN+ CREATE INDEX IF NOT EXISTS idx_comment_content_trgm+ ON comment USING gin (LOWER(content) gin_trgm_ops);+EXCEPTION WHEN OTHERS THEN+ RAISE NOTICE 'skipping trigram index on comment (pg_trgm not installed)';+END+$$;++DO $$+BEGIN+ CREATE INDEX IF NOT EXISTS idx_project_title_trgm+ ON project USING gin (LOWER(title) gin_trgm_ops);+ CREATE INDEX IF NOT EXISTS idx_project_description_trgm+ ON project USING gin (LOWER(COALESCE(description, '')) gin_trgm_ops);+EXCEPTION WHEN OTHERS THEN+ RAISE NOTICE 'skipping trigram indexes on project (pg_trgm not installed)';+END+$$;diff --git a/server/migrations/135_comment_workspace_index.down.sql b/server/migrations/135_comment_workspace_index.down.sqlnew file mode 100644index 0000000000..36029d4956--- /dev/null+++ b/server/migrations/135_comment_workspace_index.down.sql@@ -0,0 +1,8 @@+-- Drop the comment.workspace_id supporting btree index (MUL-4059).+-- The search handler's WHERE clause will still work without it — the+-- planner will just fall back to a Seq Scan on `comment` filtered by+-- workspace_id, which is the pre-migration-135 behavior. Only run this+-- down migration if operating below the query-rewrite change; otherwise+-- expect search latency to regress.++DROP INDEX IF EXISTS idx_comment_workspace;diff --git a/server/migrations/135_comment_workspace_index.up.sql b/server/migrations/135_comment_workspace_index.up.sqlnew file mode 100644index 0000000000..586ee1c127--- /dev/null+++ b/server/migrations/135_comment_workspace_index.up.sql@@ -0,0 +1,48 @@+-- Supporting btree index on comment.workspace_id for the search handler.+--+-- Context (MUL-4059): The search handler's WHERE clause contains a+-- correlated `EXISTS` subquery over `comment` that Postgres routinely+-- rewrites into a *hashed* subplan — the subquery is evaluated once and+-- the results are hashed for lookup by the outer scan. That rewrite is+-- an optimization when the subquery is cheap; it becomes a pathology+-- when the subquery scans the entire `comment` table filtered only by+-- LIKE, because for common tokens (e.g. "search", "agent") the bigm/trgm+-- GIN index matches hundreds of thousands of rows across every+-- workspace. Confirmed on prd against `multica-prod`: a search for+-- '%search%' returned 536,761 comment bigm hits, spilled work_mem into a+-- lossy bitmap (`Heap Blocks: exact=48297 lossy=164696`), rechecked 1.9M+-- rows, and the outer query took 32.3 s despite indexes being present.+--+-- The fix is two-part:+-- 1. Query-level: buildSearchQuery now adds `c.workspace_id = $wsParam`+-- to every comment subquery. With the workspace_id as a compile-time+-- constant (same parameter as the outer WHERE), the planner can+-- collapse the hashed set to this workspace's comments only.+-- 2. Index-level: this migration. Without a btree index on+-- comment.workspace_id, the pushed-down filter still triggers a+-- Seq Scan on `comment`; with it, the planner picks an Index Scan+-- or Bitmap AND with the bigm/trgm content index.+--+-- Verified on a local repro that mirrors the prd hot workspace+-- (5k issues in the target workspace, 100k comments in a sibling+-- workspace all containing "search"): the query plan drops from+-- 60 ms (hashed global scan) to 1.8 ms (subplan uses this index).+-- Prd extrapolation: 32.3 s → tens of milliseconds.+--+-- This CREATE INDEX is deliberately unwrapped. The whole point of+-- MUL-4059 was that migrations 032 / 033 / 036 hid CREATE INDEX inside+-- `DO $$ ... EXCEPTION WHEN OTHERS $$` blocks, so on any environment+-- where pg_bigm was absent the migration "succeeded" while quietly+-- creating no indexes at all — the exact silent-skip pattern that took+-- prd search down. This index is the critical support for the fix, not+-- an optional CJK bonus, so a real failure (lock timeout, disk full,+-- permission denied, schema drift) MUST abort the migration and fail+-- deployment, not slip through as a green success. IF NOT EXISTS keeps+-- the migration idempotent for the operator-precreated case; operators+-- who need concurrent creation on a large prd table should run+-- `CREATE INDEX CONCURRENTLY idx_comment_workspace ON comment+-- (workspace_id);` before applying, which turns this statement into a+-- no-op.++CREATE INDEX IF NOT EXISTS idx_comment_workspace+ ON comment (workspace_id);