Skip to content

: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.

fix(search): literal-substring matching for hog functions (#62384)

Paul D'Ambrab9784e05c322
diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.py
index a63843e3a93f..9644b47583cd 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 serializers
from posthog.api.organization_member import OrganizationMemberSerializer
from posthog.api.shared import SearchMatchTypeSerializerMixin
+from products.cdp.backend.api.hog_function import HogFunctionMinimalSerializer, HogFunctionSerializer
from products.dashboards.backend.api.dashboard import DashboardBasicSerializer
from products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer
@@ -14,6 +15,8 @@ SEARCH_LIST_SERIALIZERS = [
("insight", InsightSerializer),
("organization_member", OrganizationMemberSerializer),
("dashboard_basic", DashboardBasicSerializer),
+ ("hog_function_minimal", HogFunctionMinimalSerializer),
+ ("hog_function", HogFunctionSerializer),
]
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index b42320475aec..7a9abb100489 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -1,10 +1,8 @@
import json
from typing import Any, Optional, cast
-from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity
from 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 Q, QuerySet
import structlog
import posthoganalytics
@@ -23,7 +21,7 @@ from posthog.api.app_metrics2 import AppMetricsMixin
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.shared import UserBasicSerializer
+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.utils import action, log_activity_from_viewset
from posthog.cdp.services.icons import CDPIconsService
from posthog.cdp.site_functions import get_transpiled_function
@@ -36,13 +34,7 @@ from posthog.cdp.validation import (
generate_template_bytecode,
)
from posthog.exceptions_capture import capture_exception
-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_search
from posthog.models import Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.plugins.plugin_server_api import create_hog_invocation_test
@@ -72,7 +64,7 @@ class HogFunctionStatusSerializer(serializers.Serializer):
tokens: serializers.IntegerField = serializers.IntegerField()
-class HogFunctionMinimalSerializer(serializers.ModelSerializer):
+class HogFunctionMinimalSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
status = HogFunctionStatusSerializer(read_only=True, required=False, allow_null=True)
template = HogFunctionTemplateSerializer(read_only=True)
@@ -94,6 +86,7 @@ class HogFunctionMinimalSerializer(serializers.ModelSerializer):
"template",
"status",
"execution_order",
+ "search_match_type",
]
read_only_fields = fields
@@ -176,6 +169,7 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
"execution_order",
"_create_in_folder",
"batch_export_id",
+ "search_match_type",
]
read_only_fields = [
"id",
@@ -505,33 +499,12 @@ class HogFunctionViewSet(
@staticmethod
@tracer.start_as_current_span("HogFunctionViewSet._apply_search")
def _apply_search(queryset: QuerySet, search: str) -> QuerySet:
- search = normalize_search_term(search)
- span = trace.get_current_span()
- span.set_attribute("hog_function.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="hog_function.search",
+ fields=(NAME_FIELD, DESCRIPTION_FIELD),
+ tiebreakers=("name",),
)
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 08f040d268b8..7d92418e0960 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -1740,7 +1740,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
for name in function_names:
HogFunction.objects.create(team=self.team, name=name, type="destination", hog="return event")
- response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?search={search}")
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/", {"search": search})
assert response.status_code == status.HTTP_200_OK
result_names = [r["name"] for r in response.json()["results"]]
@@ -1777,7 +1777,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
a = HogFunction.objects.create(team=self.team, name="Alpha", type="destination", hog="return event")
b = HogFunction.objects.create(team=self.team, name="Beta", type="destination", hog="return event")
- response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?search={search}")
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/", {"search": search})
assert response.status_code == status.HTTP_200_OK
result_ids = {r["id"] for r in response.json()["results"]}
@@ -1838,6 +1838,74 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
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 webhook", "com.acme.billing"),
+ ]
+ )
+ def test_list_filter_by_search_matches_literal_substring_below_trigram_threshold(
+ self, _name, function_name, search
+ ):
+ matching = HogFunction.objects.create(
+ team=self.team, name=function_name, type="destination", hog="return event"
+ )
+ HogFunction.objects.create(team=self.team, name="Totally unrelated", type="destination", hog="return event")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/", {"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 ("slack notification", "notification slack", "slcak metrics", "Engineering metrics"):
+ HogFunction.objects.create(team=self.team, name=name, type="destination", hog="return event")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?search=slack")
+ 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 == {
+ "slack notification": "exact",
+ "notification slack": "exact",
+ "slcak metrics": "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):
+ HogFunction.objects.create(team=self.team, name="Alpha", type="destination", hog="return event")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/")
+ 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)
+
+ def test_list_filter_by_search_surfaces_match_type_on_full_serializer(self):
+ matching = HogFunction.objects.create(
+ team=self.team, name="[email protected]", type="destination", hog="return event"
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_functions/",
+ {"search": "[email protected]", "full": "true"},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ match_type_by_id = {r["id"]: r["search_match_type"] for r in response.json()["results"]}
+ assert match_type_by_id.get(str(matching.id)) == "exact", (
+ "the full (?full=true) serializer must also surface search_match_type — it redeclares Meta.fields"
+ )
+
def test_can_update_with_null_filters(self):
# First create a function with filters
response = self.client.post(
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index 53071ed686d1..25ef970225fc 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -169,6 +169,13 @@ export interface HogFunctionStatusApi {
tokens: number
}
+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]
+
+export const SearchMatchTypeEnumApi = {
+ Exact: 'exact',
+ Similar: 'similar',
+} as const
+
export interface HogFunctionMinimalApi {
readonly id: string
/** @nullable */
@@ -188,6 +195,8 @@ export interface HogFunctionMinimalApi {
readonly status: HogFunctionStatusApi | null
/** @nullable */
readonly execution_order: number | null
+ /** 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 PaginatedHogFunctionMinimalListApi {
@@ -430,6 +439,8 @@ export interface HogFunctionApi {
_create_in_folder?: string
/** @nullable */
readonly batch_export_id: string | null
+ /** 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
}
/**
@@ -505,6 +516,8 @@ export interface PatchedHogFunctionApi {
_create_in_folder?: string
/** @nullable */
readonly batch_export_id?: string | null
+ /** 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
}
/**
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index 582f661414e5..bae6858f3318 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -1394,6 +1394,11 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
batch_export_id: zod.uuid().nullable(),
+ search_match_type: zod
+ .union([zod.enum(['exact', 'similar']), zod.null()])
+ .describe(
+ '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`.'
+ ),
})
.describe('Full function configuration to test.'),
globals: zod
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 186d739f676c..52fddc725384 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20431,6 +20431,8 @@ export namespace Schemas {
_create_in_folder?: string;
/** @nullable */
readonly batch_export_id: string | null;
+ /** 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;
}
/**
@@ -20482,6 +20484,8 @@ export namespace Schemas {
readonly status: HogFunctionStatus | null;
/** @nullable */
readonly execution_order: number | null;
+ /** 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 HogInvocationResult {
@@ -30780,6 +30784,8 @@ export namespace Schemas {
_create_in_folder?: string;
/** @nullable */
readonly batch_export_id?: string | null;
+ /** 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;
}
/**
diff --git a/services/mcp/src/generated/cdp_functions/api.ts b/services/mcp/src/generated/cdp_functions/api.ts
index 6577fae2e2f0..67831fda594c 100644
--- a/services/mcp/src/generated/cdp_functions/api.ts
+++ b/services/mcp/src/generated/cdp_functions/api.ts
@@ -937,6 +937,12 @@ export const HogFunctionsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe('Execution priority for transformations. Lower values run first.'),
_create_in_folder: zod.string().optional(),
batch_export_id: zod.uuid().nullish(),
+ search_match_type: zod
+ .union([zod.enum(['exact', 'similar']), zod.null()])
+ .optional()
+ .describe(
+ '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`.'
+ ),
})
.describe('Full function configuration to test.'),
globals: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
index 55d101bac6e0..059078085158 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cdp-functions-invocations-create.json
@@ -582,6 +582,18 @@
],
"description": "Display name for the function."
},
+ "search_match_type": {
+ "anyOf": [
+ {
+ "enum": ["exact", "similar"],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "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`."
+ },
"status": {
"anyOf": [
{