: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
fix(search): literal-substring matching for product tours (#62388)
Paul D'Ambrad7f47e8b21e1
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex 01ed3c95d640..cb6e6e7cea45 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -7,6 +7,7 @@ from posthog.api.shared import SearchMatchTypeSerializerMixinfrom products.cdp.backend.api.hog_function import HogFunctionMinimalSerializer, HogFunctionSerializerfrom products.dashboards.backend.api.dashboard import DashboardBasicSerializerfrom products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer+from products.product_tours.backend.api.product_tour import ProductTourSerializerfrom products.surveys.backend.api.survey import SurveySerializer# Each product that migrates its saved-list search onto apply_trigram_search appends its@@ -19,6 +20,7 @@ SEARCH_LIST_SERIALIZERS = [("hog_function_minimal", HogFunctionMinimalSerializer),("hog_function", HogFunctionSerializer),("survey", SurveySerializer),+ ("product_tour", ProductTourSerializer),]diff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex 1df500af3e58..722edc23d7bd 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -4,10 +4,8 @@ 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 Coalesce+from django.db.models import QuerySetfrom django.http import HttpResponse, JsonResponsefrom django.utils.text import slugifyfrom django.views.decorators.csrf import csrf_exempt@@ -23,19 +21,13 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import get_tokenfrom 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.helpers.trigram_search import DESCRIPTION_FIELD, MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_searchfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activityfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -101,7 +93,7 @@ def _validate_step_targeting(step: dict, idx: int):raise serializers.ValidationError(f"Step {idx + 1} requires an element to be selected")-class ProductTourSerializer(serializers.ModelSerializer):+class ProductTourSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):"""Read-only serializer for ProductTour."""internal_targeting_flag = MinimalFeatureFlagSerializer(read_only=True)@@ -130,6 +122,7 @@ class ProductTourSerializer(serializers.ModelSerializer):"created_by","updated_at","archived",+ "search_match_type",]read_only_fields = ["id", "created_at", "created_by", "updated_at"]@@ -795,33 +788,12 @@ class ProductTourViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, view@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")+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="product_tour.search",+ fields=(NAME_FIELD, DESCRIPTION_FIELD),+ tiebreakers=("name",),)def safely_get_queryset(self, queryset):diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex 4a57d3d79c1f..168df865ee78 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -284,7 +284,7 @@ class TestProductTour(APIBaseTest):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}")+ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": search})assert response.status_code == status.HTTP_200_OKresult_names = [r["name"] for r in response.json()["results"]]@@ -320,7 +320,7 @@ class TestProductTour(APIBaseTest):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}")+ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": search})assert response.status_code == status.HTTP_200_OKresult_ids = {r["id"] for r in response.json()["results"]}@@ -359,6 +359,55 @@ class TestProductTour(APIBaseTest):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']}"+ @parameterized.expand(+ [+ ("email in name", "[email protected]", "[email protected]"),+ ("uuid in name", "run 1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"),+ ("dotted identifier", "com.acme.billing tour", "com.acme.billing"),+ ]+ )+ def test_list_filter_by_search_matches_literal_substring_below_trigram_threshold(self, _name, tour_name, search):+ matching = ProductTour.objects.create(team=self.team, name=tour_name, content={"steps": []})+ ProductTour.objects.create(team=self.team, name="Totally unrelated", content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/", {"search": search})+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_id = {r["id"]: r["search_match_type"] for r in results}+ assert match_type_by_id.get(str(matching.id)) == "exact", (+ "a literal substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert all(r["name"] != "Totally unrelated" for r in results)++ def test_list_filter_by_search_returns_exact_first_with_match_type(self):+ for name in ("onboarding tour", "tour for onboarding", "onbarding flow", "Engineering tour"):+ ProductTour.objects.create(team=self.team, name=name, content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/?search=onboarding")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_name = {r["name"]: r["search_match_type"] for r in results}+ assert match_type_by_name == {+ "onboarding tour": "exact",+ "tour for onboarding": "exact",+ "onbarding flow": "similar",+ }++ match_types = [r["search_match_type"] for r in results]+ assert match_types == ["exact", "exact", "similar"], f"exact matches must rank first, got {match_types}"++ def test_list_filter_by_search_match_type_absent_without_search(self):+ ProductTour.objects.create(team=self.team, name="Alpha", content={"steps": []})++ response = self.client.get(f"/api/projects/{self.team.id}/product_tours/")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ assert results+ assert all("search_match_type" not in r for r in results)+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 eedee1767ed1..65b03ce77205 100644--- a/products/product_tours/frontend/generated/api.schemas.ts+++ b/products/product_tours/frontend/generated/api.schemas.ts@@ -119,6 +119,13 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+/*** Return the targeting flag filters, excluding the base exclusion properties.* @nullable@@ -152,6 +159,8 @@ export interface ProductTourApi {readonly created_by: UserBasicApireadonly updated_at: stringarchived?: boolean+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnumApi | null}export interface PaginatedProductTourListApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 988abd775739..0474e340f699 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26127,6 +26127,8 @@ export namespace Schemas {readonly created_by: UserBasic;readonly updated_at: string;archived?: boolean;+ /** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnum | null;}export interface PaginatedProductTourList {