: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 alerts (#62389)
Paul D'Ambrad47db4c05248
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex cb6e6e7cea45..3a75a4feff6e 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -4,6 +4,7 @@ from rest_framework import serializersfrom posthog.api.organization_member import OrganizationMemberSerializerfrom posthog.api.shared import SearchMatchTypeSerializerMixin+from products.alerts.backend.api.alert import AlertSerializerfrom 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@@ -21,6 +22,7 @@ SEARCH_LIST_SERIALIZERS = [("hog_function", HogFunctionSerializer),("survey", SurveySerializer),("product_tour", ProductTourSerializer),+ ("alert", AlertSerializer),]diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex 71311f6070ad..5b93670c6bcf 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -1,9 +1,7 @@import uuidfrom zoneinfo import ZoneInfo-from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity-from django.db.models import F, OuterRef, Q, QuerySet, Subquery, Value-from django.db.models.functions import Coalesce+from django.db.models import OuterRef, QuerySet, Subqueryfrom drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_viewfrom rest_framework import serializers, viewsets@@ -23,9 +21,9 @@ from posthog.schema import (from posthog.api.documentation import extend_schema_fieldfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.event_usage import get_request_analytics_properties-from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, MIN_NAME_TRIGRAM_SIMILARITY, normalize_search_term+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_searchfrom posthog.models import Userfrom posthog.resource_limits import LimitKey, check_count_limitfrom posthog.schema_migrations.upgrade_manager import upgrade_query@@ -180,7 +178,7 @@ class RelativeDateTimeField(serializers.DateTimeField):return data-class AlertSerializer(serializers.ModelSerializer):+class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)checks = AlertCheckSerializer(many=True,@@ -301,6 +299,7 @@ class AlertSerializer(serializers.ModelSerializer):"investigation_agent_enabled","investigation_gates_notifications","investigation_inconclusive_action",+ "search_match_type",]read_only_fields = ["id",@@ -787,22 +786,12 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):@staticmethoddef _apply_search(queryset: QuerySet, search: str) -> QuerySet:- search = normalize_search_term(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)-- return (- queryset.annotate(- _name_word=name_word_score,- _name_full=name_full_score,- )- .filter(Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY) | Q(_name_full__gt=MIN_NAME_TRIGRAM_SIMILARITY))- .annotate(_search_score=F("_name_word") + F("_name_full"))- .order_by("-_search_score", "-created_at")+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="alert.search",+ fields=(NAME_FIELD,),+ tiebreakers=("-created_at",),)CHECKS_DEFAULT_LIMIT = 5diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.pyindex 94df98a0affe..6318d5c29bdf 100644--- a/products/alerts/backend/api/test/test_alert.py+++ b/products/alerts/backend/api/test/test_alert.py@@ -1351,6 +1351,54 @@ class TestAlertListFilters(APIBaseTest):assert result_names == ["Revenue other"]+ @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 alert", "com.acme.billing"),+ ]+ )+ def test_list_filter_by_search_matches_literal_substring_below_trigram_threshold(+ self, _name: str, alert_name: str, search: str+ ) -> None:+ self._create_alert(alert_name)+ self._create_alert("Totally unrelated")++ response = self.client.get(f"/api/projects/{self.team.id}/alerts", {"search": search})+ results = response.json()["results"]++ match_type_by_name = {a["name"]: a["search_match_type"] for a in results}+ assert match_type_by_name.get(alert_name) == "exact", (+ "a literal substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert all(a["name"] != "Totally unrelated" for a in results)++ def test_list_filter_by_search_returns_exact_first_with_match_type(self) -> None:+ for name in ("revenue spike", "spike in revenue", "reveneu drop", "Unrelated alert"):+ self._create_alert(name)++ response = self.client.get(f"/api/projects/{self.team.id}/alerts", {"search": "revenue"})+ results = response.json()["results"]++ match_type_by_name = {a["name"]: a["search_match_type"] for a in results}+ assert match_type_by_name == {+ "revenue spike": "exact",+ "spike in revenue": "exact",+ "reveneu drop": "similar",+ }++ match_types = [a["search_match_type"] for a 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) -> None:+ self._create_alert("Revenue spike")++ response = self.client.get(f"/api/projects/{self.team.id}/alerts")+ results = response.json()["results"]++ assert results+ assert all("search_match_type" not in a for a in results)+@parameterized.expand([("search_length_cap", {"search": "a" * 201}, "search"),diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.tsindex 59f0d878685b..ef5181529597 100644--- a/products/alerts/frontend/generated/api.schemas.ts+++ b/products/alerts/frontend/generated/api.schemas.ts@@ -421,6 +421,13 @@ export const InvestigationInconclusiveActionEnumApi = {Suppress: 'suppress',} as const+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+export interface AlertApi {readonly id: stringreadonly created_by: UserBasicApi@@ -489,6 +496,8 @@ export interface AlertApi {* * `notify` - Notify* * `suppress` - Suppress */investigation_inconclusive_action?: InvestigationInconclusiveActionEnumApi+ /** 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 PaginatedAlertListApi {@@ -568,6 +577,8 @@ export interface PatchedAlertApi {* * `notify` - Notify* * `suppress` - Suppress */investigation_inconclusive_action?: InvestigationInconclusiveActionEnumApi+ /** 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 AlertSimulateApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 845414d41f33..c61a5a192a1e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7575,6 +7575,8 @@ export namespace Schemas {* * `notify` - Notify* * `suppress` - Suppress */investigation_inconclusive_action?: InvestigationInconclusiveActionEnum;+ /** 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 AlertSimulate {@@ -29366,6 +29368,8 @@ export namespace Schemas {* * `notify` - Notify* * `suppress` - Suppress */investigation_inconclusive_action?: InvestigationInconclusiveActionEnum;+ /** 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 PatchedAnnotation {