Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7183: reduce issue search normalization work (#8204)
Multica Eve9a3d92da12c4
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex b1ce51e657..99121bfd4d 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -665,22 +665,37 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,// 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.+ const (+ loweredIssueTitle = "lowered_issue_title.lowered"+ loweredIssueDescription = "lowered_issue_description.lowered"+ )+ titlePhrasePredicate := fmt.Sprintf("%s LIKE %s", loweredIssueTitle, phraseContainsParam)+ titleTermPredicates := make([]string, 0, len(termContainsParams))+ for _, termParam := range termContainsParams {+ titleTermPredicates = append(titleTermPredicates, fmt.Sprintf("%s LIKE %s", loweredIssueTitle, termParam))+ }+ titleMatchParts := []string{titlePhrasePredicate}+ if len(termContainsParams) > 1 {+ titleMatchParts = append(titleMatchParts, "("+strings.Join(titleTermPredicates, " AND ")+")")+ }+ titleMatchExpr := "(" + strings.Join(titleMatchParts, " OR ") + ")"+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),+ fmt.Sprintf("%s = %s AS title_exact", loweredIssueTitle, phraseParam),+ fmt.Sprintf("%s LIKE %s AS title_starts_with", loweredIssueTitle, phraseStartsWithParam),+ fmt.Sprintf("%s AS title_phrase", titlePhrasePredicate),+ fmt.Sprintf("COALESCE(%s LIKE %s, FALSE) AS description_phrase", loweredIssueDescription, phraseContainsParam),}if hasNum {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),+ fmt.Sprintf("%s AS title_term_%d", titleTermPredicates[index], index),+ fmt.Sprintf("COALESCE(%s LIKE %s, FALSE) AS description_term_%d", loweredIssueDescription, termParam, index),)}@@ -688,11 +703,30 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,if terminalStatusesParam != "" {issueWhere += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)}+ // PostgreSQL otherwise inlines scalar LATERAL subqueries and recomputes the+ // LOWER expressions for every flag. The OFFSET 0 fences cache the normalized+ // title and description per issue row without materializing the whole CTE.+ // Once the title contains the phrase or every search term, it has already+ // satisfied eligibility and won both relevance-rank and match-source+ // precedence, so the LEFT JOIN can skip normalizing the description and its+ // flags safely fall back to FALSE. Correctness requires every title rank and+ // match-source branch below to remain ahead of its description counterpart.+ // Future indexable text predicates must stay outside these projection-only+ // fences so expression indexes can still match them.issueMatchesCTE := fmt.Sprintf(`issue_matches AS (SELECT %sFROM issue i+ CROSS JOIN LATERAL (+ SELECT LOWER(i.title) AS lowered+ OFFSET 0+ ) lowered_issue_title+ LEFT JOIN LATERAL (+ SELECT LOWER(COALESCE(i.description, '')) AS lowered+ WHERE NOT %s+ OFFSET 0+ ) lowered_issue_description ON TRUEWHERE %s- )`, strings.Join(issueFlagColumns, ",\n\t\t\t"), issueWhere)+ )`, strings.Join(issueFlagColumns, ",\n\t\t\t"), titleMatchExpr, issueWhere)// Comments are also scanned once, workspace-first. This intentionally avoids// the legacy planner choice between global content GIN postings and repeateddiff --git a/server/internal/handler/search_candidate_parity_test.go b/server/internal/handler/search_candidate_parity_test.goindex 8c706909f6..56959c7734 100644--- a/server/internal/handler/search_candidate_parity_test.go+++ b/server/internal/handler/search_candidate_parity_test.go@@ -96,15 +96,25 @@ func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {"status": "cancelled","updated_at": baseTime.Add(15 * time.Minute),})+ phraseDoubleMatch := token + " overlap phrase"+ phraseDoubleMatchID := dbfx.Issue(t, "title "+phraseDoubleMatch, testutil.Cols{+ "description": "description also contains " + phraseDoubleMatch,+ "updated_at": baseTime.Add(16 * time.Minute),+ })+ titleTermsDoubleMatch := token + " ordered phrase"+ titleTermsDoubleMatchID := dbfx.Issue(t, token+" ordered gap phrase", testutil.Cols{+ "description": "description contains the contiguous phrase " + titleTermsDoubleMatch,+ "updated_at": baseTime.Add(17 * 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),+ "updated_at": baseTime.Add(18 * time.Minute),})dbfx.Comment(t, foreignIssueID, token+" foreign comment", testutil.Cols{"workspace_id": foreignWorkspaceID,- "created_at": baseTime.Add(16 * time.Minute),+ "created_at": baseTime.Add(18 * time.Minute),})var exactNumber int@@ -124,6 +134,8 @@ func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {}{{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: "title and description both contain phrase", phrase: phraseDoubleMatch, includeClosed: true, limit: 50},+ {name: "title contains all terms while description contains phrase", phrase: titleTermsDoubleMatch, includeClosed: true, 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},@@ -168,14 +180,14 @@ func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {// 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),+ "updated_at": baseTime.Add(19 * time.Minute),})firstCommentID, secondCommentID := uuid.NewString(), uuid.NewString()lowCommentID, highCommentID := firstCommentID, secondCommentIDif lowCommentID > highCommentID {lowCommentID, highCommentID = highCommentID, lowCommentID}- tiedCommentTime := baseTime.Add(17 * time.Minute)+ tiedCommentTime := baseTime.Add(20 * time.Minute)dbfx.Comment(t, tiedSnippetIssueID, token+" tied snippet low", testutil.Cols{"id": lowCommentID,"created_at": tiedCommentTime,@@ -224,6 +236,20 @@ func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {} else if row.matchSource != "description" {t.Fatalf("description match source = %q, want description", row.matchSource)}++ phraseDoubleMatchRows := runBuiltSearchForParity(t, phraseDoubleMatch, true, nil, 50, 0)+ if row, ok := findSearchParityRow(phraseDoubleMatchRows, phraseDoubleMatchID); !ok {+ t.Fatal("title/description phrase double match is missing")+ } else if row.matchSource != "title" {+ t.Fatalf("title/description phrase double match source = %q, want title", row.matchSource)+ }++ titleTermsDoubleMatchRows := runBuiltSearchForParity(t, titleTermsDoubleMatch, true, nil, 50, 0)+ if row, ok := findSearchParityRow(titleTermsDoubleMatchRows, titleTermsDoubleMatchID); !ok {+ t.Fatal("title-terms/description-phrase double match is missing")+ } else if row.matchSource != "title" {+ t.Fatalf("title-terms/description-phrase double match source = %q, want title", row.matchSource)+ }}func runBuiltSearchForParity(t *testing.T, phrase string, includeClosed bool, terminalKeys []string, limit, offset int) []searchParityRow {diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex 310b39fe4c..ff82219baa 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -17,22 +17,22 @@ func TestBuildSearchQuery_SingleTerm(t *testing.T) {if strings.Contains(query, "ILIKE") {t.Error("query should not contain ILIKE")}- if !strings.Contains(query, "LOWER(i.title) LIKE") {- t.Error("query should contain LOWER(i.title) LIKE")+ if !strings.Contains(query, "lowered_issue_title.lowered LIKE") {+ t.Error("query should match against the pre-lowered issue title")}- if !strings.Contains(query, "LOWER(COALESCE(i.description, '')) LIKE") {- t.Error("query should contain LOWER(COALESCE(i.description, '')) LIKE")+ if !strings.Contains(query, "lowered_issue_description.lowered LIKE") {+ t.Error("query should match against the conditionally lowered issue description")}if !strings.Contains(query, "lowered_comment.lowered LIKE") {t.Error("query should match against the pre-lowered comment content")}// Exact title rank should not double-LOWER the pattern.- if strings.Contains(query, "LOWER(i.title) = LOWER(") {+ if strings.Contains(query, "lowered_issue_title.lowered = LOWER(") {t.Error("exact title rank should not wrap pattern in LOWER (already lowercased in Go)")}- if !strings.Contains(query, "LOWER(i.title) = $1") {- t.Error("exact title rank should compare LOWER(i.title) = $1 directly")+ if !strings.Contains(query, "lowered_issue_title.lowered = $1") {+ t.Error("exact title rank should compare the lowered title to $1 directly")}// Should exclude closed issues by default.@@ -129,6 +129,58 @@ func TestBuildSearchQuery_LowersCommentContentOnce(t *testing.T) {}}+func TestBuildSearchQuery_LowersIssueTextOnceAndSkipsDescriptionForTitleMatches(t *testing.T) {+ query, _ := buildSearchQuery("Foo Bar Baz", []string{"Foo", "Bar", "Baz"}, 0, false, false, []string{"done", "cancelled"})+ normalizedQuery := strings.Join(strings.Fields(query), " ")++ if count := strings.Count(query, "LOWER(i.title)"); count != 1 {+ t.Fatalf("query lowers issue title %d times, want exactly once:\n%s", count, query)+ }+ if count := strings.Count(query, "LOWER(COALESCE(i.description, ''))"); count != 1 {+ t.Fatalf("query lowers issue description %d times, want exactly once:\n%s", count, query)+ }+ if !strings.Contains(normalizedQuery, "CROSS JOIN LATERAL ( SELECT LOWER(i.title) AS lowered OFFSET 0 ) lowered_issue_title") {+ t.Fatalf("query does not retain the title planner fence:\n%s", query)+ }+ if !strings.Contains(normalizedQuery, "LEFT JOIN LATERAL ( SELECT LOWER(COALESCE(i.description, '')) AS lowered WHERE NOT (lowered_issue_title.lowered LIKE $2 OR (lowered_issue_title.lowered LIKE $5 AND lowered_issue_title.lowered LIKE $6 AND lowered_issue_title.lowered LIKE $7)) OFFSET 0 ) lowered_issue_description ON TRUE") {+ t.Fatalf("query does not condition description lowercasing on a complete title match:\n%s", query)+ }+ if strings.Contains(query, "LOWER(i.title) LIKE") || strings.Contains(query, "LOWER(COALESCE(i.description, '')) LIKE") {+ t.Fatalf("issue predicates bypass the pre-lowered values:\n%s", query)+ }+ if !strings.Contains(query, "COALESCE(lowered_issue_description.lowered LIKE $2, FALSE) AS description_phrase") {+ t.Fatalf("skipped description matches do not fall back to FALSE:\n%s", query)+ }++ // Conditional description skipping is equivalent only while every complete+ // title match outranks and takes match-source precedence over description.+ assertSQLBefore(t, query,+ "WHEN im.title_phrase THEN 3",+ "WHEN im.description_phrase THEN 5",+ )+ assertSQLBefore(t, query,+ "WHEN (im.title_term_0 AND im.title_term_1 AND im.title_term_2) THEN 4",+ "WHEN im.description_phrase THEN 5",+ )+ assertSQLBefore(t, query,+ "WHEN im.title_phrase THEN 'title'",+ "WHEN im.description_phrase THEN 'description'",+ )+ assertSQLBefore(t, query,+ "WHEN (im.title_term_0 AND im.title_term_1 AND im.title_term_2) THEN 'title'",+ "WHEN im.description_phrase THEN 'description'",+ )+}++func assertSQLBefore(t *testing.T, query, earlier, later string) {+ t.Helper()+ earlierAt := strings.Index(query, earlier)+ laterAt := strings.Index(query, later)+ if earlierAt == -1 || laterAt == -1 || earlierAt > laterAt {+ t.Fatalf("query must keep %q before %q:\n%s", earlier, later, query)+ }+}+func TestBuildSearchQuery_WithNumber(t *testing.T) {query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false, []string{"done", "cancelled"})