: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
feat(members): server-side fuzzy search via pg_trgm (#57542)
Paul D'Ambra0a2b5e1dfc6b
diff --git a/frontend/src/scenes/organization/membersLogic.tsx b/frontend/src/scenes/organization/membersLogic.tsxindex 72dea74b76c3..e20de931b29e 100644--- a/frontend/src/scenes/organization/membersLogic.tsx+++ b/frontend/src/scenes/organization/membersLogic.tsx@@ -1,11 +1,9 @@-import Fuse from 'fuse.js'import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'import { OrganizationMembershipLevel } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { createFuse } from 'lib/utils/fuseSearch'import { permanentlyMount } from 'lib/utils/kea-logic-builders'import { membershipLevelToName } from 'lib/utils/permissioning'import { organizationLogic } from 'scenes/organizationLogic'@@ -15,8 +13,6 @@ import { OrganizationMemberScopedApiKeysResponse, OrganizationMemberType } fromimport type { membersLogicType } from './membersLogicType'-export interface MembersFuse extends Fuse<OrganizationMemberType> {}-const PAGINATION_LIMIT = 200export const membersLogic = kea<membersLogicType>([@@ -28,6 +24,7 @@ export const membersLogic = kea<membersLogicType>([ensureAllMembersLoaded: true,loadAllMembers: true,loadMemberUpdates: true,+ loadSearchedMembers: true,loadMemberScopedApiKeys: (member: OrganizationMemberType) => ({ member }),setSearch: (search) => ({ search }),changeMemberAccessLevel: (member: OrganizationMemberType, level: OrganizationMembershipLevel) => ({@@ -114,6 +111,22 @@ export const membersLogic = kea<membersLogicType>([}},},+ // Server-side search results — separate from the canonical `members` store so+ // other consumers (rolesLogic, hedgehogModeLogic, etc.) keep seeing the full org+ // when the user has a search term active in the org-settings members page.+ searchedMembers: {+ __default: null as OrganizationMemberType[] | null,+ loadSearchedMembers: async () => {+ const search = values.search?.trim()+ if (!search) {+ return null+ }+ return await api.organizationMembers.listAll({+ limit: PAGINATION_LIMIT,+ search,+ })+ },+ },})),reducers({search: ['', { setSearch: (_, { search }) => search }],@@ -141,17 +154,19 @@ export const membersLogic = kea<membersLogicType>([return result},],- membersFuse: [- (s) => [s.meFirstMembers],- (members): MembersFuse =>- createFuse<OrganizationMemberType>(members ?? [], {- keys: ['user.first_name', 'user.last_name', 'user.email'],- }),- ],filteredMembers: [- (s) => [s.meFirstMembers, s.membersFuse, s.search],- (members, membersFuse, search): OrganizationMemberType[] =>- search ? membersFuse.search(search).map((result) => result.item) : (members ?? []),+ (s) => [s.meFirstMembers, s.searchedMembers, s.search],+ (members, searched, search): OrganizationMemberType[] => {+ // When a search term is set, return the (server-filtered) searchedMembers+ // — this avoids polluting the canonical `members` store with a filtered+ // subset, so other consumers (rolesLogic, hedgehogModeLogic) keep seeing+ // the full org. me-first is dropped during search because the user is+ // looking for someone else, not themselves.+ if (search?.trim()) {+ return searched ?? []+ }+ return members ?? []+ },],memberCount: [(s) => [s.user, s.sortedMembers],@@ -180,6 +195,11 @@ export const membersLogic = kea<membersLogicType>([actions.loadMemberUpdates()}},++ setSearch: async (_, breakpoint) => {+ await breakpoint(250)+ actions.loadSearchedMembers()+ },})),permanentlyMount(),diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsxindex 043e66d9eef6..0fcf790fcb33 100644--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx@@ -18,31 +18,45 @@ describe('SavedInsightsFilters Created by dropdown', () => {let setFilters: jest.MockbeforeEach(() => {+ const allMembers = [+ {+ id: '1',+ user: MOCK_DEFAULT_BASIC_USER,+ level: 8,+ joined_at: '2020-09-24T15:05:26.758796Z',+ updated_at: '2020-09-24T15:05:26.758837Z',+ is_2fa_enabled: false,+ has_social_auth: false,+ last_login: '2020-09-24T15:05:26.758796Z',+ },+ {+ id: '2',+ user: MOCK_SECOND_BASIC_USER,+ level: 1,+ joined_at: '2021-03-11T19:11:11Z',+ updated_at: '2021-03-11T19:11:11Z',+ is_2fa_enabled: false,+ has_social_auth: false,+ last_login: '2021-03-11T19:11:11Z',+ },+ ]useMocks({get: {- '/api/organizations/:organization_id/members/': {- results: [- {- id: '1',- user: MOCK_DEFAULT_BASIC_USER,- level: 8,- joined_at: '2020-09-24T15:05:26.758796Z',- updated_at: '2020-09-24T15:05:26.758837Z',- is_2fa_enabled: false,- has_social_auth: false,- last_login: '2020-09-24T15:05:26.758796Z',- },- {- id: '2',- user: MOCK_SECOND_BASIC_USER,- level: 1,- joined_at: '2021-03-11T19:11:11Z',- updated_at: '2021-03-11T19:11:11Z',- is_2fa_enabled: false,- has_social_auth: false,- last_login: '2021-03-11T19:11:11Z',- },- ],+ '/api/organizations/:organization_id/members/': (req) => {+ // membersLogic now does server-side search; mock honors `?search=`+ // by filtering on first_name, last_name, and email substring.+ const search = new URL(req.url).searchParams.get('search')?.toLowerCase()+ const results = search+ ? allMembers.filter((m) => {+ const u = m.user+ return (+ u.first_name?.toLowerCase().includes(search) ||+ u.last_name?.toLowerCase().includes(search) ||+ u.email?.toLowerCase().includes(search)+ )+ })+ : allMembers+ return [200, { results }]},},})diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 0dc387a8e1c4..41610c7d0ef5 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -575,6 +575,7 @@ export interface ListOrganizationMembersParams {offset?: numberlimit?: numberupdated_after?: string+ search?: string}export interface APIErrorType {diff --git a/posthog/api/organization_member.py b/posthog/api/organization_member.pyindex 15f229a75e2d..be24ea55ea77 100644--- a/posthog/api/organization_member.py+++ b/posthog/api/organization_member.py@@ -1,11 +1,14 @@-from typing import cast+from typing import Any, cast-from django.db.models import F, Model, Prefetch, QuerySet+from django.contrib.postgres.search import TrigramWordSimilarity+from django.db.models import F, Model, Prefetch, Q, QuerySet, Value+from django.db.models.functions import Coalescefrom django.shortcuts import get_object_or_404from django_otp.plugins.otp_totp.models import TOTPDevicefrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view+from opentelemetry import tracefrom rest_framework import exceptions, mixins, serializers, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import SAFE_METHODS, BasePermission@@ -18,12 +21,15 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import 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_termfrom posthog.models import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import TimeSensitiveActionPermission, extract_organizationfrom posthog.utils import posthoganalytics+tracer = trace.get_tracer(__name__)+# Only index-backed orderings are allowed. `-joined_at` is served by the# `(organization, -joined_at)` composite index; other fields would force a# full scan + sort and can time out for large organizations.@@ -110,6 +116,11 @@ class OrganizationMemberSerializer(serializers.ModelSerializer):enum=sorted(ALLOWED_ORDERINGS),description=f"Sort order. Defaults to `{DEFAULT_ORDERING}`.",),+ 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.",+ ),],),)@@ -151,6 +162,46 @@ class OrganizationMemberViewSet(filter_kwargs = {self.lookup_field: lookup_value}return get_object_or_404(queryset, **filter_kwargs)+ @tracer.start_as_current_span("OrganizationMemberViewSet.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("organization_member.search.result_count", results_len)+ span.set_attribute("organization_member.search.empty", results_len == 0)+ return response++ @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")+ )+def safely_get_queryset(self, queryset) -> QuerySet:if self.action == "list":params = self.request.GET.dict()@@ -161,11 +212,22 @@ class OrganizationMemberViewSet(if "updated_after" in params:queryset = queryset.filter(updated_at__gt=params["updated_after"])- order = self.request.GET.get("order")- if order in ALLOWED_ORDERINGS:- queryset = queryset.order_by(order)+ search = self.request.GET.get("search", "")+ if len(search) > MAX_SEARCH_LENGTH:+ raise serializers.ValidationError(+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}+ )+ # Normalize before deciding so whitespace-only queries fall through to default+ # ordering rather than reaching `_apply_search` and returning the queryset+ # without any order applied.+ if normalize_search_term(search):+ queryset = self._apply_search(queryset, search)else:- queryset = queryset.order_by(DEFAULT_ORDERING)+ order = self.request.GET.get("order")+ if order in ALLOWED_ORDERINGS:+ queryset = queryset.order_by(order)+ else:+ queryset = queryset.order_by(DEFAULT_ORDERING)return querysetdiff --git a/posthog/api/test/test_organization_members.py b/posthog/api/test/test_organization_members.pyindex bc512ab91feb..8e6e75a361fa 100644--- a/posthog/api/test/test_organization_members.py+++ b/posthog/api/test/test_organization_members.py@@ -457,6 +457,74 @@ class TestOrganizationMembersAPI(APIBaseTest, QueryMatchingTest):self.assertEqual(len(data), 2)self.assertEqual(data[0]["user"]["email"], expected_first_email)+ @parameterized.expand(+ [+ ("first name match", "Marketing", "[email protected]"),+ ("typo / transposition still matches", "marekting", "[email protected]"),+ ("prefix-as-you-type on first name", "Marke", "[email protected]"),+ ("case-insensitive", "MARKETING", "[email protected]"),+ ("email match", "engineering", "[email protected]"),+ ("last name match", "Smith", "[email protected]"),+ ]+ )+ def test_list_organization_members_filter_by_search(self, _name, search, expected_email):+ 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="Engineering", last_name="Manager"+ )+ User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Bob", last_name="Smith")++ response = self.client.get(f"/api/organizations/@current/members/?search={search}")+ assert response.status_code == status.HTTP_200_OK+ emails = [r["user"]["email"] for r in response.json()["results"]]++ assert emails, f"expected at least one match for {search!r}, got nothing"+ assert expected_email in emails, f"expected {expected_email!r} in results, got {emails}"++ @parameterized.expand(+ [+ ("whitespace-only", " "),+ ("empty", ""),+ ]+ )+ def test_list_organization_members_blank_search_returns_all(self, _name, search):+ User.objects.create_and_join(self.organization, "[email protected]", None)++ response = self.client.get(f"/api/organizations/@current/members/?search={search}")+ assert response.status_code == status.HTTP_200_OK+ emails = {r["user"]["email"] for r in response.json()["results"]}+ # Self-user + the one we just added should both be present+ assert "[email protected]" in emails++ @parameterized.expand(+ [+ ("plain symbols", "&|!"),+ ("sql-injection-shaped", "'; DROP TABLE--"),+ ("nul bytes", "\x00\x00\x00"),+ ]+ )+ def test_list_organization_members_pathological_search_does_not_500(self, _name, search):+ response = self.client.get("/api/organizations/@current/members/", {"search": search})+ assert response.status_code == status.HTTP_200_OK++ @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_organization_members_search_enforces_length_cap(self, _name, length, expected_status):+ response = self.client.get("/api/organizations/@current/members/", {"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']}"+@parameterized.expand([# (name, has_totp, passkeys_enabled_for_2fa, passkey_verified, expected)diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 327b7a6d1833..77f2415b7ceb 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -761,6 +761,10 @@ export type MembersListParams = {* Sort order. Defaults to `-joined_at`.*/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.+ */+ search?: string}export type RolesListParams = {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 39812b156d89..f776d3006f30 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -41449,6 +41449,10 @@ export namespace Schemas {* Sort order. Defaults to `-joined_at`.*/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.+ */+ search?: string;};export type OauthApplicationsListParams = {diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex 228c7675cdb9..f80a034c7c68 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -78,6 +78,12 @@ export const MembersListQueryParams = /* @__PURE__ */ zod.object({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.'),order: zod.string().optional().describe('Sort order. Defaults to `-joined_at`.'),+ search: zod+ .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.'+ ),})export const RolesListParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.tsindex 093b919b884c..1488e7ee4754 100644--- a/services/mcp/src/tools/generated/platform_features.ts+++ b/services/mcp/src/tools/generated/platform_features.ts@@ -303,6 +303,7 @@ const orgMembersList = (): ToolBase<typeof OrgMembersListSchema, Schemas.Paginatlimit: params.limit,offset: params.offset,order: params.order,+ search: params.search,},})return resultdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/org-members-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/org-members-list.jsonindex 2cfa1e6c6909..1f2fccf914b2 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/org-members-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/org-members-list.json@@ -12,6 +12,10 @@"order": {"description": "Sort order. Defaults to `-joined_at`.","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.",+ "type": "string"}},"type": "object"