: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(product-tours): server-side fuzzy search via pg_trgm (#57537)
Paul D'Ambraa148e786b396
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 3997bbb229b2..858f3938c77a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5115,8 +5115,11 @@ const api = {},productTours: {- async list(): Promise<PaginatedResponse<ProductTour>> {- return await new ApiRequest().productTours().get()+ async list({ search }: { search?: string } = {}): Promise<PaginatedResponse<ProductTour>> {+ return await new ApiRequest()+ .productTours()+ .withQueryString(search ? { search } : {})+ .get()},async get(tourId: ProductTour['id']): Promise<ProductTour> {return await new ApiRequest().productTour(tourId).get()diff --git a/frontend/src/scenes/product-tours/productToursLogic.ts b/frontend/src/scenes/product-tours/productToursLogic.tsindex b7c3b6c207ba..fc47649de520 100644--- a/frontend/src/scenes/product-tours/productToursLogic.ts+++ b/frontend/src/scenes/product-tours/productToursLogic.ts@@ -8,7 +8,6 @@ import api, { PaginatedResponse } from 'lib/api'import { dayjs } from 'lib/dayjs'import { uuid } from 'lib/utils'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { createFuse } from 'lib/utils/fuseSearch'import { addProductIntent } from 'lib/utils/product-intents'import { sceneConfigurations } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'@@ -265,7 +264,8 @@ export const productToursLogic = kea<productToursLogicType>([productTours: {__default: [] as ProductTour[],loadProductTours: async () => {- const response: PaginatedResponse<ProductTour> = await api.productTours.list()+ const search = values.searchTerm?.trim() || undefined+ const response: PaginatedResponse<ProductTour> = await api.productTours.list({ search })return response.results},deleteProductTour: async (id: string) => {@@ -341,6 +341,10 @@ export const productToursLogic = kea<productToursLogicType>([],}),listeners(({ actions }) => ({+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(250)+ actions.loadProductTours()+ },setTab: ({ tab }) => {actions.setFilters({ archived: tab === ProductToursTabs.Archived })},@@ -404,25 +408,12 @@ export const productToursLogic = kea<productToursLogicType>([})),selectors({filteredProductTours: [- (s) => [s.productTours, s.searchTerm, s.filters],- (productTours: ProductTour[], searchTerm: string, filters: ProductToursFilters) => {- let filtered = productTours-- if (searchTerm) {- const fuse = createFuse(filtered, {- keys: ['name', 'description'],- ignoreLocation: true,- })- filtered = fuse.search(searchTerm).map((result) => result.item)- }-+ (s) => [s.productTours, s.filters],+ (productTours: ProductTour[], filters: ProductToursFilters) => {if (filters.archived) {- filtered = filtered.filter((tour: ProductTour) => tour.archived)- } else {- filtered = filtered.filter((tour: ProductTour) => !tour.archived)+ return productTours.filter((tour: ProductTour) => tour.archived)}-- return filtered+ return productTours.filter((tour: ProductTour) => !tour.archived)},],breadcrumbs: [diff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex 8b896f933fd6..d049a7b7c9c6 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -4,15 +4,20 @@ import itertoolsfrom typing import Any, castfrom django.conf import settings+from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.db import transaction+from django.db.models import F, Q, QuerySet, Value+from django.db.models.functions import Coalescefrom django.http import HttpResponse, JsonResponsefrom django.utils.text import slugifyfrom django.views.decorators.csrf import csrf_exempt-from drf_spectacular.utils import OpenApiResponse, extend_schema+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom nanoid import generate-from rest_framework import exceptions, filters, serializers, status, viewsets+from opentelemetry import trace+from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -25,6 +30,13 @@ from posthog.cloud_utils import is_cloudfrom posthog.constants import PRODUCT_TOUR_TARGETING_FLAG_PREFIXfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import generate_exception_response+from posthog.helpers.trigram_search import (+ DESCRIPTION_SCORE_WEIGHT,+ MAX_SEARCH_LENGTH,+ MIN_DESCRIPTION_TRIGRAM_SIMILARITY,+ MIN_NAME_TRIGRAM_SIMILARITY,+ normalize_search_term,+)from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activityfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -37,6 +49,7 @@ from products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveylogger = logging.getLogger(__name__)+tracer = trace.get_tracer(__name__)TOUR_GENERATION_MODEL = "claude-haiku-4-5"@@ -737,6 +750,17 @@ class GenerateResponseSerializer(serializers.Serializer):steps = GenerateStepResponseSerializer(many=True)+@extend_schema_view(+ list=extend_schema(+ parameters=[+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ description="Fuzzy match against product tour `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.",+ ),+ ],+ ),+)class ProductTourViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):scope_object = "product_tour"scope_object_read_actions = ["list", "retrieve", "draft_status"]@@ -751,16 +775,66 @@ class ProductTourViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, view"generate",]queryset = ProductTour.all_objects.select_related("internal_targeting_flag", "linked_flag", "created_by").all()- filter_backends = [filters.SearchFilter]- search_fields = ["name", "description"]def get_serializer_class(self) -> type[serializers.Serializer]:if self.request.method in ("POST", "PATCH"):return ProductTourSerializerCreateUpdateOnlyreturn ProductTourSerializer+ @tracer.start_as_current_span("ProductTourViewSet.list")+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ response = super().list(request, *args, **kwargs)+ if request.query_params.get("search"):+ data = response.data if isinstance(response.data, dict) else {}+ results_len = data.get("count", len(data.get("results", [])))+ span = trace.get_current_span()+ span.set_attribute("product_tour.search.result_count", results_len)+ span.set_attribute("product_tour.search.empty", results_len == 0)+ return response++ @staticmethod+ @tracer.start_as_current_span("ProductTourViewSet._apply_search")+ def _apply_search(queryset: QuerySet, search: str) -> QuerySet:+ search = normalize_search_term(search)+ span = trace.get_current_span()+ span.set_attribute("product_tour.search.length", len(search))+ if not search:+ return queryset++ zero = Value(0.0)+ name_word_score = Coalesce(TrigramWordSimilarity(search, "name"), zero)+ name_full_score = Coalesce(TrigramSimilarity("name", search), zero)+ description_word_score = Coalesce(TrigramWordSimilarity(search, "description"), zero)++ return (+ queryset.annotate(+ _name_word=name_word_score,+ _name_full=name_full_score,+ _description_word=description_word_score,+ )+ .filter(+ Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)+ | Q(_description_word__gt=MIN_DESCRIPTION_TRIGRAM_SIMILARITY)+ )+ .annotate(+ _name_match_score=F("_name_word") + F("_name_full"),+ _description_match_score=F("_description_word"),+ )+ .annotate(_search_score=F("_name_match_score") + F("_description_match_score") * DESCRIPTION_SCORE_WEIGHT)+ .order_by("-_search_score", "name")+ )+def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team_id)+ queryset = queryset.filter(team_id=self.team_id)+ if self.action == "list":+ search = self.request.GET.get("search")+ if search:+ if len(search) > MAX_SEARCH_LENGTH:+ raise serializers.ValidationError(+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}+ )+ queryset = self._apply_search(queryset, search)+ return querysetdef perform_destroy(self, instance: ProductTour) -> None:"""Hard delete the tour and clean up related resources."""diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex c3d229850543..b782fa78fb0e 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -241,6 +241,124 @@ class TestProductTour(APIBaseTest):call_args = mock_report.call_argsassert call_args[0][2]["creation_context"] == "toolbar"+ @parameterized.expand(+ [+ (+ "exact match wins over partial matches",+ ["Ad Sales", "Email Sales", "Sales", "Sales Funnel", "Weekly Sales", "Unrelated"],+ "Sales",+ "Sales",+ ["Unrelated"],+ ),+ (+ "typo / transposition still matches via trigram",+ ["Onboarding tour", "Unrelated"],+ "onbarding",+ "Onboarding tour",+ ["Unrelated"],+ ),+ (+ "prefix-as-you-type",+ ["Marketing tour", "Engineering tour"],+ "Marke",+ "Marketing tour",+ ["Engineering tour"],+ ),+ (+ "case-insensitive: lower",+ ["NPS Tour", "Engineering tour"],+ "nps",+ "NPS Tour",+ ["Engineering tour"],+ ),+ (+ "case-insensitive: upper",+ ["NPS Tour", "Engineering tour"],+ "NPS",+ "NPS Tour",+ ["Engineering tour"],+ ),+ ]+ )+ def test_list_filter_by_search_relevance(self, _name, tour_names, search, expected_first, excluded):+ for name in tour_names:+ ProductTour.objects.create(team=self.team, name=name, content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/?search={search}")+ assert response.status_code == status.HTTP_200_OK+ result_names = [r["name"] for r in response.json()["results"]]++ assert result_names, f"expected at least one match for {search!r}, got nothing"+ assert result_names[0] == expected_first, f"expected {expected_first!r} first, got {result_names}"+ for name in excluded:+ assert name not in result_names, f"expected {name!r} excluded, got {result_names}"++ def test_list_filter_by_search_matches_description_with_lower_rank_than_name(self):+ name_match = ProductTour.objects.create(team=self.team, name="revenue", content={"steps": []})+ description_match = ProductTour.objects.create(+ team=self.team,+ name="Q4 review",+ description="Quarterly revenue tour",+ content={"steps": []},+ )+ ProductTour.objects.create(team=self.team, name="Unrelated", content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/?search=revenue")+ assert response.status_code == status.HTTP_200_OK+ result_ids = [r["id"] for r in response.json()["results"]]++ assert result_ids[:2] == [str(name_match.id), str(description_match.id)]+ assert all(r["name"] != "Unrelated" for r in response.json()["results"])++ @parameterized.expand(+ [+ ("whitespace-only", " "),+ ("empty", ""),+ ]+ )+ def test_list_filter_by_search_blank_returns_all(self, _name, search):+ a = ProductTour.objects.create(team=self.team, name="Alpha", content={"steps": []})+ b = ProductTour.objects.create(team=self.team, name="Beta", content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/?search={search}")+ assert response.status_code == status.HTTP_200_OK+ result_ids = {r["id"] for r in response.json()["results"]}++ assert {str(a.id), str(b.id)}.issubset(result_ids)++ @parameterized.expand(+ [+ ("plain symbols", "&|!"),+ ("sql-injection-shaped", "'; DROP TABLE--"),+ ]+ )+ def test_list_filter_by_search_pathological_input_does_not_500(self, _name, search):+ ProductTour.objects.create(team=self.team, name="Tour overview", content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": search})+ assert response.status_code == status.HTTP_200_OK++ def test_list_filter_by_search_nul_bytes_do_not_500(self):+ ProductTour.objects.create(team=self.team, name="Alpha", content={"steps": []})+ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": "\x00\x00\x00"})+ assert response.status_code == status.HTTP_200_OK++ @parameterized.expand(+ [+ ("at cap (200)", 200, status.HTTP_200_OK),+ ("just over cap (201)", 201, status.HTTP_400_BAD_REQUEST),+ ("very long (10k)", 10_000, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_list_filter_by_search_enforces_length_cap(self, _name, length, expected_status):+ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": "a" * length})+ assert response.status_code == expected_status++ if expected_status == status.HTTP_400_BAD_REQUEST:+ body = response.json()+ assert body["attr"] == "search", f"expected error scoped to 'search', got {body}"+ assert "200 characters" in body["detail"], f"expected error detail to mention the cap, got {body['detail']}"+class TestProductTourAnalyticsMetadata(APIBaseTest):@parameterized.expand(diff --git a/products/product_tours/frontend/generated/api.schemas.ts b/products/product_tours/frontend/generated/api.schemas.tsindex 55658dec920f..6cfb1ac11cf9 100644--- a/products/product_tours/frontend/generated/api.schemas.ts+++ b/products/product_tours/frontend/generated/api.schemas.ts@@ -274,7 +274,7 @@ export type ProductToursListParams = {*/offset?: number/**- * A search term.+ * Fuzzy match against product tour `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0efe51413cde..e64b3563fff9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45465,7 +45465,7 @@ export namespace Schemas {*/offset?: number;/**- * A search term.+ * Fuzzy match against product tour `name` and `description` using Postgres trigram word similarity. Supports typos and prefix-as-you-type.*/search?: string;};