:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(conversations): speed up ticket search via query rewrite and index (#73860)
Luke Belton4df630f9e5f1
diff --git a/posthog/migrations/1266_comment_convo_content_trgm.py b/posthog/migrations/1266_comment_convo_content_trgm.pynew file mode 100644index 000000000000..5e7b196e68d4--- /dev/null+++ b/posthog/migrations/1266_comment_convo_content_trgm.py@@ -0,0 +1,27 @@+from django.contrib.postgres.indexes import GinIndex, OpClass+from django.db import migrations, models+from django.db.models.functions import Upper++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # Concurrent index builds can't run in a transaction.+ atomic = False++ dependencies = [("posthog", "1265_delete_duckgresserverteam")]++ # On UPPER(content) because icontains compiles to UPPER(col) LIKE UPPER(pattern) on+ # Postgres. Partial on the conversations scope: posthog_comment is shared across+ # products and the ticket search always filters on it. pg_trgm is already installed+ # (migration 0034).+ operations = [+ SafeAddIndexConcurrently(+ model_name="comment",+ index=GinIndex(+ OpClass(Upper("content"), name="gin_trgm_ops"),+ name="comment_convo_content_trgm",+ condition=models.Q(scope="conversations_ticket"),+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 228eacb3aaed..8c8e4e3d6223 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1265_delete_duckgresserverteam+1266_comment_convo_content_trgmdiff --git a/posthog/models/comment/comment.py b/posthog/models/comment/comment.pyindex d03816cf760f..b88698db1aab 100644--- a/posthog/models/comment/comment.py+++ b/posthog/models/comment/comment.py@@ -1,6 +1,8 @@from typing import cast+from django.contrib.postgres.indexes import GinIndex, OpClassfrom django.db import models+from django.db.models.functions import Upperfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import get_was_impersonated@@ -47,6 +49,15 @@ class Comment(UUIDTModel, RootTeamMixin):fields=["team_id", "scope", "item_id", "deleted", "-created_at"],name="posthog_comment_convo_idx",),+ # Trigram index for conversations ticket search on message content. On UPPER(...)+ # because icontains compiles to UPPER(col) LIKE UPPER(pattern) on Postgres.+ # Partial: the table is shared across products, and the search always filters+ # on this scope.+ GinIndex(+ OpClass(Upper("content"), name="gin_trgm_ops"),+ name="comment_convo_content_trgm",+ condition=models.Q(scope="conversations_ticket"),+ ),]diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 7650d128a8b2..852489510334 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -25,7 +25,7 @@ from posthog.schema import HogQLQueryModifiers, MaterializationModefrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query-from posthog.models import ActivityLog, Comment, Organization, Tag, User+from posthog.models import ActivityLog, Comment, Organization, Tag, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.persons import create_person@@ -699,6 +699,36 @@ class TestTicketAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["count"], 0)+ def test_search_excludes_other_team_comments(self, mock_on_commit):+ # The comment pre-query filters by the request's team; a matching comment in+ # another team pointing at this ticket's id must not surface the ticket, while+ # the same content on a same-team ticket must — so a search that filters+ # everything out (or nothing) can't pass this test.+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ Comment.objects.create(+ team=other_team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="zebra migration question",+ )+ same_team_ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="zebra-session",+ distinct_id="zebra-user",+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(same_team_ticket.id),+ content="zebra migration question",+ )++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/?search=zebra")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)+ self.assertEqual(response.json()["results"][0]["id"], str(same_team_ticket.id))+def test_search_ignores_too_long_query(self, mock_on_commit):long_query = "a" * 201response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/?search={long_query}")diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 67831a6345e1..1e7d985c44f4 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -1,13 +1,14 @@from __future__ import annotationsimport json+import timeimport uuidfrom collections.abc import Sequencefrom datetime import timedeltafrom typing import Anyfrom django.db import transaction-from django.db.models import CharField, Exists, F, OrderBy, OuterRef, Q, QuerySet, Sum+from django.db.models import CharField, F, OrderBy, Q, QuerySet, Sumfrom django.db.models.functions import Castfrom django.http import Http404from django.utils import timezone@@ -54,6 +55,7 @@ from products.conversations.backend.events import (capture_ticket_priority_changed,capture_ticket_status_changed,)+from products.conversations.backend.metrics import TICKET_SEARCH_DURATION_SECONDSfrom products.conversations.backend.models import EmailChannel, Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom products.conversations.backend.person_lookup import _get_persons_by_email@@ -368,6 +370,29 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modpermission_classes = [IsAuthenticated, APIScopePermission]pagination_class = TicketPagination+ # Which search branch safely_get_queryset applied, for the latency histogram.+ _search_path: str | None = None++ def _filter_by_text_search(self, queryset: QuerySet, search: str) -> QuerySet:+ # Comment match as a non-correlated subquery: self-contained, so Postgres hashes+ # it once per query (scanning posthog_comment through its trigram index) instead+ # of probing comments per ticket the way a correlated EXISTS would. The ticket id+ # is cast to text rather than item_id to uuid — the id side is always a valid+ # UUID, while a malformed item_id row would make the whole search error.+ comment_match = Comment.objects.filter(+ team_id=self.team_id,+ scope="conversations_ticket",+ deleted=False,+ content__icontains=search,+ ).values("item_id")++ return queryset.alias(id_text=Cast("id", output_field=CharField())).filter(+ Q(anonymous_traits__name__icontains=search)+ | Q(anonymous_traits__email__icontains=search)+ | Q(email_subject__icontains=search)+ | Q(id_text__in=comment_match)+ )+def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:"""Filter tickets by team."""queryset = queryset.filter(team_id=self.team_id)@@ -477,28 +502,11 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod# that int() then rejects, which would 500 the request.ticket_number_search = search[1:] if search.startswith("#") else searchif ticket_number_search.isascii() and ticket_number_search.isdigit():+ self._search_path = "ticket_number"queryset = queryset.filter(ticket_number=int(ticket_number_search))else:- # EXISTS subquery: matches any comment in the ticket's conversation.- # Uses the (team_id, scope, item_id) composite index on Comment to- # narrow to per-ticket comments; EXISTS short-circuits on first match.- # If this becomes slow at scale (10k+ candidate tickets with broad- # filters), consider adding a GIN trigram index on Comment.content:- # GinIndex(name="comment_content_trigram", fields=["content"],- # opclasses=["gin_trgm_ops"])- comment_match = Comment.objects.filter(- team_id=OuterRef("team_id"),- scope="conversations_ticket",- item_id=Cast(OuterRef("id"), output_field=CharField()),- content__icontains=search,- deleted=False,- )- queryset = queryset.filter(- Q(anonymous_traits__name__icontains=search)- | Q(anonymous_traits__email__icontains=search)- | Q(email_subject__icontains=search)- | Exists(comment_match)- )+ self._search_path = "text"+ queryset = self._filter_by_text_search(queryset, search)sla_param = self.request.query_params.get("sla")if sla_param:@@ -768,8 +776,9 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.ModOpenApiTypes.STR,location=OpenApiParameter.QUERY,description=(- "Free-text search. A numeric value matches a ticket number exactly; otherwise matches "- "against the customer's name or email (case-insensitive, partial match)."+ "Free-text search. A numeric value (optionally prefixed with `#`) matches a ticket number "+ "exactly; otherwise matches against the customer's name or email, the email subject, or "+ "message content (case-insensitive, partial match)."),),OpenApiParameter(@@ -820,18 +829,27 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod)def list(self, request, *args, **kwargs):"""List tickets with person data attached."""- queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)-- if page is not None:- self._attach_persons_to_tickets(page)- serializer = self.get_serializer(page, many=True)- return self.get_paginated_response(serializer.data)-- tickets = list(queryset)- self._attach_persons_to_tickets(tickets)- serializer = self.get_serializer(tickets, many=True)- return Response(serializer.data)+ # _search_path starts as the class default (None) on each request's fresh+ # viewset instance; filter_queryset sets it when a search filter is applied.+ start = time.perf_counter()+ try:+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)++ if page is not None:+ self._attach_persons_to_tickets(page)+ serializer = self.get_serializer(page, many=True)+ return self.get_paginated_response(serializer.data)++ tickets = list(queryset)+ self._attach_persons_to_tickets(tickets)+ serializer = self.get_serializer(tickets, many=True)+ return Response(serializer.data)+ finally:+ if self._search_path is not None:+ TICKET_SEARCH_DURATION_SECONDS.labels(search_path=self._search_path).observe(+ time.perf_counter() - start+ )def retrieve(self, request, *args, **kwargs):"""Get single ticket and mark as read by team."""diff --git a/products/conversations/backend/metrics.py b/products/conversations/backend/metrics.pynew file mode 100644index 000000000000..f76e3fbaa3fa--- /dev/null+++ b/products/conversations/backend/metrics.py@@ -0,0 +1,8 @@+from prometheus_client import Histogram++TICKET_SEARCH_DURATION_SECONDS = Histogram(+ "posthog_support_ticket_search_duration_seconds",+ "End-to-end duration of support ticket list requests that include a search term",+ labelnames=["search_path"], # ticket_number | text+ buckets=(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, float("inf")),+)diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 4efd9152b5c6..5f48f69fc061 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -1237,7 +1237,7 @@ export type ConversationsTicketsListParams = {*/priority?: string/**- * Free-text search. A numeric value matches a ticket number exactly; otherwise matches against the customer's name or email (case-insensitive, partial match).+ * Free-text search. A numeric value (optionally prefixed with `#`) matches a ticket number exactly; otherwise matches against the customer's name or email, the email subject, or message content (case-insensitive, partial match).*/search?: string/**diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.tsindex a0525bb9c7c8..dc3af88295f1 100644--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts@@ -1,4 +1,16 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'@@ -720,9 +732,15 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([try {const response = await api.conversationsTickets.list(params)+ // Drop responses that were superseded while in flight, so a slow reply+ // to an older query can't overwrite newer results.+ breakpoint()actions.setTickets(response.results || [])actions.setTotalCount(response.count ?? response.results?.length ?? 0)- } catch {+ } catch (error: any) {+ if (isBreakpoint(error)) {+ throw error+ }lemonToast.error('Failed to load tickets')actions.setTicketsLoading(false)}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 305e9b5577a9..de96dde2022a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -72204,7 +72204,7 @@ export namespace Schemas {*/priority?: string;/**- * Free-text search. A numeric value matches a ticket number exactly; otherwise matches against the customer's name or email (case-insensitive, partial match).+ * Free-text search. A numeric value (optionally prefixed with `#`) matches a ticket number exactly; otherwise matches against the customer's name or email, the email subject, or message content (case-insensitive, partial match).*/search?: string;/**diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 39fa84069e71..a71a898f0e31 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -79,7 +79,7 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({.string().optional().describe(- "Free-text search. A numeric value matches a ticket number exactly; otherwise matches against the customer's name or email (case-insensitive, partial match)."+ "Free-text search. A numeric value (optionally prefixed with `#`) matches a ticket number exactly; otherwise matches against the customer's name or email, the email subject, or message content (case-insensitive, partial match)."),sla: zod.enum(['at-risk', 'breached', 'on-track'])diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.jsonindex 80edfbc4458f..bd47dee3bbc6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json@@ -57,7 +57,7 @@"type": "string"},"search": {- "description": "Free-text search. A numeric value matches a ticket number exactly; otherwise matches against the customer's name or email (case-insensitive, partial match).",+ "description": "Free-text search. A numeric value (optionally prefixed with `#`) matches a ticket number exactly; otherwise matches against the customer's name or email, the email subject, or message content (case-insensitive, partial match).","type": "string"},"sla": {