Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7050 perf(search): remove unused exact search counts (#8033)
Multica Eve70ea4c8f0d04
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex 68e4083979..f1582dfa1d 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -375,12 +375,10 @@ const SearchIssueResultSchema = IssueSchema.safeExtend({export const SearchIssuesResponseSchema = z.object({issues: z.array(SearchIssueResultSchema).default([]),- total: z.number().default(0),}).loose();export const EMPTY_SEARCH_ISSUES_RESPONSE: SearchIssuesResponse = {issues: [],- total: 0,};const SearchProjectResultSchema = ProjectSchema.safeExtend({@@ -390,12 +388,10 @@ const SearchProjectResultSchema = ProjectSchema.safeExtend({export const SearchProjectsResponseSchema = z.object({projects: z.array(SearchProjectResultSchema).default([]),- total: z.number().default(0),}).loose();export const EMPTY_SEARCH_PROJECTS_RESPONSE: SearchProjectsResponse = {projects: [],- total: 0,};// =====================================================diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 6afc43b363..abffe933ae 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -320,7 +320,14 @@ describe("ApiClient schema fallback", () => {stubFetchJson({ issues: "not-an-array", total: 0 });const client = new ApiClient("https://api.example.test");const res = await client.searchIssues({ q: "bug" });- expect(res).toEqual({ issues: [], total: 0 });+ expect(res).toEqual({ issues: [] });+ });++ it("accepts a response without an exact total", async () => {+ stubFetchJson({ issues: [] });+ const client = new ApiClient("https://api.example.test");+ const res = await client.searchIssues({ q: "bug" });+ expect(res).toEqual({ issues: [] });});});@@ -329,7 +336,14 @@ describe("ApiClient schema fallback", () => {stubFetchJson({ projects: "not-an-array", total: 0 });const client = new ApiClient("https://api.example.test");const res = await client.searchProjects({ q: "roadmap" });- expect(res).toEqual({ projects: [], total: 0 });+ expect(res).toEqual({ projects: [] });+ });++ it("accepts a response without an exact total", async () => {+ stubFetchJson({ projects: [] });+ const client = new ApiClient("https://api.example.test");+ const res = await client.searchProjects({ q: "roadmap" });+ expect(res).toEqual({ projects: [] });});});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 0bb00c9029..5d86396c91 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1287,12 +1287,10 @@ const SearchIssueResultSchema = IssueSchema.extend({export const SearchIssuesResponseSchema = z.object({issues: z.array(SearchIssueResultSchema).default([]),- total: z.number().default(0),}).loose();export const EMPTY_SEARCH_ISSUES_RESPONSE: SearchIssuesResponse = {issues: [],- total: 0,};const ProjectSchema = z.object({@@ -1324,12 +1322,10 @@ const SearchProjectResultSchema = ProjectSchema.extend({export const SearchProjectsResponseSchema = z.object({projects: z.array(SearchProjectResultSchema).default([]),- total: z.number().default(0),}).loose();export const EMPTY_SEARCH_PROJECTS_RESPONSE: SearchProjectsResponse = {projects: [],- total: 0,};const IssueAssigneeGroupSchema = z.object({diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 3d3d35a295..0ecb9fd2f8 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -442,9 +442,9 @@ export function issueDetailOptions(wsId: string, id: string) {** It deliberately does NOT use `/api/issues/search`: that endpoint runs the* workspace-wide full-text query (title/description/comment `LIKE`, ranking,- * snippet subquery, `COUNT(*) OVER()`) which is orders of magnitude more- * expensive than a point read, and autolink resolution was the dominant- * caller of it (MUL-6268).+ * and snippet subqueries) which is orders of magnitude more expensive than a+ * point read, and autolink resolution was the dominant caller of it+ * (MUL-6268).** Server state → TanStack Query; the key includes `wsId` and the identifier,* so identical identifiers across the app share one request. Caller gatesdiff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 4e6b22a547..9f008b87bf 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -516,7 +516,6 @@ export interface SearchIssueResult extends Issue {export interface SearchIssuesResponse {issues: SearchIssueResult[];- total: number;}export interface SearchProjectResult extends Project {@@ -526,7 +525,6 @@ export interface SearchProjectResult extends Project {export interface SearchProjectsResponse {projects: SearchProjectResult[];- total: number;}export interface UpdateMeRequest {diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex a3d24d9e69..8a1a2f7648 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -611,7 +611,6 @@ func parseQueryNumber(q string) (int, bool) {// searchResult holds a raw row from the dynamic search query.type searchResult struct {issue db.Issue- totalCount int64matchSource stringmatchedCommentContent string}@@ -861,7 +860,6 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,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,- COUNT(*) OVER() AS total_count,%s AS match_source,%s AS matched_comment_contentFROM issue i@@ -960,7 +958,6 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {&sr.issue.Number,&sr.issue.ProjectID,&sr.issue.Revision,- &sr.totalCount,&sr.matchSource,&sr.matchedCommentContent,); err != nil {@@ -989,11 +986,6 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {return}- var total int64- if len(results) > 0 {- total = results[0].totalCount- }-prefix := h.getIssuePrefix(ctx, wsUUID)fillSearch := h.newStatusCategoryFiller(ctx, wsUUID)resp := make([]SearchIssueResponse, len(results))@@ -1022,10 +1014,8 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {resp[i] = sir}- w.Header().Set("X-Total-Count", strconv.FormatInt(total, 10))writeJSON(w, http.StatusOK, map[string]any{"issues": resp,- "total": total,})}diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex bd05fca65c..5f8690a858 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -801,7 +801,6 @@ func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool)p.status, p.priority, p.lead_type, p.lead_id,p.start_date, p.due_date,p.created_at, p.updated_at,- COUNT(*) OVER() AS total_count,%s AS match_sourceFROM project pWHERE p.workspace_id = %s AND %s@@ -860,7 +859,6 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {type projectSearchRow struct {project db.Project- totalCount int64matchSource string}@@ -882,7 +880,6 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {&row.project.DueDate,&row.project.CreatedAt,&row.project.UpdatedAt,- &row.totalCount,&row.matchSource,); err != nil {return fmt.Errorf("scan: %w", err)@@ -907,11 +904,6 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {return}- var total int64- if len(results) > 0 {- total = results[0].totalCount- }-// Batch-fetch issue stats and resource countsstatsMap := make(map[string]db.GetProjectIssueStatsRow)resourceCountMap := make(map[string]int64)@@ -964,9 +956,7 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {resp[i] = spr}- w.Header().Set("X-Total-Count", strconv.FormatInt(total, 10))writeJSON(w, http.StatusOK, map[string]any{"projects": resp,- "total": total,})}diff --git a/server/internal/handler/search_response_test.go b/server/internal/handler/search_response_test.gonew file mode 100644index 0000000000..e2eb1ddc69--- /dev/null+++ b/server/internal/handler/search_response_test.go@@ -0,0 +1,49 @@+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestSearchIssuesOmitsExactTotal(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ recorder := httptest.NewRecorder()+ testHandler.SearchIssues(recorder, newRequest(http.MethodGet, "/api/issues/search?q=exact-total-contract-test", nil))+ assertSearchResponseOmitsExactTotal(t, recorder, "issues")+}++func TestSearchProjectsOmitsExactTotal(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ recorder := httptest.NewRecorder()+ testHandler.SearchProjects(recorder, newRequest(http.MethodGet, "/api/projects/search?q=exact-total-contract-test", nil))+ assertSearchResponseOmitsExactTotal(t, recorder, "projects")+}++func assertSearchResponseOmitsExactTotal(t *testing.T, recorder *httptest.ResponseRecorder, collectionKey string) {+ t.Helper()+ if recorder.Code != http.StatusOK {+ t.Fatalf("search status = %d: %s", recorder.Code, recorder.Body.String())+ }+ if got := recorder.Header().Get("X-Total-Count"); got != "" {+ t.Fatalf("search X-Total-Count = %q, want absent", got)+ }++ var payload map[string]json.RawMessage+ if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode search payload: %v", err)+ }+ if _, ok := payload[collectionKey]; !ok {+ t.Fatalf("search response missing %q: %s", collectionKey, recorder.Body.String())+ }+ if _, ok := payload["total"]; ok {+ t.Fatalf("search response unexpectedly contains exact total: %s", recorder.Body.String())+ }+}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex ebc93db665..3dd5f73d37 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -44,6 +44,22 @@ func TestBuildSearchQuery_SingleTerm(t *testing.T) {}}+func TestBuildSearchQuery_OmitsUnusedExactTotal(t *testing.T) {+ query, _ := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, []string{"done", "cancelled"})++ if strings.Contains(query, "COUNT(*) OVER()") || strings.Contains(query, "total_count") {+ t.Fatalf("search query should not calculate an unused exact total:\n%s", query)+ }+}++func TestBuildProjectSearchQuery_OmitsUnusedExactTotal(t *testing.T) {+ query, _ := buildProjectSearchQuery("Hello", []string{"Hello"}, false)++ if strings.Contains(query, "COUNT(*) OVER()") || strings.Contains(query, "total_count") {+ t.Fatalf("project search query should not calculate an unused exact total:\n%s", query)+ }+}+func TestBuildSearchQuery_CustomTerminalStatuses(t *testing.T) {terminalStatusKeys := []string{"done", "cancelled", "verified"}query, args := buildSearchQuery(