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.

feat(hog-functions): server-side fuzzy search via pg_trgm (#57440)

Paul D'Ambra17c942bd90a7
diff --git a/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx b/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
index 2385d7e9ec9d..42e9abe7fd23 100644
--- a/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
+++ b/frontend/src/scenes/hog-functions/list/hogFunctionsListLogic.tsx
@@ -1,4 +1,3 @@
-import FuseClass from 'fuse.js'
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
@@ -9,7 +8,6 @@ import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { objectsEqual } from 'lib/utils'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
-import { createFuse } from 'lib/utils/fuseSearch'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'
@@ -20,8 +18,6 @@ import type { hogFunctionsListLogicType } from './hogFunctionsListLogicType'
export const CDP_TEST_HIDDEN_FLAG = '[CDP-TEST-HIDDEN]'
const EMPTY_MANUAL_FUNCTIONS: HogFunctionType[] = []
-// Helping kea-typegen navigate the exported default class for Fuse
-export interface Fuse extends FuseClass<HogFunctionType> {}
export type HogFunctionListFilters = {
search?: string
@@ -99,10 +95,12 @@ export const hogFunctionsListLogic = kea<hogFunctionsListLogicType>([
[] as HogFunctionType[],
{
loadHogFunctions: async () => {
+ const search = values.filters.search?.trim() || undefined
return (
await api.hogFunctions.list({
filter_groups: props.forceFilterGroups,
types: [props.type, ...(props.additionalTypes || [])],
+ search,
// TODO: This is a temporary fix. We need proper server-side pagination
// once we rework the data pipelines UI and batch exports is no longer
// part of the same list
@@ -153,9 +151,19 @@ export const hogFunctionsListLogic = kea<hogFunctionsListLogicType>([
selectors({
loading: [(s) => [s.hogFunctionsLoading], (hogFunctionsLoading) => hogFunctionsLoading],
sortedHogFunctions: [
- (s) => [s.hogFunctions, (_, props) => props.manualFunctions ?? EMPTY_MANUAL_FUNCTIONS],
- (hogFunctions, manualFunctions): HogFunctionType[] => {
- const enabledFirst = [...hogFunctions, ...manualFunctions].sort(
+ (s) => [s.hogFunctions, s.filters, (_, props) => props.manualFunctions ?? EMPTY_MANUAL_FUNCTIONS],
+ (
+ hogFunctions: HogFunctionType[],
+ filters: HogFunctionListFilters,
+ manualFunctions: HogFunctionType[]
+ ): HogFunctionType[] => {
+ const search = filters.search?.trim().toLowerCase()
+ const filteredManual = search
+ ? manualFunctions.filter(
+ (f) => f.name?.toLowerCase().includes(search) || f.description?.toLowerCase().includes(search)
+ )
+ : manualFunctions
+ const enabledFirst = [...hogFunctions, ...filteredManual].sort(
(a, b) => Number(b.enabled) - Number(a.enabled)
)
return enabledFirst
@@ -167,21 +175,12 @@ export const hogFunctionsListLogic = kea<hogFunctionsListLogicType>([
return hogFunctions.filter((hogFunction) => hogFunction.enabled)
},
],
- hogFunctionsFuse: [
- (s) => [s.sortedHogFunctions],
- (hogFunctions): Fuse => {
- return createFuse(hogFunctions || [], {
- keys: ['name', 'description'],
- })
- },
- ],
-
filteredHogFunctions: [
- (s) => [s.filters, s.sortedHogFunctions, s.hogFunctionsFuse, s.user],
- (filters, hogFunctions, hogFunctionsFuse, user): HogFunctionType[] => {
- const { search, showPaused, createdBy } = filters
+ (s) => [s.filters, s.sortedHogFunctions, s.user],
+ (filters, hogFunctions, user): HogFunctionType[] => {
+ const { showPaused, createdBy } = filters
- return (search ? hogFunctionsFuse.search(search).map((x) => x.item) : hogFunctions).filter((x) => {
+ return hogFunctions.filter((x) => {
if (!shouldShowHogFunction(x, user)) {
return false
}
@@ -208,6 +207,16 @@ export const hogFunctionsListLogic = kea<hogFunctionsListLogicType>([
}),
listeners(({ actions }) => ({
+ setFilters: async ({ filters }, breakpoint) => {
+ if (filters.search === undefined) {
+ return
+ }
+ await breakpoint(250)
+ actions.loadHogFunctions()
+ },
+ resetFilters: () => {
+ actions.loadHogFunctions()
+ },
saveHogFunctionOrderSuccess: () => {
actions.setReorderModalOpen(false)
lemonToast.success('Order updated successfully')
diff --git a/posthog/api/hog_function.py b/posthog/api/hog_function.py
index 4da194c9bbcc..207759b048be 100644
--- a/posthog/api/hog_function.py
+++ b/posthog/api/hog_function.py
@@ -1,8 +1,10 @@
import json
-from typing import Optional, cast
+from typing import Any, Optional, cast
+from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity
from django.db import transaction
-from django.db.models import QuerySet
+from django.db.models import F, Q, QuerySet, Value
+from django.db.models.functions import Coalesce
import structlog
import posthoganalytics
@@ -10,7 +12,8 @@ from django_filters import BaseInFilter, CharFilter, FilterSet
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from loginas.utils import is_impersonated_session
-from rest_framework import exceptions, filters, serializers, viewsets
+from opentelemetry import trace
+from rest_framework import exceptions, serializers, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
@@ -34,6 +37,13 @@ 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.models import Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.hog_function_template import HogFunctionTemplate
@@ -53,6 +63,7 @@ MAX_HOG_CODE_SIZE_BYTES = 100 * 1024
MAX_TRANSFORMATIONS_PER_TEAM = 20
logger = structlog.get_logger(__name__)
+tracer = trace.get_tracer(__name__)
class HogFunctionStatusSerializer(serializers.Serializer):
@@ -466,8 +477,7 @@ class HogFunctionViewSet(
scope_object_read_actions = ["list", "retrieve", "logs", "metrics", "metrics_totals"]
scope_object_write_actions = ["create", "update", "partial_update", "invocations", "rearrange"]
queryset = HogFunction.objects.all()
- filter_backends = [DjangoFilterBackend, filters.SearchFilter]
- search_fields = ["name", "description"]
+ filter_backends = [DjangoFilterBackend]
filterset_class = HogFunctionFilterSet
log_source = "hog_function"
app_source = "hog_function"
@@ -480,6 +490,49 @@ class HogFunctionViewSet(
return HogFunctionMinimalSerializer
return HogFunctionSerializer
+ @tracer.start_as_current_span("HogFunctionViewSet.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("hog_function.search.result_count", results_len)
+ span.set_attribute("hog_function.search.empty", results_len == 0)
+ return response
+
+ @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")
+ )
+
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
queryset = queryset.exclude(type=HogFunctionType.WAREHOUSE_SOURCE_WEBHOOK.value)
@@ -488,7 +541,15 @@ class HogFunctionViewSet(
queryset = queryset.filter(deleted=False)
if self.action == "list":
- queryset = queryset.order_by("execution_order", "-updated_at")
+ 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)
+ else:
+ queryset = queryset.order_by("execution_order", "-updated_at")
final_filter_groups = []
@@ -512,8 +573,6 @@ class HogFunctionViewSet(
raise exceptions.ValidationError({"filters": "Invalid filters"})
if final_filter_groups:
- from django.db.models import Q
-
combined_q = Q()
for filter_group in final_filter_groups:
diff --git a/posthog/api/test/test_hog_function.py b/posthog/api/test/test_hog_function.py
index d7aea0825a60..dc278217d31f 100644
--- a/posthog/api/test/test_hog_function.py
+++ b/posthog/api/test/test_hog_function.py
@@ -7,6 +7,7 @@ from unittest.mock import ANY, MagicMock, patch
from django.db import connection
+from parameterized import parameterized
from rest_framework import status
from posthog.api.hog_function import MAX_HOG_CODE_SIZE_BYTES, MAX_TRANSFORMATIONS_PER_TEAM
@@ -1693,6 +1694,147 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"value": "http://localhost:2080/0e02d917-563f-4050-9725-aad881b69937",
}
+ @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",
+ ["Slack notification", "Unrelated"],
+ "slcak",
+ "Slack notification",
+ ["Unrelated"],
+ ),
+ (
+ "prefix-as-you-type",
+ ["Marketing webhook", "Engineering metrics"],
+ "Marke",
+ "Marketing webhook",
+ ["Engineering metrics"],
+ ),
+ (
+ "case-insensitive: lower",
+ ["Revenue webhook", "Engineering metrics"],
+ "revenue",
+ "Revenue webhook",
+ ["Engineering metrics"],
+ ),
+ (
+ "case-insensitive: upper",
+ ["Revenue webhook", "Engineering metrics"],
+ "REVENUE",
+ "Revenue webhook",
+ ["Engineering metrics"],
+ ),
+ ]
+ )
+ def test_list_filter_by_search_relevance(self, _name, function_names, search, expected_first, excluded):
+ 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}")
+ 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 = HogFunction.objects.create(team=self.team, name="revenue", type="destination", hog="return event")
+ description_match = HogFunction.objects.create(
+ team=self.team,
+ name="Q4 review",
+ description="Quarterly revenue webhook",
+ type="destination",
+ hog="return event",
+ )
+ HogFunction.objects.create(team=self.team, name="Unrelated", type="destination", hog="return event")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?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 = 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}")
+ 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):
+ HogFunction.objects.create(team=self.team, name="Webhook overview", 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
+
+ def test_list_filter_by_search_nul_bytes_do_not_500(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/", {"search": "\x00\x00\x00"})
+ assert response.status_code == status.HTTP_200_OK
+
+ def test_list_filter_by_search_handles_null_name_with_description_match(self):
+ named_match = HogFunction.objects.create(
+ team=self.team, name="Marketing webhook", type="destination", hog="return event"
+ )
+ unnamed_match = HogFunction.objects.create(
+ team=self.team,
+ name=None,
+ description="A marketing-focused destination",
+ type="destination",
+ hog="return event",
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?search=marketing")
+ assert response.status_code == status.HTTP_200_OK
+ result_ids = [r["id"] for r in response.json()["results"]]
+
+ assert str(named_match.id) in result_ids
+ assert str(unnamed_match.id) in result_ids
+ assert result_ids.index(str(named_match.id)) < result_ids.index(str(unnamed_match.id)), (
+ f"named match should rank above unnamed description match, got {result_ids}"
+ )
+
+ @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}/hog_functions/", {"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']}"
+
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 2b26dd7b9af4..99cac34037f6 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -600,10 +600,6 @@ export type HogFunctionsListParams = {
* The initial index from which to return the results.
*/
offset?: number
- /**
- * A search term.
- */
- search?: string
/**
* Multiple values may be separated by commas.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1434a1b6c75f..d8c01c53f4a1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39050,10 +39050,6 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
- /**
- * A search term.
- */
- search?: string;
/**
* Multiple values may be separated by commas.
*/
@@ -43507,10 +43503,6 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
- /**
- * A search term.
- */
- search?: string;
/**
* Multiple values may be separated by commas.
*/
diff --git a/services/mcp/src/generated/cdp_functions/api.ts b/services/mcp/src/generated/cdp_functions/api.ts
index f368429896b5..b542a5b64b28 100644
--- a/services/mcp/src/generated/cdp_functions/api.ts
+++ b/services/mcp/src/generated/cdp_functions/api.ts
@@ -23,7 +23,6 @@ export const HogFunctionsListQueryParams = /* @__PURE__ */ zod.object({
id: zod.string().optional(),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
- search: zod.string().optional().describe('A search term.'),
type: zod.array(zod.string()).optional().describe('Multiple values may be separated by commas.'),
updated_at: zod.iso.datetime({}).optional(),
})
diff --git a/services/mcp/src/tools/generated/cdp_functions.ts b/services/mcp/src/tools/generated/cdp_functions.ts
index b8cd8bc6f193..aaeed9b07e0f 100644
--- a/services/mcp/src/tools/generated/cdp_functions.ts
+++ b/services/mcp/src/tools/generated/cdp_functions.ts
@@ -163,7 +163,6 @@ const cdpFunctionsList = (): ToolBase<
id: params.id,
limit: params.limit,
offset: params.offset,
- search: params.search,
type: params.type,
updated_at: params.updated_at,
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/cdp-functions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/cdp-functions-list.json
index 6dc0800eb36a..0c3d741c6c38 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/cdp-functions-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/cdp-functions-list.json
@@ -23,10 +23,6 @@
"description": "The initial index from which to return the results.",
"type": "number"
},
- "search": {
- "description": "A search term.",
- "type": "string"
- },
"type": {
"description": "Multiple values may be separated by commas.",
"items": {