Skip to content

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

Go

MUL-7055: refactor issue search to candidate-first pipeline (#8041)

Multica Eved3f1e64ea853
diff --git a/.env.example b/.env.example
index 0192ee92f7..7a02f152e3 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,10 @@ DATABASE_URL=postgres://multica:multica@localhost:5432/multica?sslmode=disable
# DATABASE_URL; env vars below take precedence over URL params.
# DATABASE_MAX_CONNS=25
# DATABASE_MIN_CONNS=5
+# Search transactions default to a 64 MB PostgreSQL work_mem ceiling per plan
+# node. Set 1-64 to lower it for memory-constrained databases, or 0 to keep the
+# database/session default. Values above 64 or invalid values fall back to 64.
+# DATABASE_SEARCH_WORK_MEM_MB=64
# Optional PostgreSQL read replica. The API keeps all existing reads on primary
# until a business explicitly opts into eventual-consistency routing in code.
# Every new replica connection is required to be read-only and is recycled
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 5b58805939..64c5bc8f99 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -33,6 +33,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | ローカルの `multica` データベース | PostgreSQL 接続文字列 |
| `DATABASE_MAX_CONNS` | `25` | API プロセスあたりの最大データベース接続数 |
| `DATABASE_MIN_CONNS` | `5` | API プロセスが保持する最小接続数 |
+| `DATABASE_SEARCH_WORK_MEM_MB` | `64` | 検索プランの各ノードに対する PostgreSQL `work_mem` 上限(MB)。`1`~`64` で引き下げ、`0` でデータベース/セッションの既定値を使用 |
| `DATABASE_REPLICA_URL` | 空 | オプションの PostgreSQL 読み取り専用レプリカ接続文字列。新しい接続では読み取り専用状態が検証され、各機能はコードで結果整合性読み取りを明示的に選択する必要があります |
| `DATABASE_REPLICA_MAX_CONNS` | `10` | API プロセスあたりの最大レプリカ接続数 |
| `DATABASE_REPLICA_MIN_CONNS` | `0` | API プロセスが保持する最小レプリカ接続数 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 487e7bcb4b..ac2805136f 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -33,6 +33,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | 로컬 `multica` 데이터베이스 | PostgreSQL 연결 주소 |
| `DATABASE_MAX_CONNS` | `25` | API 프로세스 하나의 최대 데이터베이스 연결 수 |
| `DATABASE_MIN_CONNS` | `5` | API 프로세스 하나가 유지하는 최소 연결 수 |
+| `DATABASE_SEARCH_WORK_MEM_MB` | `64` | 검색 계획의 각 노드에 적용되는 PostgreSQL `work_mem` 상한(MB). `1`~`64`로 낮추거나 `0`으로 데이터베이스/세션 기본값 사용 |
| `DATABASE_REPLICA_URL` | 비어 있음 | 선택적 PostgreSQL 읽기 전용 복제본 연결 주소. 새 연결은 읽기 전용 상태를 검증하며 각 기능은 코드에서 최종 일관성 읽기를 명시적으로 선택해야 함 |
| `DATABASE_REPLICA_MAX_CONNS` | `10` | API 프로세스당 최대 복제본 연결 수 |
| `DATABASE_REPLICA_MIN_CONNS` | `0` | API 프로세스가 유지하는 최소 복제본 연결 수 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 950411591e..fc593ee590 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -33,6 +33,7 @@ You also need to pick an email service, otherwise verification codes and invitat
| `DATABASE_URL` | local `multica` database | PostgreSQL connection string |
| `DATABASE_MAX_CONNS` | `25` | Maximum database connections per API process |
| `DATABASE_MIN_CONNS` | `5` | Minimum connections each API process keeps |
+| `DATABASE_SEARCH_WORK_MEM_MB` | `64` | PostgreSQL `work_mem` ceiling in MB for each search plan node; set `1`-`64` to lower it or `0` to keep the database/session default |
| `DATABASE_REPLICA_URL` | empty | Optional PostgreSQL read-only replica connection string; new connections are validated as read-only, while businesses must explicitly opt into eventual-consistency reads in code |
| `DATABASE_REPLICA_MAX_CONNS` | `10` | Maximum replica connections per API process |
| `DATABASE_REPLICA_MIN_CONNS` | `0` | Minimum replica connections each API process keeps |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 7bbf52f623..9cc2ede491 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -33,6 +33,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | 本地 `multica` 数据库 | PostgreSQL 连接地址 |
| `DATABASE_MAX_CONNS` | `25` | 单个 API 进程的最大数据库连接数 |
| `DATABASE_MIN_CONNS` | `5` | 单个 API 进程保留的最小连接数 |
+| `DATABASE_SEARCH_WORK_MEM_MB` | `64` | 每个搜索计划算子的 PostgreSQL `work_mem` 上限(MB);设为 `1`–`64` 可调低,设为 `0` 则沿用数据库/会话默认值 |
| `DATABASE_REPLICA_URL` | 空 | 可选的 PostgreSQL 只读从库连接地址;新连接会强制校验只读状态,业务仍需在代码中显式选择最终一致读取 |
| `DATABASE_REPLICA_MAX_CONNS` | `10` | 单个 API 进程的最大从库连接数 |
| `DATABASE_REPLICA_MIN_CONNS` | `0` | 单个 API 进程保留的最小从库连接数 |
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index 17156a13ca..d99be1b3e6 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -9,6 +9,7 @@ data:
PORT: "8080"
MULTICA_DATABASE_STARTUP_TIMEOUT: {{ .Values.backend.config.databaseStartupTimeout | quote }}
MULTICA_DATABASE_CONNECT_TIMEOUT: {{ .Values.backend.config.databaseConnectTimeout | quote }}
+ DATABASE_SEARCH_WORK_MEM_MB: {{ .Values.backend.config.databaseSearchWorkMemMB | quote }}
APP_ENV: {{ .Values.backend.config.appEnv | quote }}
MULTICA_APP_URL: {{ .Values.backend.config.appUrl | quote }}
FRONTEND_ORIGIN: {{ .Values.backend.config.frontendOrigin | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index a25fc500d1..0f9ce5d489 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -117,6 +117,10 @@ backend:
# Native connect_timeout / PGCONNECT_TIMEOUT / service settings take
# precedence so existing deployments keep their pgx connection behavior.
databaseConnectTimeout: 5s
+ # PostgreSQL work_mem ceiling in MB for search transactions. Set 1-64 to
+ # lower it for memory-constrained databases, or 0 to keep the database
+ # default. Invalid values fall back to 64 in the API process.
+ databaseSearchWorkMemMB: 64
appEnv: production
appUrl: http://multica.dev.lan
frontendOrigin: http://multica.dev.lan
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 052fe2efce..98a7311b10 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -63,6 +63,7 @@ services:
- backend_uploads:/app/data/uploads
environment:
DATABASE_URL: postgres://${POSTGRES_USER:-multica}:${POSTGRES_PASSWORD:-multica}@postgres:5432/${POSTGRES_DB:-multica}?sslmode=disable
+ DATABASE_SEARCH_WORK_MEM_MB: ${DATABASE_SEARCH_WORK_MEM_MB:-64}
DATABASE_REPLICA_URL: ${DATABASE_REPLICA_URL:-}
DATABASE_REPLICA_MAX_CONNS: ${DATABASE_REPLICA_MAX_CONNS:-}
DATABASE_REPLICA_MIN_CONNS: ${DATABASE_REPLICA_MIN_CONNS:-}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 8a1a2f7648..ba28af3e44 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -615,154 +615,207 @@ type searchResult struct {
matchedCommentContent string
}
-// buildSearchQuery builds a dynamic SQL query for issue search.
-// It uses LOWER(column) LIKE for case-insensitive matching compatible with pg_bigm 1.2 GIN indexes.
-// Search patterns are lowercased in Go to avoid redundant LOWER() on the pattern side in SQL.
-// LIKE patterns are pre-built in Go (e.g. "%html%") so pg_bigm can extract bigrams from a single parameter value.
+// buildSearchQuery builds a two-stage, workspace-scoped candidate pipeline for issue search.
+// Search patterns are lowercased and escaped in Go so every flag uses the same
+// case-insensitive LIKE semantics as the legacy query. The pipeline deliberately
+// trades the title, description, and comment content GIN fast paths for one
+// predictable pass over each relation within the selected workspace.
func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string) (string, []any) {
// Lowercase in Go so SQL only needs LOWER() on the column side.
phrase = strings.ToLower(phrase)
- for i, t := range terms {
- terms[i] = strings.ToLower(t)
+ for i, term := range terms {
+ terms[i] = strings.ToLower(term)
}
- // Parameter index tracker
- argIdx := 1
args := []any{}
- nextArg := func(val any) string {
- args = append(args, val)
- s := fmt.Sprintf("$%d", argIdx)
- argIdx++
- return s
+ nextArg := func(value any) string {
+ args = append(args, value)
+ return fmt.Sprintf("$%d", len(args))
}
escapedPhrase := escapeLike(phrase)
- // $1: exact phrase (for exact title match)
- phraseParam := nextArg(escapedPhrase)
- // $2: "%phrase%" (contains pattern — pre-built for pg_bigm index usage)
- phraseContainsParam := nextArg("%" + escapedPhrase + "%")
- // $3: "phrase%" (starts-with pattern)
- phraseStartsWithParam := nextArg(escapedPhrase + "%")
+ phraseParam := nextArg(escapedPhrase) // $1: exact title
+ phraseContainsParam := nextArg("%" + escapedPhrase + "%") // $2: contains
+ phraseStartsWithParam := nextArg(escapedPhrase + "%") // $3: starts with
+ wsParam := nextArg(nil) // $4: workspace_id, filled by caller
- wsParam := nextArg(nil) // $4 — workspace_id, will be filled by caller position
-
- // Build per-term LIKE conditions only for multi-word search.
var termContainsParams []string
if len(terms) > 1 {
- for _, t := range terms {
- et := escapeLike(t)
- termContainsParams = append(termContainsParams, nextArg("%"+et+"%"))
+ for _, term := range terms {
+ termContainsParams = append(termContainsParams, nextArg("%"+escapeLike(term)+"%"))
}
}
- // --- WHERE clause ---
- var whereParts []string
-
- // 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 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). Same
- // workspace_id-in-subquery contract as above.
- if len(termContainsParams) > 1 {
- var termConditions []string
- for _, 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 c.workspace_id = %s AND LOWER(c.content) LIKE %s))",
- tp, tp, wsParam, tp,
- ))
- }
- whereParts = append(whereParts, "("+strings.Join(termConditions, " AND ")+")")
- }
-
- // Number match
numParam := ""
if hasNum {
numParam = nextArg(queryNum)
- whereParts = append(whereParts, fmt.Sprintf("i.number = %s", numParam))
}
- whereClause := "(" + strings.Join(whereParts, " OR ") + ")"
-
+ terminalStatusesParam := ""
if !includeClosed {
// Negate only known terminal keys so an unknown legacy key remains
// searchable instead of disappearing from the default result set.
- terminalStatusesParam := nextArg(terminalStatusKeys)
- whereClause += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)
+ terminalStatusesParam = nextArg(terminalStatusKeys)
}
- // --- ORDER BY clause ---
- // Build ranking CASE with fine-grained tiers.
- var rankCases []string
+ limitParam := nextArg(nil)
+ offsetParam := nextArg(nil)
- // Tier 0: Identifier exact match
+ // Stage one scans this workspace's issues once and retains only the narrow
+ // flags and sort fields needed to choose a page. Do not force this CTE to be
+ // MATERIALIZED: production EXPLAIN showed 28-68% lower execution time after
+ // removing that fence. Full issue rows are hydrated after LIMIT/OFFSET below.
+ issueFlagColumns := []string{
+ "i.id AS issue_id",
+ "i.status",
+ "i.updated_at",
+ fmt.Sprintf("LOWER(i.title) = %s AS title_exact", phraseParam),
+ fmt.Sprintf("LOWER(i.title) LIKE %s AS title_starts_with", phraseStartsWithParam),
+ fmt.Sprintf("LOWER(i.title) LIKE %s AS title_phrase", phraseContainsParam),
+ fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s AS description_phrase", phraseContainsParam),
+ }
if hasNum {
- rankCases = append(rankCases, fmt.Sprintf("WHEN i.number = %s THEN 0", numParam))
+ issueFlagColumns = append(issueFlagColumns, fmt.Sprintf("i.number = %s AS number_exact", numParam))
+ }
+ for index, termParam := range termContainsParams {
+ issueFlagColumns = append(issueFlagColumns,
+ fmt.Sprintf("LOWER(i.title) LIKE %s AS title_term_%d", termParam, index),
+ fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s AS description_term_%d", termParam, index),
+ )
}
- // Tier 1: Exact title match
- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) = %s THEN 1", phraseParam))
+ issueWhere := "i.workspace_id = " + wsParam
+ if terminalStatusesParam != "" {
+ issueWhere += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)
+ }
+ issueMatchesCTE := fmt.Sprintf(`issue_matches AS (
+ SELECT %s
+ FROM issue i
+ WHERE %s
+ )`, strings.Join(issueFlagColumns, ",\n\t\t\t"), issueWhere)
+
+ // Comments are also scanned once, workspace-first. This intentionally avoids
+ // the legacy planner choice between global content GIN postings and repeated
+ // correlated/hashed subplans (MUL-4059); idx_comment_workspace bounds the
+ // candidate scan instead. Aggregation retains only per-issue flags plus the
+ // latest matching comment ID, and content is fetched by primary key after the
+ // final page is known. Per-term BOOL_OR flags keep the legacy eligibility rule
+ // where terms may be spread across comments, while comment_all_terms keeps
+ // ranking/snippet tied to one comment.
+ commentFlagColumns := []string{
+ "c.issue_id",
+ fmt.Sprintf("BOOL_OR(LOWER(c.content) LIKE %s) AS comment_phrase", phraseContainsParam),
+ }
+ commentCandidateFlags := []string{"aggregated_comments.comment_phrase"}
+ commentTerms := make([]string, 0, len(termContainsParams))
+ for index, termParam := range termContainsParams {
+ alias := fmt.Sprintf("comment_term_%d", index)
+ commentFlagColumns = append(commentFlagColumns,
+ fmt.Sprintf("BOOL_OR(LOWER(c.content) LIKE %s) AS %s", termParam, alias),
+ )
+ commentCandidateFlags = append(commentCandidateFlags, "aggregated_comments."+alias)
+ commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", termParam))
+ }
- // Tier 2: Title starts with phrase
- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 2", phraseStartsWithParam))
+ commentSnippetPredicate := fmt.Sprintf("LOWER(c.content) LIKE %s", phraseContainsParam)
+ if len(commentTerms) > 1 {
+ commentAllTerms := "(" + strings.Join(commentTerms, " AND ") + ")"
+ commentFlagColumns = append(commentFlagColumns,
+ fmt.Sprintf("BOOL_OR(%s) AS comment_all_terms", commentAllTerms),
+ )
+ commentSnippetPredicate += " OR " + commentAllTerms
+ }
+ // Keep the ordered aggregate in the measured single comment pass. Replacing
+ // it with DISTINCT ON/window ranking changes that production-tested plan;
+ // looking the ID up later would repeat text predicates after pagination.
+ // The aggregate stores matching UUIDs per issue (not content), and the ID
+ // tie-break makes equal created_at values deterministic.
+ commentFlagColumns = append(commentFlagColumns, fmt.Sprintf(
+ "(ARRAY_AGG(c.id ORDER BY c.created_at DESC, c.id DESC) FILTER (WHERE %s))[1] AS snippet_comment_id",
+ commentSnippetPredicate,
+ ))
- // Tier 3: Title contains phrase
- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 3", phraseContainsParam))
+ commentMatchesCTE := fmt.Sprintf(`comment_matches AS MATERIALIZED (
+ SELECT *
+ FROM (
+ SELECT %s
+ FROM comment c
+ WHERE c.workspace_id = %s
+ GROUP BY c.issue_id
+ ) aggregated_comments
+ WHERE %s
+ )`,
+ strings.Join(commentFlagColumns, ",\n\t\t\t\t"),
+ wsParam,
+ strings.Join(commentCandidateFlags, " OR "),
+ )
- // Tier 4: Title matches all words (multi-word only)
+ // Stage two combines the two narrow sources, applies the legacy eligibility
+ // and ranking rules once, and materializes only the requested page.
+ eligibleParts := []string{
+ "im.title_phrase",
+ "im.description_phrase",
+ "COALESCE(cm.comment_phrase, FALSE)",
+ }
if len(termContainsParams) > 1 {
- var titleTerms []string
- for _, tp := range termContainsParams {
- titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))
+ var allTerms []string
+ for index := range termContainsParams {
+ allTerms = append(allTerms, fmt.Sprintf(
+ "(im.title_term_%[1]d OR im.description_term_%[1]d OR COALESCE(cm.comment_term_%[1]d, FALSE))",
+ index,
+ ))
}
- rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 4", strings.Join(titleTerms, " AND ")))
+ eligibleParts = append(eligibleParts, "("+strings.Join(allTerms, " AND ")+")")
}
+ if hasNum {
+ eligibleParts = append(eligibleParts, "im.number_exact")
+ }
+ eligibleExpr := "(" + strings.Join(eligibleParts, " OR ") + ")"
- // Tier 5: Description contains phrase
- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 5", phraseContainsParam))
-
- // Tier 6: Description matches all words (multi-word only)
+ rankCases := []string{}
+ if hasNum {
+ rankCases = append(rankCases, "WHEN im.number_exact THEN 0")
+ }
+ rankCases = append(rankCases,
+ "WHEN im.title_exact THEN 1",
+ "WHEN im.title_starts_with THEN 2",
+ "WHEN im.title_phrase THEN 3",
+ )
if len(termContainsParams) > 1 {
- var descTerms []string
- for _, tp := range termContainsParams {
- descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))
+ var titleTerms []string
+ for index := range termContainsParams {
+ titleTerms = append(titleTerms, fmt.Sprintf("im.title_term_%d", index))
}
- rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 6", strings.Join(descTerms, " AND ")))
+ rankCases = append(rankCases, "WHEN ("+strings.Join(titleTerms, " AND ")+") THEN 4")
}
-
- // 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)
+ rankCases = append(rankCases, "WHEN im.description_phrase THEN 5")
if len(termContainsParams) > 1 {
- var commentTerms []string
- for _, tp := range termContainsParams {
- commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))
+ var descriptionTerms []string
+ for index := range termContainsParams {
+ descriptionTerms = append(descriptionTerms, fmt.Sprintf("im.description_term_%d", index))
}
- 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 ")))
+ rankCases = append(rankCases, "WHEN ("+strings.Join(descriptionTerms, " AND ")+") THEN 6")
+ }
+ rankCases = append(rankCases, "WHEN COALESCE(cm.comment_phrase, FALSE) THEN 7")
+ if len(termContainsParams) > 1 {
+ rankCases = append(rankCases, "WHEN COALESCE(cm.comment_all_terms, FALSE) THEN 8")
}
-
rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 9 END"
- // Status priority: active issues first
- statusRank := `CASE i.status
+ // title_exact deliberately preserves the legacy escapeLike quirk: a title
+ // containing _, %, or \\ is still searchable, but the escaped phrase does
+ // not compare equal and therefore is not treated as a cancelled direct hit.
+ directHitParts := []string{"im.title_exact"}
+ if hasNum {
+ directHitParts = append(directHitParts, "im.number_exact")
+ }
+ // Cancelled issues sort behind every live match unless an exact title or
+ // identifier shows that the user is targeting that specific issue.
+ cancelledRank := fmt.Sprintf(
+ "CASE WHEN im.status = 'cancelled' AND NOT (%s) THEN 1 ELSE 0 END",
+ strings.Join(directHitParts, " OR "),
+ )
+ statusRank := `CASE im.status
WHEN 'in_progress' THEN 0
WHEN 'in_review' THEN 1
WHEN 'todo' THEN 2
@@ -773,108 +826,63 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,
ELSE 7
END`
- // Cancelled issues are abandoned work. statusRank alone cannot keep them
- // down because it is only a tie-breaker within one relevance tier: a
- // cancelled issue whose title matches the phrase exactly (tier 1) still
- // outranks an in_progress issue that merely contains it (tier 3), and a
- // workspace with many cancelled issues can fill the whole LIMIT window and
- // push live work off the page entirely. So demote cancelled ahead of
- // rankExpr — they sort after every other match and are the first rows the
- // LIMIT drops. Unlike 'done', which is finished work worth referencing,
- // cancelled work was thrown away. The exception is a direct hit: an exact
- // identifier or exact title means the user is targeting that one issue and
- // knows what they asked for.
- //
- // The title half reuses tier 1's predicate verbatim, including its quirk:
- // phraseParam is escapeLike'd, so a title containing _ or % never compares
- // equal and is not treated as a direct hit. Such an issue is still returned
- // by number; keeping the two predicates identical matters more than working
- // around an escaping bug that belongs with tier 1.
- directHitParts := []string{fmt.Sprintf("LOWER(i.title) = %s", phraseParam)}
- if hasNum {
- directHitParts = append(directHitParts, fmt.Sprintf("i.number = %s", numParam))
- }
- cancelledRank := fmt.Sprintf(
- "CASE WHEN i.status = 'cancelled' AND NOT (%s) THEN 1 ELSE 0 END",
- strings.Join(directHitParts, " OR "),
- )
-
- // --- match_source expression ---
- matchSourceExpr := fmt.Sprintf(`CASE
- WHEN LOWER(i.title) LIKE %s THEN 'title'
- WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 'description'
- ELSE 'comment'
- END`, phraseContainsParam, phraseContainsParam)
-
- // For multi-word: also check if all terms match in title/description
+ matchSourceParts := []string{"WHEN im.title_phrase THEN 'title'"}
if len(termContainsParams) > 1 {
var titleTerms []string
- var descTerms []string
- for _, tp := range termContainsParams {
- titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))
- descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))
- }
- matchSourceExpr = fmt.Sprintf(`CASE
- WHEN LOWER(i.title) LIKE %s THEN 'title'
- WHEN (%s) THEN 'title'
- WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 'description'
- WHEN (%s) THEN 'description'
- ELSE 'comment'
- END`,
- phraseContainsParam, strings.Join(titleTerms, " AND "),
- phraseContainsParam, strings.Join(descTerms, " AND "),
- )
- }
-
- // --- 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 c.workspace_id = %s AND LOWER(c.content) LIKE %s
- ORDER BY c.created_at DESC LIMIT 1),
- ''
- )`, wsParam, phraseContainsParam)
-
- if len(termContainsParams) > 1 {
- var commentTerms []string
- for _, tp := range termContainsParams {
- commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))
+ for index := range termContainsParams {
+ titleTerms = append(titleTerms, fmt.Sprintf("im.title_term_%d", index))
}
- commentSubquery = fmt.Sprintf(`COALESCE(
- (SELECT c.content FROM comment c
- 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),
- ''
- )`, wsParam, phraseContainsParam, strings.Join(commentTerms, " AND "))
+ matchSourceParts = append(matchSourceParts, "WHEN ("+strings.Join(titleTerms, " AND ")+") THEN 'title'")
}
-
- limitParam := nextArg(nil) // placeholder
- offsetParam := nextArg(nil) // placeholder
-
- query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
+ matchSourceParts = append(matchSourceParts, "WHEN im.description_phrase THEN 'description'")
+ if len(termContainsParams) > 1 {
+ var descriptionTerms []string
+ for index := range termContainsParams {
+ descriptionTerms = append(descriptionTerms, fmt.Sprintf("im.description_term_%d", index))
+ }
+ matchSourceParts = append(matchSourceParts, "WHEN ("+strings.Join(descriptionTerms, " AND ")+") THEN 'description'")
+ }
+ matchSourceExpr := "CASE " + strings.Join(matchSourceParts, " ") + " ELSE 'comment' END"
+
+ rankedCandidatesCTE := fmt.Sprintf(`ranked_candidates AS (
+ SELECT im.issue_id, im.updated_at, cm.snippet_comment_id,
+ %s AS cancelled_rank,
+ %s AS relevance_rank,
+ %s AS status_rank,
+ %s AS match_source
+ FROM issue_matches im
+ LEFT JOIN comment_matches cm ON cm.issue_id = im.issue_id
+ WHERE %s
+ )`, cancelledRank, rankExpr, statusRank, matchSourceExpr, eligibleExpr)
+
+ pageCandidatesCTE := fmt.Sprintf(`page_candidates AS MATERIALIZED (
+ SELECT issue_id, updated_at, snippet_comment_id, cancelled_rank, relevance_rank, status_rank, match_source
+ FROM ranked_candidates
+ ORDER BY cancelled_rank, relevance_rank, status_rank, updated_at DESC, issue_id ASC
+ LIMIT %s OFFSET %s
+ )`, limitParam, offsetParam)
+
+ query := fmt.Sprintf(`WITH %s,
+ %s,
+ %s,
+ %s
+ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position,
i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id,
i.revision,
- %s AS match_source,
- %s AS matched_comment_content
- FROM issue i
- WHERE i.workspace_id = %s AND %s
- ORDER BY %s, %s, %s, i.updated_at DESC
- LIMIT %s OFFSET %s`,
- matchSourceExpr,
- commentSubquery,
+ pc.match_source,
+ COALESCE(c.content, '') AS matched_comment_content
+ FROM page_candidates pc
+ JOIN issue i ON i.id = pc.issue_id AND i.workspace_id = %s
+ LEFT JOIN comment c ON c.id = pc.snippet_comment_id AND c.workspace_id = %s
+ ORDER BY pc.cancelled_rank, pc.relevance_rank, pc.status_rank, pc.updated_at DESC, pc.issue_id ASC`,
+ issueMatchesCTE,
+ commentMatchesCTE,
+ rankedCandidatesCTE,
+ pageCandidatesCTE,
+ wsParam,
wsParam,
- whereClause,
- cancelledRank,
- rankExpr,
- statusRank,
- limitParam,
- offsetParam,
)
return query, args
diff --git a/server/internal/handler/search.go b/server/internal/handler/search.go
index 8e703fdefa..5c4dd626ba 100644
--- a/server/internal/handler/search.go
+++ b/server/internal/handler/search.go
@@ -4,6 +4,10 @@ import (
"context"
"errors"
"fmt"
+ "log/slog"
+ "os"
+ "strconv"
+ "strings"
"time"
"github.com/jackc/pgx/v5"
@@ -12,24 +16,76 @@ import (
// 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, 137–142). When those extensions are
-// missing — as they were on every self-hosted deployment using the bundled
-// pgvector/pgvector:pg17 image before migration 137 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).
+// SearchProjects runs LOWER(col) LIKE '%pattern%' queries whose fast path
+// depends on pg_bigm / pg_trgm GIN indexes (see migrations 032, 033, 036,
+// 137–142). SearchIssues instead deliberately uses a candidate-first plan that
+// scans each selected workspace's issues and comments once, avoiding repeated
+// global GIN/hashed-subplan work at the cost of giving up content-index
+// selectivity. Missing extensions or an unexpectedly large workspace can
+// therefore still make either path slow enough that the frontend appears to
+// hang ("搜索卡死没有任何反应", 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
+// The 3 s cap leaves margin above the production-observed candidate-first
+// maximum (1.72 s in the MUL-7055 matrix) and is 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
+
+ searchWorkMemEnv = "DATABASE_SEARCH_WORK_MEM_MB"
+ defaultSearchWorkMemMB = 64
+)
+
+// configuredSearchWorkMemMB removes the candidate-first comment aggregation
+// spill seen at Postgres' 4 MB default. work_mem is a per-node ceiling, not a
+// reservation: the production plan's dominant sort used about 9 MB, but the
+// query has roughly three memory-using sort/hash nodes. With the default 25
+// primary connections, the theoretical ceiling is therefore about 4.8 GB per
+// API process's connection set, not 1.6 GB for the whole query set. Actual use
+// is demand-driven and was much lower in the measured plan.
+//
+// runSearchQuery backs both issue and project search. Project search inherits
+// the same ceiling, but its indexed candidate and small sort do not approach it;
+// no memory is reserved merely by setting the ceiling. Keep this transaction-
+// local so unrelated pooled work retains its database default. Self-hosted
+// operators can set DATABASE_SEARCH_WORK_MEM_MB to 0 to keep that default or to
+// 1-64 to lower the cap; higher values are rejected to avoid expanding risk.
+var configuredSearchWorkMemMB = searchWorkMemMBFromEnv()
+
+func parseSearchWorkMemMB(raw string) (int, bool) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return defaultSearchWorkMemMB, true
+ }
+ value, err := strconv.Atoi(raw)
+ if err != nil || value < 0 || value > defaultSearchWorkMemMB {
+ return defaultSearchWorkMemMB, false
+ }
+ return value, true
+}
+
+func searchWorkMemMBFromEnv() int {
+ raw := os.Getenv(searchWorkMemEnv)
+ value, ok := parseSearchWorkMemMB(raw)
+ if !ok {
+ slog.Warn("invalid search work_mem; using default",
+ "name", searchWorkMemEnv,
+ "value", raw,
+ "default_mb", defaultSearchWorkMemMB,
+ )
+ }
+ return value
+}
+
+func searchWorkMemValue() string {
+ if configuredSearchWorkMemMB == 0 {
+ return ""
+ }
+ return fmt.Sprintf("%dMB", configuredSearchWorkMemMB)
+}
// searchStatementTimeoutOverride, when non-zero, replaces
// searchStatementTimeout for the duration of a test. Never read outside
@@ -44,10 +100,10 @@ func effectiveSearchStatementTimeout() time.Duration {
}
// 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.
+// transaction with transaction-local timeout and working-memory settings.
+// rowsFn receives each pgx.Rows result and is responsible for scanning and
+// 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.
@@ -72,12 +128,19 @@ func runSearchQuery(
}()
// SET LOCAL is transaction-scoped, so pgxpool can safely hand this
- // connection back out after COMMIT without the timeout leaking to
- // unrelated queries.
+ // connection back out after COMMIT without search-specific settings 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)
}
+ if workMem := searchWorkMemValue(); workMem != "" {
+ // workMem is constructed only from the bounded integer parsed above, so
+ // interpolating it cannot introduce SQL syntax or user input.
+ if _, err := tx.Exec(ctx, fmt.Sprintf("SET LOCAL work_mem = '%s'", workMem)); err != nil {
+ return fmt.Errorf("set search work_mem: %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.
diff --git a/server/internal/handler/search_candidate_parity_test.go b/server/internal/handler/search_candidate_parity_test.go
new file mode 100644
index 0000000000..8c706909f6
--- /dev/null
+++ b/server/internal/handler/search_candidate_parity_test.go
@@ -0,0 +1,571 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+type searchParityRow struct {
+ id string
+ matchSource string
+ matchedCommentContent string
+}
+
+// TestBuildSearchQuery_CandidateFirstParity compares the candidate-first query
+// with the exact parent-commit buildSearchQuery against the same database rows.
+// The matrix deliberately covers matches spread across fields and comments,
+// because those are the cases most likely to be changed accidentally by a
+// candidate aggregation. The legacy query has no final ID tie-breaker, so every
+// matching fixture has a distinct updated_at; deterministic ties are tested as
+// a new candidate-first property rather than attributed to legacy behavior.
+func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {
+ token := fmt.Sprintf("mulparity%d", time.Now().UnixNano())
+ baseTime := time.Now().Add(-time.Hour).UTC()
+
+ exactTitle := token + " exact title"
+ exactID := dbfx.Issue(t, exactTitle, testutil.Cols{
+ "description": nil,
+ "updated_at": baseTime.Add(time.Minute),
+ })
+ dbfx.Issue(t, token+" phrase starts here", testutil.Cols{
+ "description": "",
+ "updated_at": baseTime.Add(2 * time.Minute),
+ })
+ dbfx.Issue(t, "prefix "+token+" phrase contained", testutil.Cols{
+ "description": "unrelated",
+ "updated_at": baseTime.Add(3 * time.Minute),
+ })
+ descriptionID := dbfx.Issue(t, "description source "+token, testutil.Cols{
+ "description": "the " + token + " description phrase lives here",
+ "updated_at": baseTime.Add(4 * time.Minute),
+ })
+
+ crossFieldID := dbfx.Issue(t, token+" title-part", testutil.Cols{
+ "description": "cross-part",
+ "updated_at": baseTime.Add(5 * time.Minute),
+ })
+ dbfx.Comment(t, crossFieldID, "fields-part", testutil.Cols{
+ "created_at": baseTime.Add(5 * time.Minute),
+ })
+
+ sameCommentID := dbfx.Issue(t, "same-comment source "+token, testutil.Cols{
+ "updated_at": baseTime.Add(6 * time.Minute),
+ })
+ dbfx.Comment(t, sameCommentID, token+" same gap all", testutil.Cols{
+ "created_at": baseTime.Add(6 * time.Minute),
+ })
+
+ splitCommentID := dbfx.Issue(t, "split-comment source "+token, testutil.Cols{
+ "updated_at": baseTime.Add(7 * time.Minute),
+ })
+ dbfx.Comment(t, splitCommentID, token, testutil.Cols{"created_at": baseTime.Add(7 * time.Minute)})
+ dbfx.Comment(t, splitCommentID, "same", testutil.Cols{"created_at": baseTime.Add(8 * time.Minute)})
+ dbfx.Comment(t, splitCommentID, "all", testutil.Cols{"created_at": baseTime.Add(9 * time.Minute)})
+
+ latestCommentID := dbfx.Issue(t, "latest-comment source", testutil.Cols{
+ "updated_at": baseTime.Add(10 * time.Minute),
+ })
+ dbfx.Comment(t, latestCommentID, token+" snippet older", testutil.Cols{
+ "created_at": baseTime.Add(10 * time.Minute),
+ })
+ latestComment := token + " snippet newer"
+ dbfx.Comment(t, latestCommentID, latestComment, testutil.Cols{
+ "created_at": baseTime.Add(11 * time.Minute),
+ })
+
+ dbfx.Issue(t, "special characters", testutil.Cols{
+ "description": token + ` 100% under_score path\segment`,
+ "updated_at": baseTime.Add(12 * time.Minute),
+ })
+ dbfx.Issue(t, token+" done result", testutil.Cols{
+ "status": "done",
+ "updated_at": baseTime.Add(13 * time.Minute),
+ })
+ dbfx.Issue(t, token+" custom terminal", testutil.Cols{
+ "status": "custom_done",
+ "updated_at": baseTime.Add(14 * time.Minute),
+ })
+ dbfx.Issue(t, token+" cancelled exact", testutil.Cols{
+ "status": "cancelled",
+ "updated_at": baseTime.Add(15 * time.Minute),
+ })
+
+ foreignWorkspaceID := dbfx.Workspace(t, "Search parity foreign", token+"-foreign")
+ foreignIssueID := dbfx.Issue(t, token+" foreign issue", testutil.Cols{
+ "workspace_id": foreignWorkspaceID,
+ "updated_at": baseTime.Add(16 * time.Minute),
+ })
+ dbfx.Comment(t, foreignIssueID, token+" foreign comment", testutil.Cols{
+ "workspace_id": foreignWorkspaceID,
+ "created_at": baseTime.Add(16 * time.Minute),
+ })
+
+ var exactNumber int
+ if err := testPool.QueryRow(context.Background(), `SELECT number FROM issue WHERE id = $1`, exactID).Scan(&exactNumber); err != nil {
+ t.Fatalf("load exact issue number: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ phrase string
+ queryNum int
+ hasNum bool
+ includeClosed bool
+ terminalKeys []string
+ limit int
+ offset int
+ }{
+ {name: "single term", phrase: token, terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "two word phrase and all terms", phrase: token + " phrase", terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "three terms across title description and comment", phrase: token + " cross-part fields-part", terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "same comment versus split comments", phrase: token + " same all", terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "latest matching comment", phrase: token + " snippet", terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "identifier", phrase: fmt.Sprintf("HAN-%d", exactNumber), queryNum: exactNumber, hasNum: true, includeClosed: true, limit: 50},
+ {name: "bare issue number", phrase: fmt.Sprint(exactNumber), queryNum: exactNumber, hasNum: true, includeClosed: true, limit: 50},
+ {name: "exact title", phrase: exactTitle, includeClosed: true, limit: 50},
+ {name: "percent escape", phrase: token + " 100%", includeClosed: true, limit: 50},
+ {name: "underscore escape", phrase: token + " under_score", includeClosed: true, limit: 50},
+ {name: "backslash escape", phrase: token + ` path\segment`, includeClosed: true, limit: 50},
+ {name: "exclude terminal statuses", phrase: token, terminalKeys: []string{"done", "cancelled", "custom_done"}, limit: 50},
+ {name: "include closed and cancelled demotion", phrase: token, includeClosed: true, limit: 50},
+ {name: "limit and offset", phrase: token, includeClosed: true, limit: 3, offset: 2},
+ {name: "no results", phrase: token + " absent-value", includeClosed: true, limit: 50},
+ }
+
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ terms := splitSearchTerms(tt.phrase)
+ legacyQuery, legacyArgs := buildLegacySearchQueryForParity(
+ tt.phrase, append([]string(nil), terms...), tt.queryNum, tt.hasNum, tt.includeClosed, tt.terminalKeys,
+ )
+ legacyArgs[3] = testWorkspaceID
+ legacyArgs[len(legacyArgs)-2] = tt.limit
+ legacyArgs[len(legacyArgs)-1] = tt.offset
+
+ candidateQuery, candidateArgs := buildSearchQuery(
+ tt.phrase, append([]string(nil), terms...), tt.queryNum, tt.hasNum, tt.includeClosed, tt.terminalKeys,
+ )
+ candidateArgs[3] = testWorkspaceID
+ candidateArgs[len(candidateArgs)-2] = tt.limit
+ candidateArgs[len(candidateArgs)-1] = tt.offset
+
+ legacyRows := runLegacySearchForParity(t, legacyQuery, legacyArgs)
+ candidateRows := runCandidateSearchForParity(t, candidateQuery, candidateArgs)
+ if !reflect.DeepEqual(candidateRows, legacyRows) {
+ t.Fatalf("candidate-first rows differ from legacy semantics\ncandidate: %#v\nlegacy: %#v", candidateRows, legacyRows)
+ }
+ })
+ }
+
+ // Legacy ordering is undefined when two matching comments have the same
+ // created_at. Candidate-first makes that case deterministic by choosing the
+ // greater UUID, matching the timeline's established (created_at, id) order.
+ tiedSnippetIssueID := dbfx.Issue(t, "tied snippet source", testutil.Cols{
+ "updated_at": baseTime.Add(17 * time.Minute),
+ })
+ firstCommentID, secondCommentID := uuid.NewString(), uuid.NewString()
+ lowCommentID, highCommentID := firstCommentID, secondCommentID
+ if lowCommentID > highCommentID {
+ lowCommentID, highCommentID = highCommentID, lowCommentID
+ }
+ tiedCommentTime := baseTime.Add(17 * time.Minute)
+ dbfx.Comment(t, tiedSnippetIssueID, token+" tied snippet low", testutil.Cols{
+ "id": lowCommentID,
+ "created_at": tiedCommentTime,
+ })
+ highCommentContent := token + " tied snippet high"
+ dbfx.Comment(t, tiedSnippetIssueID, highCommentContent, testutil.Cols{
+ "id": highCommentID,
+ "created_at": tiedCommentTime,
+ })
+ tiedRows := runBuiltSearchForParity(t, token+" tied snippet", true, nil, 50, 0)
+ if row, ok := findSearchParityRow(tiedRows, tiedSnippetIssueID); !ok {
+ t.Fatal("tied-comment match is missing")
+ } else if row.matchedCommentContent != highCommentContent {
+ t.Fatalf("tied-comment snippet = %q, want greater-ID comment %q", row.matchedCommentContent, highCommentContent)
+ }
+
+ splitRows := runBuiltSearchForParity(t, token+" same all", true, nil, 50, 0)
+ if row, ok := findSearchParityRow(splitRows, splitCommentID); !ok {
+ t.Fatal("split-comment cross-comment match is missing")
+ } else if row.matchSource != "comment" || row.matchedCommentContent != "" {
+ t.Fatalf("split-comment match = %#v, want comment source with no same-comment snippet", row)
+ }
+ if row, ok := findSearchParityRow(splitRows, sameCommentID); !ok {
+ t.Fatal("same-comment all-terms match is missing")
+ } else if row.matchedCommentContent == "" {
+ t.Fatalf("same-comment all-terms match has no snippet: %#v", row)
+ }
+
+ crossRows := runBuiltSearchForParity(t, token+" cross-part fields-part", true, nil, 50, 0)
+ if row, ok := findSearchParityRow(crossRows, crossFieldID); !ok {
+ t.Fatal("cross-field all-terms match is missing")
+ } else if row.matchSource != "comment" {
+ t.Fatalf("cross-field match source = %q, want legacy fallback comment", row.matchSource)
+ }
+
+ latestRows := runBuiltSearchForParity(t, token+" snippet", true, nil, 50, 0)
+ if row, ok := findSearchParityRow(latestRows, latestCommentID); !ok {
+ t.Fatal("latest-comment match is missing")
+ } else if row.matchedCommentContent != latestComment {
+ t.Fatalf("matched comment = %q, want latest %q", row.matchedCommentContent, latestComment)
+ }
+
+ descriptionRows := runBuiltSearchForParity(t, token+" description phrase", true, nil, 50, 0)
+ if row, ok := findSearchParityRow(descriptionRows, descriptionID); !ok {
+ t.Fatal("description phrase match is missing")
+ } else if row.matchSource != "description" {
+ t.Fatalf("description match source = %q, want description", row.matchSource)
+ }
+}
+
+func runBuiltSearchForParity(t *testing.T, phrase string, includeClosed bool, terminalKeys []string, limit, offset int) []searchParityRow {
+ t.Helper()
+ terms := splitSearchTerms(phrase)
+ queryNum, hasNum := parseQueryNumber(phrase)
+ query, args := buildSearchQuery(phrase, terms, queryNum, hasNum, includeClosed, terminalKeys)
+ args[3] = testWorkspaceID
+ args[len(args)-2] = limit
+ args[len(args)-1] = offset
+ return runCandidateSearchForParity(t, query, args)
+}
+
+func findSearchParityRow(rows []searchParityRow, id string) (searchParityRow, bool) {
+ for _, row := range rows {
+ if row.id == id {
+ return row, true
+ }
+ }
+ return searchParityRow{}, false
+}
+
+func runCandidateSearchForParity(t *testing.T, query string, args []any) []searchParityRow {
+ return runSearchForParity(t, "candidate", query, args)
+}
+
+func runLegacySearchForParity(t *testing.T, query string, args []any) []searchParityRow {
+ return runSearchForParity(t, "legacy", query, args)
+}
+
+func runSearchForParity(t *testing.T, label, query string, args []any) []searchParityRow {
+ t.Helper()
+ rows, err := testPool.Query(context.Background(), query, args...)
+ if err != nil {
+ t.Fatalf("run %s search: %v\n%s", label, err, query)
+ }
+ defer rows.Close()
+
+ var result []searchParityRow
+ 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.LastActivityAt,
+ &sr.issue.Number,
+ &sr.issue.ProjectID,
+ &sr.issue.Revision,
+ &sr.matchSource,
+ &sr.matchedCommentContent,
+ ); err != nil {
+ t.Fatalf("scan %s row: %v", label, err)
+ }
+ result = append(result, searchParityRow{
+ id: uuidToString(sr.issue.ID),
+ matchSource: sr.matchSource,
+ matchedCommentContent: sr.matchedCommentContent,
+ })
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("%s rows: %v", label, err)
+ }
+ return result
+}
+
+// buildLegacySearchQueryForParity is the parent commit's buildSearchQuery copied
+// verbatim except for its name. Keeping the original implementation here avoids
+// proving parity against a re-derived oracle that could share the new query's
+// assumptions. This remains test-only; production has no legacy fallback path.
+func buildLegacySearchQueryForParity(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string) (string, []any) {
+ // Lowercase in Go so SQL only needs LOWER() on the column side.
+ phrase = strings.ToLower(phrase)
+ for i, t := range terms {
+ terms[i] = strings.ToLower(t)
+ }
+
+ // Parameter index tracker
+ argIdx := 1
+ args := []any{}
+ nextArg := func(val any) string {
+ args = append(args, val)
+ s := fmt.Sprintf("$%d", argIdx)
+ argIdx++
+ return s
+ }
+
+ escapedPhrase := escapeLike(phrase)
+ // $1: exact phrase (for exact title match)
+ phraseParam := nextArg(escapedPhrase)
+ // $2: "%phrase%" (contains pattern — pre-built for pg_bigm index usage)
+ phraseContainsParam := nextArg("%" + escapedPhrase + "%")
+ // $3: "phrase%" (starts-with pattern)
+ phraseStartsWithParam := nextArg(escapedPhrase + "%")
+
+ wsParam := nextArg(nil) // $4 — workspace_id, will be filled by caller position
+
+ // Build per-term LIKE conditions only for multi-word search.
+ var termContainsParams []string
+ if len(terms) > 1 {
+ for _, t := range terms {
+ et := escapeLike(t)
+ termContainsParams = append(termContainsParams, nextArg("%"+et+"%"))
+ }
+ }
+
+ // --- WHERE clause ---
+ var whereParts []string
+
+ // 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 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). Same
+ // workspace_id-in-subquery contract as above.
+ if len(termContainsParams) > 1 {
+ var termConditions []string
+ for _, 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 c.workspace_id = %s AND LOWER(c.content) LIKE %s))",
+ tp, tp, wsParam, tp,
+ ))
+ }
+ whereParts = append(whereParts, "("+strings.Join(termConditions, " AND ")+")")
+ }
+
+ // Number match
+ numParam := ""
+ if hasNum {
+ numParam = nextArg(queryNum)
+ whereParts = append(whereParts, fmt.Sprintf("i.number = %s", numParam))
+ }
+
+ whereClause := "(" + strings.Join(whereParts, " OR ") + ")"
+
+ if !includeClosed {
+ // Negate only known terminal keys so an unknown legacy key remains
+ // searchable instead of disappearing from the default result set.
+ terminalStatusesParam := nextArg(terminalStatusKeys)
+ whereClause += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)
+ }
+
+ // --- ORDER BY clause ---
+ // Build ranking CASE with fine-grained tiers.
+ var rankCases []string
+
+ // Tier 0: Identifier exact match
+ if hasNum {
+ rankCases = append(rankCases, fmt.Sprintf("WHEN i.number = %s THEN 0", numParam))
+ }
+
+ // Tier 1: Exact title match
+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) = %s THEN 1", phraseParam))
+
+ // Tier 2: Title starts with phrase
+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 2", phraseStartsWithParam))
+
+ // Tier 3: Title contains phrase
+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 3", phraseContainsParam))
+
+ // Tier 4: Title matches all words (multi-word only)
+ if len(termContainsParams) > 1 {
+ var titleTerms []string
+ for _, tp := range termContainsParams {
+ titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))
+ }
+ rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 4", strings.Join(titleTerms, " AND ")))
+ }
+
+ // Tier 5: Description contains phrase
+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 5", phraseContainsParam))
+
+ // Tier 6: Description matches all words (multi-word only)
+ if len(termContainsParams) > 1 {
+ var descTerms []string
+ for _, tp := range termContainsParams {
+ descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))
+ }
+ rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 6", strings.Join(descTerms, " AND ")))
+ }
+
+ // 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 {
+ var commentTerms []string
+ 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 c.workspace_id = %s AND (%s)) THEN 8", wsParam, strings.Join(commentTerms, " AND ")))
+ }
+
+ rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 9 END"
+
+ // Status priority: active issues first
+ statusRank := `CASE i.status
+ WHEN 'in_progress' THEN 0
+ WHEN 'in_review' THEN 1
+ WHEN 'todo' THEN 2
+ WHEN 'blocked' THEN 3
+ WHEN 'backlog' THEN 4
+ WHEN 'done' THEN 5
+ WHEN 'cancelled' THEN 6
+ ELSE 7
+ END`
+
+ // Cancelled issues are abandoned work. statusRank alone cannot keep them
+ // down because it is only a tie-breaker within one relevance tier: a
+ // cancelled issue whose title matches the phrase exactly (tier 1) still
+ // outranks an in_progress issue that merely contains it (tier 3), and a
+ // workspace with many cancelled issues can fill the whole LIMIT window and
+ // push live work off the page entirely. So demote cancelled ahead of
+ // rankExpr — they sort after every other match and are the first rows the
+ // LIMIT drops. Unlike 'done', which is finished work worth referencing,
+ // cancelled work was thrown away. The exception is a direct hit: an exact
+ // identifier or exact title means the user is targeting that one issue and
+ // knows what they asked for.
+ //
+ // The title half reuses tier 1's predicate verbatim, including its quirk:
+ // phraseParam is escapeLike'd, so a title containing _ or % never compares
+ // equal and is not treated as a direct hit. Such an issue is still returned
+ // by number; keeping the two predicates identical matters more than working
+ // around an escaping bug that belongs with tier 1.
+ directHitParts := []string{fmt.Sprintf("LOWER(i.title) = %s", phraseParam)}
+ if hasNum {
+ directHitParts = append(directHitParts, fmt.Sprintf("i.number = %s", numParam))
+ }
+ cancelledRank := fmt.Sprintf(
+ "CASE WHEN i.status = 'cancelled' AND NOT (%s) THEN 1 ELSE 0 END",
+ strings.Join(directHitParts, " OR "),
+ )
+
+ // --- match_source expression ---
+ matchSourceExpr := fmt.Sprintf(`CASE
+ WHEN LOWER(i.title) LIKE %s THEN 'title'
+ WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 'description'
+ ELSE 'comment'
+ END`, phraseContainsParam, phraseContainsParam)
+
+ // For multi-word: also check if all terms match in title/description
+ if len(termContainsParams) > 1 {
+ var titleTerms []string
+ var descTerms []string
+ for _, tp := range termContainsParams {
+ titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))
+ descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))
+ }
+ matchSourceExpr = fmt.Sprintf(`CASE
+ WHEN LOWER(i.title) LIKE %s THEN 'title'
+ WHEN (%s) THEN 'title'
+ WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 'description'
+ WHEN (%s) THEN 'description'
+ ELSE 'comment'
+ END`,
+ phraseContainsParam, strings.Join(titleTerms, " AND "),
+ phraseContainsParam, strings.Join(descTerms, " AND "),
+ )
+ }
+
+ // --- 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 c.workspace_id = %s AND LOWER(c.content) LIKE %s
+ ORDER BY c.created_at DESC LIMIT 1),
+ ''
+ )`, wsParam, phraseContainsParam)
+
+ if len(termContainsParams) > 1 {
+ var commentTerms []string
+ for _, tp := range termContainsParams {
+ commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))
+ }
+ commentSubquery = fmt.Sprintf(`COALESCE(
+ (SELECT c.content FROM comment c
+ 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),
+ ''
+ )`, wsParam, phraseContainsParam, strings.Join(commentTerms, " AND "))
+ }
+
+ limitParam := nextArg(nil) // placeholder
+ offsetParam := nextArg(nil) // placeholder
+
+ query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
+ i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position,
+ i.start_date, i.due_date, i.created_at, i.updated_at, i.last_activity_at, i.number, i.project_id,
+ i.revision,
+ %s AS match_source,
+ %s AS matched_comment_content
+ FROM issue i
+ WHERE i.workspace_id = %s AND %s
+ ORDER BY %s, %s, %s, i.updated_at DESC
+ LIMIT %s OFFSET %s`,
+ matchSourceExpr,
+ commentSubquery,
+ wsParam,
+ whereClause,
+ cancelledRank,
+ rankExpr,
+ statusRank,
+ limitParam,
+ offsetParam,
+ )
+
+ return query, args
+}
diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.go
index 3dd5f73d37..2da26e992b 100644
--- a/server/internal/handler/search_test.go
+++ b/server/internal/handler/search_test.go
@@ -301,41 +301,64 @@ func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {
}
// 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.
+// MUL-4059 fix: the single comment scan and the final point hydration MUST
+// both filter by c.workspace_id = $wsParam. Without this, Postgres can read
+// matching comments from every workspace — on prd this was 536k rows / 32.3 s
+// for '%search%'.
//
// $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, []string{"done", "cancelled"})
- // 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.
+ // Candidate-first search aggregates comments in one workspace-first pass;
+ // it must not grow a second scan for eligibility, ranking, or snippets.
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 fromCount != 1 {
+ t.Fatalf("single-term query has %d comment scans, want exactly one:\n%s", fromCount, singleQuery)
}
- 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)
+ if scopedCount < 2 {
+ t.Errorf("single-term query has %d workspace_id filters, want one on aggregation and one on hydration:\n%s", scopedCount, singleQuery)
+ }
+ if !strings.Contains(singleQuery, "comment_matches AS MATERIALIZED") {
+ t.Errorf("comment aggregation is not materialized:\n%s", singleQuery)
+ }
+ if strings.Contains(singleQuery, "EXISTS (SELECT 1 FROM comment") {
+ t.Errorf("candidate-first query regressed to correlated comment EXISTS checks:\n%s", singleQuery)
}
- // Multi-term uses one extra comment subquery in the WHERE and one in
- // the rank CASE for the all-terms match — same invariant applies.
+ // Adding terms adds boolean aggregates, not extra comment relation scans.
multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"})
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)
+ if fromCountMulti != 1 {
+ t.Errorf("multi-term query has %d comment scans, want exactly one:\n%s", fromCountMulti, multiQuery)
+ }
+ if !strings.Contains(multiQuery, "BOOL_OR((LOWER(c.content) LIKE") || !strings.Contains(multiQuery, "AS comment_all_terms") {
+ t.Errorf("multi-term query does not retain the same-comment all-terms flag:\n%s", multiQuery)
+ }
+ if !strings.Contains(multiQuery, "ARRAY_AGG(c.id ORDER BY c.created_at DESC, c.id DESC)") {
+ t.Errorf("snippet selection has no deterministic comment-ID tie-breaker:\n%s", multiQuery)
+ }
+}
+
+func TestBuildSearchQuery_HydratesOnlyTheSelectedPage(t *testing.T) {
+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"})
+
+ if strings.Contains(query, "issue_matches AS MATERIALIZED") {
+ t.Fatalf("issue flag CTE must remain inlineable; forced materialization spills in production:\n%s", query)
+ }
+ if !strings.Contains(query, "issue_matches AS (") || !strings.Contains(query, "page_candidates AS MATERIALIZED") {
+ t.Fatalf("query does not retain narrow issue flags and materialize the selected page:\n%s", query)
+ }
+ limitAt := strings.Index(query, "LIMIT ")
+ issueHydrationAt := strings.Index(query, "JOIN issue i ON i.id = pc.issue_id")
+ commentHydrationAt := strings.Index(query, "LEFT JOIN comment c ON c.id = pc.snippet_comment_id")
+ if limitAt == -1 || issueHydrationAt < limitAt || commentHydrationAt < limitAt {
+ t.Fatalf("full issue/comment hydration must happen after LIMIT/OFFSET:\n%s", query)
+ }
+ if lastTextMatch := strings.LastIndex(query, "LOWER(c.content) LIKE"); lastTextMatch > limitAt {
+ t.Errorf("comment hydration repeats a text search after LIMIT/OFFSET:\n%s", query)
}
}
@@ -358,57 +381,54 @@ func orderByClause(t *testing.T, query string) string {
// already landed in the same tier, so an exactly-titled cancelled issue
// (tier 1) would still beat an in_progress title-contains match (tier 3).
func TestBuildSearchQuery_CancelledDemotedAheadOfRelevance(t *testing.T) {
- orderBy := orderByClause(t, buildSearchQueryForTest(t, "login bug", []string{"login", "bug"}, 0, false, true))
-
- cancelledAt := strings.Index(orderBy, "i.status = 'cancelled' AND NOT")
- if cancelledAt == -1 {
- t.Fatalf("ORDER BY has no cancelled demotion:\n%s", orderBy)
+ query := buildSearchQueryForTest(t, "login bug", []string{"login", "bug"}, 0, false, true)
+ if !strings.Contains(query, "CASE WHEN im.status = 'cancelled' AND NOT (im.title_exact) THEN 1 ELSE 0 END AS cancelled_rank") {
+ t.Fatalf("ranked candidates have no cancelled demotion:\n%s", query)
}
- // "ELSE 9 END" terminates the relevance CASE (rankExpr).
- relevanceEndsAt := strings.Index(orderBy, "ELSE 9 END")
- if relevanceEndsAt == -1 {
- t.Fatalf("ORDER BY has no relevance rank CASE:\n%s", orderBy)
- }
- if cancelledAt > relevanceEndsAt {
- t.Errorf("cancelled demotion sorts after the relevance tiers, so a well-matching cancelled issue still outranks live work:\n%s", orderBy)
+ orderBy := orderByClause(t, query)
+ if !strings.HasPrefix(orderBy, "pc.cancelled_rank, pc.relevance_rank, pc.status_rank") {
+ t.Errorf("cancelled demotion does not sort before relevance and status:\n%s", orderBy)
}
// The demotion must not replace the existing status ordering.
- if !strings.Contains(orderBy, "WHEN 'in_progress' THEN 0") {
- t.Errorf("statusRank was dropped from ORDER BY:\n%s", orderBy)
+ if !strings.Contains(query, "WHEN 'in_progress' THEN 0") {
+ t.Errorf("statusRank was dropped from ranked candidates:\n%s", query)
}
- if !strings.Contains(orderBy, "i.updated_at DESC") {
+ if !strings.Contains(orderBy, "pc.updated_at DESC") {
t.Errorf("recency tie-breaker was dropped from ORDER BY:\n%s", orderBy)
}
+ if !strings.Contains(orderBy, "pc.issue_id ASC") {
+ t.Errorf("stable issue ID tie-breaker was dropped from ORDER BY:\n%s", orderBy)
+ }
}
// Searching an exact title or an exact identifier is unambiguous targeting —
// the searcher already knows which issue they want, so demoting it would just
// hide the row they asked for.
func TestBuildSearchQuery_CancelledDirectHitExempt(t *testing.T) {
- // $1 is the exact (non-wildcard) phrase param.
- textOnly := orderByClause(t, buildSearchQueryForTest(t, "ship it", []string{"ship", "it"}, 0, false, true))
- if !strings.Contains(textOnly, "i.status = 'cancelled' AND NOT (LOWER(i.title) = $1)") {
+ textOnly := buildSearchQueryForTest(t, "ship it", []string{"ship", "it"}, 0, false, true)
+ if !strings.Contains(textOnly, "im.status = 'cancelled' AND NOT (im.title_exact)") {
t.Errorf("exact-title hit is not exempt from the cancelled demotion:\n%s", textOnly)
}
- if strings.Contains(textOnly, "i.number = ") {
+ if strings.Contains(textOnly, "number_exact") {
t.Errorf("non-numeric query should not reference i.number in the demotion:\n%s", textOnly)
}
- withNumber := orderByClause(t, buildSearchQueryForTest(t, "MUL-42", []string{"MUL-42"}, 42, true, true))
- if !strings.Contains(withNumber, "LOWER(i.title) = $1 OR i.number = ") {
+ withNumber := buildSearchQueryForTest(t, "MUL-42", []string{"MUL-42"}, 42, true, true)
+ if !strings.Contains(withNumber, "NOT (im.title_exact OR im.number_exact)") {
t.Errorf("identifier lookup is not exempt from the cancelled demotion, so MUL-42 sinks below every fuzzy match:\n%s", withNumber)
}
}
// 'done' is finished work worth referencing; only 'cancelled' is thrown away.
func TestBuildSearchQuery_DoneNotDemotedAheadOfRelevance(t *testing.T) {
- orderBy := orderByClause(t, buildSearchQueryForTest(t, "login", []string{"login"}, 0, false, true))
-
- relevanceEndsAt := strings.Index(orderBy, "ELSE 9 END")
- if doneAt := strings.Index(orderBy, "i.status = 'done'"); doneAt != -1 && doneAt < relevanceEndsAt {
- t.Errorf("done issues were demoted ahead of relevance; only cancelled should be:\n%s", orderBy)
+ query := buildSearchQueryForTest(t, "login", []string{"login"}, 0, false, true)
+ if strings.Contains(query, "CASE WHEN im.status = 'done'") {
+ t.Errorf("done issues were demoted ahead of relevance; only cancelled should be:\n%s", query)
+ }
+ if !strings.Contains(query, "WHEN 'done' THEN 5") {
+ t.Errorf("done status tie-breaker was dropped:\n%s", query)
}
}
diff --git a/server/internal/handler/search_timeout_test.go b/server/internal/handler/search_timeout_test.go
index 76ba23d05b..5f9119ce52 100644
--- a/server/internal/handler/search_timeout_test.go
+++ b/server/internal/handler/search_timeout_test.go
@@ -32,6 +32,33 @@ func TestIsSearchStatementTimeout(t *testing.T) {
}
}
+func TestParseSearchWorkMemMB(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ want int
+ wantOK bool
+ }{
+ {name: "unset uses default", want: defaultSearchWorkMemMB, wantOK: true},
+ {name: "disable local override", raw: "0", want: 0, wantOK: true},
+ {name: "lower cap", raw: " 16 ", want: 16, wantOK: true},
+ {name: "default explicitly", raw: "64", want: 64, wantOK: true},
+ {name: "negative rejected", raw: "-1", want: defaultSearchWorkMemMB},
+ {name: "higher cap rejected", raw: "65", want: defaultSearchWorkMemMB},
+ {name: "unit suffix rejected", raw: "16MB", want: defaultSearchWorkMemMB},
+ {name: "invalid rejected", raw: "large", want: defaultSearchWorkMemMB},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, ok := parseSearchWorkMemMB(tt.raw)
+ if got != tt.want || ok != tt.wantOK {
+ t.Fatalf("parseSearchWorkMemMB(%q) = (%d, %t), want (%d, %t)", tt.raw, got, ok, tt.want, tt.wantOK)
+ }
+ })
+ }
+}
+
// 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
@@ -74,6 +101,51 @@ func TestRunSearchQuery_StatementTimeoutFires(t *testing.T) {
}
}
+func TestRunSearchQuery_WorkMemIsTransactionLocal(t *testing.T) {
+ if testPool == nil {
+ t.Skip("DATABASE_URL not set; skipping live-Postgres search work_mem test")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ conn, err := testPool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire dedicated connection: %v", err)
+ }
+ defer conn.Release()
+
+ var before string
+ if err := conn.QueryRow(ctx, "SHOW work_mem").Scan(&before); err != nil {
+ t.Fatalf("read baseline work_mem: %v", err)
+ }
+
+ var during string
+ err = runSearchQuery(ctx, conn, "SELECT current_setting('work_mem')", nil, func(rows pgx.Rows) error {
+ if !rows.Next() {
+ return rows.Err()
+ }
+ return rows.Scan(&during)
+ })
+ if err != nil {
+ t.Fatalf("run search query: %v", err)
+ }
+ wantDuring := before
+ if configured := searchWorkMemValue(); configured != "" {
+ wantDuring = configured
+ }
+ if during != wantDuring {
+ t.Fatalf("work_mem during search = %q, want %q", during, wantDuring)
+ }
+
+ var after string
+ if err := conn.QueryRow(ctx, "SHOW work_mem").Scan(&after); err != nil {
+ t.Fatalf("read work_mem after search: %v", err)
+ }
+ if after != before {
+ t.Fatalf("transaction-local work_mem leaked: before=%q after=%q", before, after)
+ }
+}
+
// 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.