: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 organization members (#62380)
Paul D'Ambra3d4b9ae7984d
diff --git a/posthog/api/organization_member.py b/posthog/api/organization_member.pyindex 947a972c556c..847803d2c593 100644--- a/posthog/api/organization_member.py+++ b/posthog/api/organization_member.py@@ -1,8 +1,6 @@from typing import Any, cast-from django.contrib.postgres.search import TrigramWordSimilarity-from django.db.models import F, Model, Prefetch, Q, QuerySet, Value-from django.db.models.functions import Coalesce+from django.db.models import F, Model, Prefetch, QuerySetfrom django.shortcuts import get_object_or_404from django_otp.plugins.otp_totp.models import TOTPDevice@@ -26,10 +24,15 @@ from rest_framework.serializers import raise_errors_on_nested_writesfrom social_django.models import UserSocialAuthfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.shared import UserBasicSerializer+from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.constants import INTERNAL_BOT_EMAIL_SUFFIXfrom posthog.event_usage import groups-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,+ TrigramSearchField,+ apply_trigram_search,+ normalize_search_term,+)from posthog.models import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.webauthn_credential import WebauthnCredential@@ -79,7 +82,7 @@ class OrganizationMemberObjectPermissions(BasePermission):return True-class OrganizationMemberSerializer(serializers.ModelSerializer):+class OrganizationMemberSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):user = UserBasicSerializer(read_only=True)is_2fa_enabled = serializers.SerializerMethodField()has_social_auth = serializers.SerializerMethodField()@@ -96,6 +99,7 @@ class OrganizationMemberSerializer(serializers.ModelSerializer):"is_2fa_enabled","has_social_auth","last_login",+ "search_match_type",]read_only_fields = ["id", "joined_at", "updated_at"]@@ -141,7 +145,7 @@ class OrganizationMemberSerializer(serializers.ModelSerializer):OpenApiParameter(name="search",type=OpenApiTypes.STR,- description="Fuzzy match against member `first_name`, `last_name`, and `email` using Postgres trigram word similarity. Supports typos and prefix-as-you-type. Capped at 200 characters.",+ description="Match against member `first_name`, `last_name`, and `email`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, prefix-as-you-type) together, ordered exact-first; each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.",),],),@@ -194,30 +198,16 @@ class OrganizationMemberViewSet(@staticmethod@tracer.start_as_current_span("OrganizationMemberViewSet._apply_search")def _apply_search(queryset: QuerySet, search: str) -> QuerySet:- search = normalize_search_term(search)- span = trace.get_current_span()- span.set_attribute("organization_member.search.length", len(search))- if not search:- return queryset-- zero = Value(0.0)- first_name_score = Coalesce(TrigramWordSimilarity(search, "user__first_name"), zero)- last_name_score = Coalesce(TrigramWordSimilarity(search, "user__last_name"), zero)- email_score = Coalesce(TrigramWordSimilarity(search, "user__email"), zero)-- return (- queryset.annotate(- _first_name_score=first_name_score,- _last_name_score=last_name_score,- _email_score=email_score,- )- .filter(- Q(_first_name_score__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_last_name_score__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_email_score__gt=MIN_NAME_TRIGRAM_SIMILARITY)- )- .annotate(_search_score=F("_first_name_score") + F("_last_name_score") + F("_email_score"))- .order_by("-_search_score", "user__first_name")+ return apply_trigram_search(+ queryset,+ search,+ span_prefix="organization_member.search",+ fields=(+ TrigramSearchField("user__first_name"),+ TrigramSearchField("user__last_name"),+ TrigramSearchField("user__email"),+ ),+ tiebreakers=("user__first_name",),)def safely_get_queryset(self, queryset) -> QuerySet:diff --git a/posthog/api/test/test_organization_members.py b/posthog/api/test/test_organization_members.pyindex 8e6e75a361fa..8022e4756db7 100644--- a/posthog/api/test/test_organization_members.py+++ b/posthog/api/test/test_organization_members.py@@ -525,6 +525,62 @@ class TestOrganizationMembersAPI(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 with plus tag", "[email protected]"),+ ("dotted email local part", "[email protected]"),+ ]+ )+ def test_list_organization_members_search_matches_literal_substring_below_trigram_threshold(self, _name, email):+ User.objects.create_and_join(self.organization, email, None, first_name="Real", last_name="Person")+ User.objects.create_and_join(+ self.organization, "[email protected]", None, first_name="Bob", last_name="Jones"+ )++ response = self.client.get("/api/organizations/@current/members/", {"search": email})+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_email = {r["user"]["email"]: r["search_match_type"] for r in results}+ assert match_type_by_email.get(email) == "exact", (+ "a literal email substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert "[email protected]" not in match_type_by_email++ def test_list_organization_members_search_returns_exact_first_with_match_type(self):+ User.objects.create_and_join(+ self.organization, "[email protected]", None, first_name="Marketing", last_name="Director"+ )+ User.objects.create_and_join(+ self.organization, "[email protected]", None, first_name="Marekting", last_name="Lead"+ )+ User.objects.create_and_join(+ self.organization, "[email protected]", None, first_name="Bob", last_name="Jones"+ )++ response = self.client.get("/api/organizations/@current/members/?search=marketing")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ emails = [r["user"]["email"] for r in results]+ match_type_by_email = {r["user"]["email"]: r["search_match_type"] for r in results}++ assert match_type_by_email.get("[email protected]") == "exact"+ assert match_type_by_email.get("[email protected]") == "similar"+ assert "[email protected]" not in emails+ assert emails.index("[email protected]") < emails.index("[email protected]"), (+ f"exact match must rank ahead of the fuzzy-only match, got {emails}"+ )++ def test_list_organization_members_search_match_type_absent_without_search(self):+ User.objects.create_and_join(self.organization, "[email protected]", None)++ response = self.client.get("/api/organizations/@current/members/")+ 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)+@parameterized.expand([# (name, has_totp, passkeys_enabled_for_2fa, passkey_verified, expected)diff --git a/posthog/api/test/test_search_match_type_mixin.py b/posthog/api/test/test_search_match_type_mixin.pyindex 62feaf66faff..4b19d1cdb75a 100644--- a/posthog/api/test/test_search_match_type_mixin.py+++ b/posthog/api/test/test_search_match_type_mixin.py@@ -1,6 +1,7 @@from parameterized import parameterizedfrom rest_framework import serializers+from posthog.api.organization_member import OrganizationMemberSerializerfrom posthog.api.shared import SearchMatchTypeSerializerMixinfrom products.product_analytics.backend.api.insight import InsightBasicSerializer, InsightSerializer@@ -10,6 +11,7 @@ from products.product_analytics.backend.api.insight import InsightBasicSerializeSEARCH_LIST_SERIALIZERS = [("insight_basic", InsightBasicSerializer),("insight", InsightSerializer),+ ("organization_member", OrganizationMemberSerializer),]diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex e9442168e2a3..ba545555e165 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -295,6 +295,13 @@ export const OrganizationMembershipLevelEnumApi = {Number15: 15,} as const+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+export interface OrganizationMemberApi {readonly id: stringreadonly user: UserBasicApi@@ -304,6 +311,8 @@ export interface OrganizationMemberApi {readonly is_2fa_enabled: booleanreadonly has_social_auth: booleanreadonly last_login: string+ /** 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 PaginatedOrganizationMemberListApi {@@ -324,6 +333,8 @@ export interface PatchedOrganizationMemberApi {readonly is_2fa_enabled?: booleanreadonly has_social_auth?: booleanreadonly last_login?: string+ /** 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 OrganizationPersonalAPIKeyOwnerApi {@@ -856,7 +867,7 @@ export type MembersListParams = {*/order?: string/**- * Fuzzy match against member `first_name`, `last_name`, and `email` using Postgres trigram word similarity. Supports typos and prefix-as-you-type. Capped at 200 characters.+ * Match against member `first_name`, `last_name`, and `email`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, prefix-as-you-type) together, ordered exact-first; each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.*/search?: string}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c2b5ffa3a7d9..bac527b32e2b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24254,6 +24254,8 @@ export namespace Schemas {readonly is_2fa_enabled: boolean;readonly has_social_auth: boolean;readonly last_login: string;+ /** 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;}/**@@ -31453,6 +31455,8 @@ export namespace Schemas {readonly is_2fa_enabled?: boolean;readonly has_social_auth?: boolean;readonly last_login?: string;+ /** 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 PatchedParserRecipe {@@ -47324,7 +47328,7 @@ export namespace Schemas {*/order?: string;/**- * Fuzzy match against member `first_name`, `last_name`, and `email` using Postgres trigram word similarity. Supports typos and prefix-as-you-type. Capped at 200 characters.+ * Match against member `first_name`, `last_name`, and `email`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, prefix-as-you-type) together, ordered exact-first; each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.*/search?: string;};diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex 32029fa1dc95..be2882452a0f 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -33,7 +33,7 @@ export const MembersListQueryParams = /* @__PURE__ */ zod.object({.string().optional().describe(- 'Fuzzy match against member `first_name`, `last_name`, and `email` using Postgres trigram word similarity. Supports typos and prefix-as-you-type. Capped at 200 characters.'+ "Match against member `first_name`, `last_name`, and `email`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, prefix-as-you-type) together, ordered exact-first; each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters."),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.jsonindex 1f2fccf914b2..4dc5745fe403 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json@@ -14,7 +14,7 @@"type": "string"},"search": {- "description": "Fuzzy match against member `first_name`, `last_name`, and `email` using Postgres trigram word similarity. Supports typos and prefix-as-you-type. Capped at 200 characters.",+ "description": "Match against member `first_name`, `last_name`, and `email`. Returns case-insensitive substring matches and fuzzy trigram matches (typos, prefix-as-you-type) together, ordered exact-first; each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.","type": "string"}},