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(persons): find email matches past an id hit and tag results (#103847)

Matheus Batistacdec4950c476
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index aa89b888bee4..7d82c67a6b23 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10672,6 +10672,10 @@ snapshots:
hash: v1.k794b7964.eaa71c50ae2ed7a81333458b1174a80885e621c9f293de0367e2a4d65294b398.8uMKPXYZ943_ncEtmg592_sXacuRN3Fux9hJ4G1qcsc
scenes-app-people-persons--persons-empty--light:
hash: v1.k794b7964.10c9878a4b0790830b0e0074a903686b0576a2fa385833673d7ee4abe113c57d.f7bzPSLBvs3XksPwPMuXolugbN1cNkOf-fxikxTqlGA
+ scenes-app-people-personsearchmatchtags--every-field--dark:
+ hash: v1.k794b7964.06e920f3a71ee2545cb54428cb780afcff032596a6a547fe0fc25401eb90eeca.w-Tu3nUGALKjrAGCCZEfGfiSfYU_GQ8_QgYASdzxnDM
+ scenes-app-people-personsearchmatchtags--every-field--light:
+ hash: v1.k794b7964.6f61abcf8ca31c767cbcd09be5e43c0833400575f5f59b42287361a7946a30ab.Eu4q1mhlQZZ6hyZxQE7cSl_nxqsGnYPICMMnw9s7F3k
scenes-app-persons-modal--empty--dark:
hash: v1.k794b7964.00a95f7411a59b96d96cd23b8f4da1eca9053e7c391a2c4db52f27526fc842d2.OhWCw6o84czmOJ-2Q_tWWo_OmFLiEf7hCAfs9UWltco
scenes-app-persons-modal--empty--light:
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
index f29b4a7317ed..1830e110fb9f 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
@@ -122,6 +122,8 @@ import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortReal
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'
import { groupDisplayId } from 'products/persons/frontend/components/GroupActorDisplay'
+import { PersonSearchMatchTags } from 'products/persons/frontend/components/PersonSearchMatchTags'
+import type { PersonListRecordApi } from 'products/persons/frontend/generated/api.schemas'
import { LazyHogFlowTaxonomicFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/LazyHogFlowTaxonomicFilters'
import type { Noun } from '../../../models/groupsModel'
@@ -1953,9 +1955,12 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
name: 'Persons',
searchPlaceholder: 'persons',
type: TaxonomicFilterGroupType.Persons,
- endpoint: `api/projects/${teamId}/persons/`,
+ endpoint: `api/projects/${teamId}/persons/?include_matched_fields=true`,
getName: (person: PersonType) => person.name || 'Anon user?',
getValue: (person: PersonType) => person.distinct_ids?.[0],
+ getTag: (person: PersonListRecordApi) => (
+ <PersonSearchMatchTags matchedFields={person.matched_fields} />
+ ),
getPopoverHeader: () => `Person`,
},
{
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
index f5d1699f6b84..dcf3518985c8 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
@@ -440,7 +440,13 @@ describe('taxonomicFilterPinnedPropertiesLogic', () => {
it.each([
{
description: 'strips denylisted fields and keeps everything else',
- input: { name: 'Alice', distinct_ids: ['d1'], email: '[email protected]', properties: { big: 'blob' } },
+ input: {
+ name: 'Alice',
+ distinct_ids: ['d1'],
+ email: '[email protected]',
+ properties: { big: 'blob' },
+ matched_fields: ['email'],
+ },
fallback: 'fallback',
expected: { name: 'Alice', distinct_ids: ['d1'] },
},
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
index 5ab601a6a3b6..ee8b14c968cf 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
@@ -41,9 +41,16 @@ export function stripPinnedContext<T extends Record<string, any>>(item: T): Omit
* the obvious PII / heavy-blob fields that source-group items may carry — Person
* `email` and `properties`, Group `group_properties`, etc. Everything else flows
* through so source-group `getValue` and `getName` keep working without us having
- * to enumerate every identifier field they read.
+ * to enumerate every identifier field they read. Person `matched_fields` only holds
+ * for the search that listed the person.
*/
-const PINNED_ITEM_DENYLIST = new Set<string>(['email', 'properties', 'group_properties', '_pinnedContext'])
+const PINNED_ITEM_DENYLIST = new Set<string>([
+ 'email',
+ 'properties',
+ 'group_properties',
+ 'matched_fields',
+ '_pinnedContext',
+])
export function pickMinimalPinnedItem(item: unknown, fallbackValue: TaxonomicFilterValue): Record<string, any> {
if (typeof item !== 'object' || item == null || Array.isArray(item)) {
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
index d719f69ade51..2c013a42cbcc 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
@@ -76,6 +76,8 @@ import {
import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'
+import { PersonSearchMatchTags } from 'products/persons/frontend/components/PersonSearchMatchTags'
+import type { PersonListRecordApi } from 'products/persons/frontend/generated/api.schemas'
import { LazyHogFlowTaxonomicFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/LazyHogFlowTaxonomicFilters'
import { InlineHogQLEditor } from '../InlineHogQLEditor'
@@ -923,9 +925,10 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
name: 'Persons',
searchPlaceholder: 'persons',
type: TaxonomicFilterGroupType.Persons,
- endpoint: `api/projects/${teamId}/persons/`,
+ endpoint: `api/projects/${teamId}/persons/?include_matched_fields=true`,
getName: (person: PersonType) => person.name || 'Anon user?',
getValue: (person: PersonType) => person.distinct_ids?.[0],
+ getTag: (person: PersonListRecordApi) => <PersonSearchMatchTags matchedFields={person.matched_fields} />,
getPopoverHeader: () => `Person`,
},
{
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 58fb5646dc3d..ae5c2ed7a9e5 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -2,10 +2,12 @@ import re
import uuid
import builtins
import dataclasses
+from collections.abc import Collection, Mapping
from datetime import UTC, datetime
from typing import Any, Optional, Union, cast # noqa: UP035
from django.conf import settings
+from django.db.models import TextChoices
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -44,9 +46,10 @@ from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.constants import LIMIT, OFFSET
from posthog.errors import ExposedCHQueryError, QueryErrorCategory, classify_query_error
from posthog.event_usage import get_request_analytics_properties
+from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.hogql_queries.properties_timeline import PropertiesTimeline
-from posthog.hogql_queries.serialized_actors import get_serialized_people
+from posthog.hogql_queries.serialized_actors import SerializedPerson, get_serialized_people
from posthog.metrics import LABEL_TEAM_ID
from posthog.models import Filter, Person, Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
@@ -81,6 +84,7 @@ from posthog.utils import (
is_anonymous_id,
refresh_requested_by_client,
relative_date_parse_with_delta_mapping,
+ str_to_bool,
)
from products.ai_training.backend.facade.api import queue_person_training_deletion
@@ -141,7 +145,7 @@ API_PERSON_LIST_BYTES_READ_FROM_POSTGRES_COUNTER = Counter(
API_PERSON_LIST_SEARCH_COUNTER = Counter(
"api_person_list_search_total",
- "Person list searches, by whether an exact identifier answered them or ClickHouse had to.",
+ "Person list searches, by what answered them: an exact identifier, ClickHouse, or both.",
labelnames=["answered_by"],
)
@@ -387,6 +391,14 @@ class DeletionStatusPagination(LimitOffsetPagination):
default_limit = 100
+# Keep in sync with `PersonStrategy.filter_conditions` and `TAG_BY_FIELD` in `PersonSearchMatchTags.tsx`.
+class PersonSearchMatchField(TextChoices):
+ DISTINCT_ID = "distinct_id", "Distinct ID"
+ EMAIL = "email", "Email"
+ NAME = "name", "Name"
+ ID = "id", "Person ID"
+
+
@extend_schema_serializer(component_name="PersonRecord")
class PersonSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.SerializerMethodField(
@@ -439,6 +451,20 @@ class PersonSerializer(serializers.HyperlinkedModelSerializer):
}
+# Schema only, since the list builds its rows as dicts. `matched_fields` is not read-only because
+# the schema marks read-only fields as required.
+@extend_schema_serializer(component_name="PersonListRecord")
+class PersonListRecordSerializer(PersonSerializer):
+ matched_fields = serializers.ListField(
+ child=serializers.ChoiceField(choices=PersonSearchMatchField.choices),
+ required=False,
+ help_text="Only on a search result with `include_matched_fields`: the searched fields the term was found in.",
+ )
+
+ class Meta(PersonSerializer.Meta):
+ fields = [*PersonSerializer.Meta.fields, "matched_fields"]
+
+
# person distinct ids can grow to be a very large list
# in the UI we don't need all of them, so we can limit the number of distinct ids we return
@extend_schema_serializer(component_name="MinimalPerson")
@@ -533,6 +559,9 @@ _GET_OBJECT_DISTINCT_ID_LIMITS: dict[str, int] = {
# hide the other matches.
_COMPLETE_EMAIL_TERM = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+# Keep in sync with the email arms of `PersonStrategy.filter_conditions`.
+_EMAIL_PROPERTY_KEYS = ("email", "Email")
+
def _is_canonical_uuid(value: str) -> bool:
# Only the dashed form counts, so the fast path answers the same terms the fuzzy search
@@ -543,8 +572,8 @@ def _is_canonical_uuid(value: str) -> bool:
return False
-def _exact_identifier_person_uuids(team_id: int, search: str) -> list[str]:
- """Resolve a search term as a person UUID or distinct ID; empty when it matches neither.
+def _exact_identifier_hits(team_id: int, search: str) -> dict[str, list[str]]:
+ """Resolve a search term as a person UUID or distinct ID, with the fields it matched; empty when it matches neither.
Fuzzy person search reads every person row and distinct ID of the team, which is what times
out on large projects. Identifiers resolve over personhog in milliseconds and hold no
@@ -552,19 +581,35 @@ def _exact_identifier_person_uuids(team_id: int, search: str) -> list[str]:
"""
term_is_uuid = _is_canonical_uuid(search)
if not term_is_uuid and not _COMPLETE_EMAIL_TERM.match(search):
- return []
+ return {}
- matches: list[str] = []
+ hits: dict[str, list[str]] = {}
with personhog_caller_tag("persons/list-exact-identifier"):
# A UUID term can be a person's own ID or an anonymous distinct ID, so try both.
if term_is_uuid:
by_uuid = get_person_by_uuid(team_id, search, distinct_id_limit=0)
if by_uuid is not None:
- matches.append(str(by_uuid.uuid))
+ hits[str(by_uuid.uuid)] = [PersonSearchMatchField.ID.value]
by_distinct_id = get_person_by_distinct_id(team_id, search, distinct_id_limit=0)
- if by_distinct_id is not None and str(by_distinct_id.uuid) not in matches:
- matches.append(str(by_distinct_id.uuid))
- return matches
+ if by_distinct_id is not None:
+ hits.setdefault(str(by_distinct_id.uuid), []).append(PersonSearchMatchField.DISTINCT_ID.value)
+ return hits
+
+
+def _search_match_fields(search: str, person: SerializedPerson, known_fields: Collection[str] = ()) -> list[str]:
+ # `known_fields` covers a matched distinct ID past the hydration cap.
+ needle = search.lower()
+ properties = person["properties"]
+ checks = (
+ (PersonSearchMatchField.DISTINCT_ID, any(needle in did.lower() for did in person["distinct_ids"])),
+ (
+ PersonSearchMatchField.EMAIL,
+ any(needle in str(properties.get(key) or "").lower() for key in _EMAIL_PROPERTY_KEYS),
+ ),
+ (PersonSearchMatchField.NAME, needle in str(properties.get("name") or "").lower()),
+ (PersonSearchMatchField.ID, needle in str(person["id"]).lower()),
+ )
+ return [field.value for field, holds_term in checks if holds_term or field.value in known_fields]
@extend_schema(extensions={"x-product": ProductKey.PERSONS})
@@ -658,6 +703,15 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"or person ID, only that person is returned."
),
),
+ OpenApiParameter(
+ "include_matched_fields",
+ OpenApiTypes.BOOL,
+ description=(
+ "Tag each search result with `matched_fields`, the searched fields the term was found in. "
+ "A complete email address that exactly matches a distinct ID then returns that person first, "
+ "followed by every person whose email or name property contains the address."
+ ),
+ ),
OpenApiParameter(
"client_query_id",
OpenApiTypes.STR,
@@ -669,6 +723,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
PersonPropertiesSerializer(required=False),
],
+ responses=PersonListRecordSerializer,
)
def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
tag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY)
@@ -695,10 +750,13 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
person_properties.append({"type": "person", "key": "email", "value": filter.email, "operator": "exact"})
include_total = "include_total" in request.GET
+ include_matched_fields = str_to_bool(request.GET.get("include_matched_fields"))
search = (filter.search or "").strip()
+ tag_term = search if include_matched_fields else None
# Nothing else narrows the result set, so an identifier that resolves over personhog is
- # already the whole first page, and a ClickHouse scan would add nothing.
- can_answer_from_identifier = not person_properties and filter.offset == 0
+ # already the whole first page, and a ClickHouse scan would add nothing. A tagged search
+ # needs the hit on every page, because it leads the tagged sequence.
+ can_answer_from_identifier = not person_properties and (filter.offset == 0 or include_matched_fields)
# This endpoint bypasses `QueryRunner.run()`, so nothing else measures how long it takes.
# The search path is the slow one, so the shape of the request is recorded alongside the
@@ -730,6 +788,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
properties=slo_properties,
) as slo:
+ exact_hits: dict[str, list[str]] = {}
+ email_property_search = False
+ properties: list[dict] | dict[str, Any] = person_properties
+ order_by = ["created_at DESC", "id DESC"]
+ answered_by = "clickhouse"
if filter.distinct_id:
# Exact match on any of the person's distinct IDs; no matching person => no results.
matched = get_person_by_distinct_id(team.pk, filter.distinct_id, distinct_id_limit=0)
@@ -740,36 +803,57 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
slo.tag(answered_by="exact_identifier", result_count=0)
return self._person_list_response(request, [], filter, total_count=0 if include_total else None)
if can_answer_from_identifier and not search:
- slo.tag(answered_by="exact_identifier", result_count=1)
+ page = [str(matched.uuid)][filter.offset : filter.offset + filter.limit]
+ slo.tag(answered_by="exact_identifier", result_count=len(page))
return self._person_list_response(
request,
- [str(matched.uuid)],
+ page,
filter,
total_count=1 if include_total else None,
has_next=False,
)
person_properties.append({"type": "hogql", "key": f"id = toUUID('{matched.uuid}')"})
elif search:
- exact_uuids = _exact_identifier_person_uuids(team.pk, search) if can_answer_from_identifier else []
- API_PERSON_LIST_SEARCH_COUNTER.labels(
- answered_by="exact_identifier" if exact_uuids else "clickhouse"
- ).inc()
- if exact_uuids:
- page = exact_uuids[: filter.limit]
+ exact_hits = _exact_identifier_hits(team.pk, search) if can_answer_from_identifier else {}
+ # An email can also sit in other persons' properties, which only ClickHouse searches.
+ email_property_search = (
+ include_matched_fields and bool(exact_hits) and _COMPLETE_EMAIL_TERM.match(search) is not None
+ )
+ if exact_hits and not email_property_search:
+ API_PERSON_LIST_SEARCH_COUNTER.labels(answered_by="exact_identifier").inc()
+ page = list(exact_hits)[filter.offset : filter.offset + filter.limit]
slo.tag(answered_by="exact_identifier", result_count=len(page))
return self._person_list_response(
request,
page,
filter,
- total_count=len(exact_uuids) if include_total else None,
- has_next=len(exact_uuids) > filter.limit,
+ total_count=len(exact_hits) if include_total else None,
+ has_next=len(exact_hits) > filter.offset + filter.limit,
+ tag_term=tag_term,
+ exact_hits=exact_hits,
)
+ if email_property_search:
+ # The fuzzy search's property arms, without its slow distinct ID scan.
+ identifier_hit = " or ".join(f"id = toUUID('{person_uuid}')" for person_uuid in exact_hits)
+ properties = {
+ "type": "OR",
+ "values": [
+ {"type": "hogql", "key": identifier_hit},
+ *(
+ {"type": "person", "key": key, "value": search, "operator": "icontains"}
+ for key in (*_EMAIL_PROPERTY_KEYS, "name")
+ ),
+ ],
+ }
+ order_by = [f"({identifier_hit}) DESC", *order_by]
+ answered_by = "exact_identifier_and_email"
+ API_PERSON_LIST_SEARCH_COUNTER.labels(answered_by=answered_by).inc()
actors_query = ActorsQuery(
select=["id"],
- properties=person_properties,
- search=filter.search or None,
- orderBy=["created_at DESC", "id DESC"],
+ properties=properties,
+ search=None if email_property_search else search or None,
+ orderBy=order_by,
limit=filter.limit,
offset=filter.offset,
)
@@ -777,15 +861,18 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# insight-caching wrapper. With an id-only select there's no actor-column hydration, so
# we still hydrate the person objects ourselves via get_serialized_people.
actors_runner = ActorsQueryRunner(team=team, query=actors_query)
+ # ClickHouse can lag behind personhog or fail, so the hit leads the first page regardless.
+ hit_leads_page = email_property_search and filter.offset == 0
+ actor_ids: list[Any] = []
+ total_count: Optional[int] = None
# A cancel kills every ClickHouse query the request has in flight, so both queries below
- # sit inside one handler. Anything that is not a cancellation is re-raised untouched.
+ # sit inside one handler.
try:
actor_ids = [row[0] for row in actors_runner.calculate().results]
# If the undocumented include_total param is set to true, we'll return the total count of people
# This is extra time and DB load, so we only do this when necessary, which is in PostHog 3000 navigation
# TODO: Use a more scalable solution before PostHog 3000 navigation is released, and remove this param
- total_count: Optional[int] = None
if include_total:
count_inner = actors_runner.to_query()
count_inner.limit = None
@@ -796,20 +883,34 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
total_count = execute_hogql_query(count_query, team=team).results[0][0]
except Exception as err:
- if classify_query_error(err) is not QueryErrorCategory.CANCELLED:
+ if classify_query_error(err) is QueryErrorCategory.CANCELLED:
+ # The caller killed this search, so there is no body to return and nothing went
+ # wrong. Raising would report a server error for every cancelled search.
+ #
+ # Returning also leaves the SLO block without an exception, so it records a
+ # success with however long the kill took. A cancel is not a failure, so the
+ # outcome stays as it is and this tag is what keeps an abandoned search from
+ # reading as a fast one in the latency percentiles.
+ slo.tag(cancelled=True)
+ return Response(status=HTTP_CLIENT_CLOSED_REQUEST)
+ if not hit_leads_page:
raise
- # The caller killed this search, so there is no body to return and nothing went
- # wrong. Raising would report a server error for every cancelled search.
- #
- # Returning also leaves the SLO block without an exception, so it records a
- # success with however long the kill took. A cancel is not a failure, so the
- # outcome stays as it is and this tag is what keeps an abandoned search from
- # reading as a fast one in the latency percentiles.
- slo.tag(cancelled=True)
- return Response(status=HTTP_CLIENT_CLOSED_REQUEST)
-
- slo.tag(answered_by="clickhouse", result_count=len(actor_ids))
- return self._person_list_response(request, actor_ids, filter, total_count=total_count)
+ # Degrade to the personhog hit instead of failing the request.
+ capture_exception(err)
+ slo.fail(error_type=type(err).__name__)
+ finally:
+ if email_property_search:
+ # The runner tags `has_search=False` because this query has no `search` field.
+ slo.tag(has_search=True)
+
+ if hit_leads_page:
+ listed = {str(actor_id) for actor_id in actor_ids}
+ actor_ids = [*(hit for hit in exact_hits if hit not in listed), *actor_ids]
+
+ slo.tag(answered_by=answered_by, result_count=len(actor_ids))
+ return self._person_list_response(
+ request, actor_ids, filter, total_count=total_count, tag_term=tag_term, exact_hits=exact_hits
+ )
def _person_list_response(
self,
@@ -818,8 +919,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
filter: Filter,
total_count: Optional[int] = None,
has_next: Optional[bool] = None,
+ tag_term: Optional[str] = None,
+ exact_hits: Optional[Mapping[str, Collection[str]]] = None,
) -> Response:
team = self.team
+ exact_hits = exact_hits or {}
with personhog_caller_tag("persons/list"):
serialized_actors = get_serialized_people(team, person_uuids) if person_uuids else []
@@ -832,6 +936,16 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
k: v for k, v in properties.items() if k not in restricted_person_properties
}
+ # After the restriction, so no tag reveals a hidden property. CSV would turn the list into
+ # per-row columns.
+ if tag_term and self.request.accepted_renderer.format != "csv":
+ for person_dict in serialized_actors:
+ known_fields = exact_hits.get(str(person_dict["id"]), ())
+ person_dict["matched_fields"] = _search_match_fields(tag_term, person_dict, known_fields)
+ if exact_hits:
+ # Hydration sorts by creation date.
+ serialized_actors.sort(key=lambda person_dict: str(person_dict["id"]) not in exact_hits)
+
# A full page means there may be more behind it. Callers that know the whole result set up
# front say so instead, so a page that happens to fill the limit does not advertise an
# empty page after it.
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 0a2955ed1811..b0f701ffe22d 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -1,4 +1,6 @@
import json
+import functools
+from datetime import timedelta
from typing import Optional, cast
from uuid import UUID, uuid4
@@ -31,6 +33,7 @@ from posthog.api.person import tag_client_query_id
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags
from posthog.constants import AvailableFeature
+from posthog.hogql_queries.serialized_actors import get_serialized_people
from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person.missing_person import uuidFromDistinctId
@@ -86,11 +89,11 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
flush_persons_and_events()
response = self.client.get("/api/person/?search=another@gm")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.json()["results"]), 1)
+ self.assertEqual([result.get("matched_fields") for result in response.json()["results"]], [None])
- response = self.client.get("/api/person/?search=distinct_id_3")
+ response = self.client.get("/api/person/?search=distinct_id_3&include_matched_fields=true")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.json()["results"]), 1)
+ self.assertEqual([result["matched_fields"] for result in response.json()["results"]], [["distinct_id"]])
@staticmethod
def _persons_list_slo_events(capture: mock.MagicMock) -> list[dict]:
@@ -106,6 +109,14 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
("partial search", "?search=another@gm", True, False, "clickhouse", "person"),
("no search", "", False, False, "clickhouse", "person"),
("exact identifier", "[email protected]", True, False, "exact_identifier", None),
+ (
+ "exact identifier and email property",
+ "[email protected]&include_matched_fields=true",
+ True,
+ False,
+ "exact_identifier_and_email",
+ "person",
+ ),
("client query id", "?search=another@gm&client_query_id=abc-123", True, True, "clickhouse", "person"),
]
)
@@ -182,13 +193,59 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
response = self.client.get(f"/api/person/?search=someone{extra_params}")
self.assertEqual(response.status_code, 499)
- def test_search_still_fails_on_a_query_error_that_is_not_a_cancellation(self) -> None:
- with mock.patch(
- "posthog.hogql_queries.actors_query_runner.ActorsQueryRunner.calculate",
- side_effect=ServerException("Boom", code=999),
+ @parameterized.expand(
+ [
+ ("partial term", "?search=someone", status.HTTP_500_INTERNAL_SERVER_ERROR, None, None),
+ (
+ "email hit",
+ "[email protected]&include_matched_fields=true",
+ status.HTTP_200_OK,
+ "exact_identifier_and_email",
+ ["distinct_id", "email"],
+ ),
+ (
+ "email hit past the first page",
+ "[email protected]&offset=1&include_matched_fields=true",
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
+ None,
+ None,
+ ),
+ ]
+ )
+ def test_search_on_a_query_error_that_is_not_a_cancellation(
+ self,
+ _name: str,
+ query: str,
+ expected_status: int,
+ expected_answered_by: Optional[str],
+ expected_matched_fields: Optional[list[str]],
+ ) -> None:
+ _create_person(
+ team=self.team,
+ distinct_ids=["[email protected]"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ # Below `calculate`, so the runner's own SLO tags still apply.
+ with (
+ mock.patch(
+ "posthog.hogql_queries.paginators.execute_hogql_query",
+ side_effect=ServerException("Boom", code=999),
+ ),
+ mock.patch("posthog.slo.events.posthoganalytics.capture") as capture,
):
- response = self.client.get("/api/person/?search=someone")
- self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ response = self.client.get(f"/api/person/{query}")
+ self.assertEqual(response.status_code, expected_status)
+ if expected_matched_fields is not None:
+ self.assertEqual(
+ [result["matched_fields"] for result in response.json()["results"]], [expected_matched_fields]
+ )
+
+ completed = self._persons_list_slo_events(capture)
+ self.assertEqual(len(completed), 1)
+ self.assertEqual(completed[0]["outcome"], "failure")
+ self.assertTrue(completed[0]["has_search"])
+ self.assertEqual(completed[0].get("answered_by"), expected_answered_by)
@also_test_with_materialized_columns(event_properties=["email"], person_properties=["email"])
@snapshot_clickhouse_queries
@@ -223,18 +280,109 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# second page. Following it would leave the fast path and run the ClickHouse search for
# results that cannot exist.
for url, expected in [
- (f"/api/person/?search={person.uuid}&limit=1", person),
- ("/api/person/[email protected]&limit=1", person),
- (f"/api/person/?search={anonymous_distinct_id}&limit=1", anonymous),
- ("/api/person/[email protected]&limit=1", person),
+ (f"/api/person/?search={person.uuid}&limit=1", [person]),
+ (f"/api/person/?search={person.uuid}&limit=1&offset=1&include_matched_fields=true", []),
+ ("/api/person/[email protected]&limit=1", [person]),
+ (f"/api/person/?search={anonymous_distinct_id}&limit=1", [anonymous]),
+ ("/api/person/[email protected]&limit=1", [person]),
+ ("/api/person/[email protected]&limit=1&offset=1&include_matched_fields=true", []),
]:
with self.subTest(url=url), self.capture_select_queries() as clickhouse_queries:
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual([result["id"] for result in response.json()["results"]], [str(expected.uuid)])
+ self.assertEqual(
+ [result["id"] for result in response.json()["results"]], [str(match.uuid) for match in expected]
+ )
self.assertIsNone(response.json()["next"])
self.assertEqual(clickhouse_queries, [])
+ def test_search_by_email_lists_the_property_matches_behind_the_distinct_id_hit(self) -> None:
+ by_distinct_id = _create_person(
+ team=self.team,
+ distinct_ids=["[email protected]"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ by_property = _create_person(
+ team=self.team,
+ distinct_ids=["0198f3c1-6c2a-7a5b-9d41-9a1b2c3d4e5f"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ by_title_cased_property = _create_person(
+ team=self.team,
+ distinct_ids=["0198f3c1-6c2a-7a5b-9d41-9a1b2c3d4e60"],
+ properties={"Email": "[email protected]"},
+ created_at=timezone.now() - timedelta(days=1),
+ immediate=True,
+ )
+ by_name = _create_person(
+ team=self.team,
+ distinct_ids=["0198f3c1-6c2a-7a5b-9d41-9a1b2c3d4e61"],
+ properties={"name": "[email protected]"},
+ created_at=timezone.now() - timedelta(days=2),
+ immediate=True,
+ )
+ _create_person(
+ team=self.team, distinct_ids=["[email protected]"], properties={"email": "[email protected]"}, immediate=True
+ )
+ flush_persons_and_events()
+
+ with self.capture_select_queries() as clickhouse_queries:
+ response = self.client.get(
+ "/api/person/[email protected]&include_total=true&include_matched_fields=true"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ [(result["id"], result["matched_fields"]) for result in response.json()["results"]],
+ [
+ (str(by_distinct_id.uuid), ["distinct_id", "email"]),
+ (str(by_property.uuid), ["email"]),
+ (str(by_title_cased_property.uuid), ["email"]),
+ (str(by_name.uuid), ["name"]),
+ ],
+ )
+ self.assertEqual(response.json()["count"], 4)
+ self.assertIsNone(response.json()["next"])
+ # The distinct ID scan is what makes the fuzzy search slow.
+ person_queries = [
+ query for query in clickhouse_queries if "system.columns" not in query and "system.tables" not in query
+ ]
+ self.assertEqual(len(person_queries), 2)
+ for query in person_queries:
+ self.assertNotIn("person_distinct_id2", query)
+
+ listed: list[str] = []
+ next_url: Optional[str] = (
+ "/api/person/[email protected]&limit=1&include_total=true&include_matched_fields=true"
+ )
+ while next_url:
+ with self.capture_select_queries() as clickhouse_queries:
+ response = self.client.get(next_url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["count"], 4)
+ listed.extend(result["id"] for result in response.json()["results"])
+ for query in clickhouse_queries:
+ self.assertNotIn("person_distinct_id2", query)
+ next_url = response.json()["next"]
+ self.assertEqual(
+ listed,
+ [str(by_distinct_id.uuid), str(by_property.uuid), str(by_title_cased_property.uuid), str(by_name.uuid)],
+ )
+
+ def test_search_by_email_tags_the_distinct_id_hit_past_the_hydration_cap(self) -> None:
+ _create_person(team=self.team, distinct_ids=["[email protected]"], properties={"name": "Abe"}, immediate=True)
+ flush_persons_and_events()
+
+ hydrate_no_distinct_ids = functools.partial(get_serialized_people, distinct_id_limit=0)
+ with mock.patch("posthog.api.person.get_serialized_people", new=hydrate_no_distinct_ids):
+ response = self.client.get("/api/person/[email protected]&include_matched_fields=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ [(result["distinct_ids"], result["matched_fields"]) for result in response.json()["results"]],
+ [([], ["distinct_id"])],
+ )
+
def test_search_by_exact_identifier_still_applies_other_filters(self) -> None:
_create_person(
team=self.team,
@@ -1981,6 +2129,11 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(len(response.content.splitlines()), 2)
+ response = self.client.get("/api/person.csv?search=4&include_matched_fields=true")
+ lines = response.content.splitlines()
+ self.assertGreater(len(lines), 1)
+ self.assertNotIn(b"matched_fields", lines[0])
+
@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_pagination_limit(self):
created_ids = []
@@ -2523,3 +2676,25 @@ class TestPersonBatchRestrictedProperties(ClickhouseTestMixin, APIBaseTest):
properties = response.json()["results"][result_key]["properties"]
self.assertEqual(properties.get("email"), "[email protected]")
self.assertNotIn("ssn", properties)
+
+ def test_search_does_not_tag_a_restricted_property(self) -> None:
+ email = PropertyDefinition.objects.create(
+ team=self.team, name="email", property_type="String", type=PropertyDefinition.Type.PERSON
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=email, access_level=PropertyAccessLevel.NONE.value
+ )
+ _create_person(
+ team=self.team,
+ distinct_ids=["[email protected]"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ flush_persons_and_events()
+
+ response = self.client.get("/api/person/[email protected]&include_matched_fields=true")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ [(result["properties"], result["matched_fields"]) for result in response.json()["results"]],
+ [({}, ["distinct_id"])],
+ )
diff --git a/posthog/hogql_queries/serialized_actors.py b/posthog/hogql_queries/serialized_actors.py
index d512825e4842..13ec6e82902f 100644
--- a/posthog/hogql_queries/serialized_actors.py
+++ b/posthog/hogql_queries/serialized_actors.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime
-from typing import Any, Literal, Optional, TypedDict, Union
+from typing import Any, Literal, NotRequired, Optional, TypedDict, Union
from django.db.models.query import QuerySet
@@ -42,6 +42,7 @@ class SerializedPerson(CommonActor):
is_identified: Optional[bool]
name: str
distinct_ids: list[str]
+ matched_fields: NotRequired[list[str]]
class SerializedGroup(CommonActor):
diff --git a/products/persons/frontend/components/PersonSearchMatchTags.stories.tsx b/products/persons/frontend/components/PersonSearchMatchTags.stories.tsx
new file mode 100644
index 000000000000..274020f216c4
--- /dev/null
+++ b/products/persons/frontend/components/PersonSearchMatchTags.stories.tsx
@@ -0,0 +1,17 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { PersonSearchMatchTags } from './PersonSearchMatchTags'
+
+const meta: Meta<typeof PersonSearchMatchTags> = {
+ title: 'Scenes-App/People/PersonSearchMatchTags',
+ component: PersonSearchMatchTags,
+ parameters: { layout: 'padded', viewMode: 'story' },
+}
+
+export default meta
+
+type Story = StoryObj<typeof PersonSearchMatchTags>
+
+export const EveryField: Story = {
+ args: { matchedFields: ['distinct_id', 'email', 'name', 'id'] },
+}
diff --git a/products/persons/frontend/components/PersonSearchMatchTags.tsx b/products/persons/frontend/components/PersonSearchMatchTags.tsx
new file mode 100644
index 000000000000..8faf45dceafa
--- /dev/null
+++ b/products/persons/frontend/components/PersonSearchMatchTags.tsx
@@ -0,0 +1,35 @@
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import type { PersonSearchMatchFieldEnumApi } from '../generated/api.schemas'
+
+type TagContent = { label: string; explanation: string }
+
+const TAG_BY_FIELD: Record<PersonSearchMatchFieldEnumApi, TagContent> = {
+ distinct_id: { label: 'Distinct ID', explanation: "The search matched one of this person's distinct IDs." },
+ email: { label: 'Email', explanation: "The search matched this person's email property." },
+ name: { label: 'Name', explanation: "The search matched this person's name property." },
+ id: { label: 'Person ID', explanation: "The search matched this person's ID." },
+}
+
+export function PersonSearchMatchTags({
+ matchedFields,
+}: {
+ matchedFields?: PersonSearchMatchFieldEnumApi[]
+}): JSX.Element | null {
+ // Skip fields newer than this bundle.
+ const tags = (matchedFields ?? []).flatMap((field) => TAG_BY_FIELD[field] ?? [])
+ if (tags.length === 0) {
+ return null
+ }
+ return (
+ <span className="flex gap-1">
+ {tags.map(({ label, explanation }) => (
+ <Tooltip key={label} title={explanation}>
+ <LemonTag type="muted" size="small" data-attr="person-search-match-tag">
+ {label}
+ </LemonTag>
+ </Tooltip>
+ ))}
+ </span>
+ )
+}
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 8e2ccbfe18a8..4a4d771fa636 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -195,7 +195,23 @@ export interface PropertyApi {
values: PropertyItemApi[]
}
-export interface PersonRecordApi {
+/**
+ * * `distinct_id` - Distinct ID
+ * * `email` - Email
+ * * `name` - Name
+ * * `id` - Person ID
+ */
+export type PersonSearchMatchFieldEnumApi =
+ (typeof PersonSearchMatchFieldEnumApi)[keyof typeof PersonSearchMatchFieldEnumApi]
+
+export const PersonSearchMatchFieldEnumApi = {
+ DistinctId: 'distinct_id',
+ Email: 'email',
+ Name: 'name',
+ Id: 'id',
+} as const
+
+export interface PersonListRecordApi {
/** Numeric person ID. */
readonly id: number
/** Display name derived from person properties (email, name, or username). */
@@ -212,15 +228,36 @@ export interface PersonRecordApi {
* @nullable
*/
readonly last_seen_at: string | null
+ /** Only on a search result with `include_matched_fields`: the searched fields the term was found in. */
+ matched_fields?: PersonSearchMatchFieldEnumApi[]
}
-export interface PaginatedPersonRecordListApi {
+export interface PaginatedPersonListRecordListApi {
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
count?: number
- results?: PersonRecordApi[]
+ results?: PersonListRecordApi[]
+}
+
+export interface PersonRecordApi {
+ /** Numeric person ID. */
+ readonly id: number
+ /** Display name derived from person properties (email, name, or username). */
+ readonly name: string
+ readonly distinct_ids: readonly string[]
+ /** Key-value map of person properties set via $set and $set_once operations. */
+ properties?: unknown
+ /** When this person was first seen (ISO 8601). */
+ readonly created_at: string
+ /** Unique identifier (UUID) for this person. */
+ readonly uuid: string
+ /**
+ * Timestamp of the last event from this person, or null.
+ * @nullable
+ */
+ readonly last_seen_at: string | null
}
export interface PatchedPersonRecordApi {
@@ -445,6 +482,10 @@ export type PersonsListParams = {
*/
email?: string
format?: PersonsListFormat
+ /**
+ * Tag each search result with `matched_fields`, the searched fields the term was found in. A complete email address that exactly matches a distinct ID then returns that person first, followed by every person whose email or name property contains the address.
+ */
+ include_matched_fields?: boolean
/**
* Number of results to return per page.
*/
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index 574560c8381a..0e3ded8a275b 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -11,7 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
MessageAssetApi,
PaginatedAsyncDeletionStatusListApi,
- PaginatedPersonRecordListApi,
+ PaginatedPersonListRecordListApi,
PatchedPersonRecordApi,
PersonBulkDeleteRequestApi,
PersonBulkDeleteResponseApi,
@@ -84,8 +84,8 @@ export const personsList = async (
projectId: string,
params?: PersonsListParams,
options?: RequestInit
-): Promise<PaginatedPersonRecordListApi> => {
- return apiMutator<PaginatedPersonRecordListApi>(getPersonsListUrl(projectId, params), {
+): Promise<PaginatedPersonListRecordListApi> => {
+ return apiMutator<PaginatedPersonListRecordListApi>(getPersonsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yaml
index 7dcb4228c4ef..39a92a8d04b3 100644
--- a/products/persons/mcp/tools.yaml
+++ b/products/persons/mcp/tools.yaml
@@ -76,6 +76,7 @@ tools:
exclude_params:
- format
- properties
+ - include_matched_fields
param_overrides:
limit:
cast: string-int
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bbdc95c83055..d3aae6756993 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -63728,7 +63728,23 @@ export namespace Schemas {
results: PauseStateResponse[];
}
- export interface PersonRecord {
+ /**
+ * * `distinct_id` - Distinct ID
+ * * `email` - Email
+ * * `name` - Name
+ * * `id` - Person ID
+ */
+ export type PersonSearchMatchFieldEnum = typeof PersonSearchMatchFieldEnum[keyof typeof PersonSearchMatchFieldEnum];
+
+
+ export const PersonSearchMatchFieldEnum = {
+ DistinctId: 'distinct_id',
+ Email: 'email',
+ Name: 'name',
+ Id: 'id',
+ } as const;
+
+ export interface PersonListRecord {
/** Numeric person ID. */
readonly id: number;
/** Display name derived from person properties (email, name, or username). */
@@ -63745,15 +63761,17 @@ export namespace Schemas {
* @nullable
*/
readonly last_seen_at: string | null;
+ /** Only on a search result with `include_matched_fields`: the searched fields the term was found in. */
+ matched_fields?: PersonSearchMatchFieldEnum[];
}
- export interface PaginatedPersonRecordList {
+ export interface PaginatedPersonListRecordList {
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
count?: number;
- results?: PersonRecord[];
+ results?: PersonListRecord[];
}
/**
@@ -78397,6 +78415,25 @@ export namespace Schemas {
point_in_time_metadata: PersonPropertiesAtTimeMetadata;
}
+ export interface PersonRecord {
+ /** Numeric person ID. */
+ readonly id: number;
+ /** Display name derived from person properties (email, name, or username). */
+ readonly name: string;
+ readonly distinct_ids: readonly string[];
+ /** Key-value map of person properties set via $set and $set_once operations. */
+ properties?: unknown;
+ /** When this person was first seen (ISO 8601). */
+ readonly created_at: string;
+ /** Unique identifier (UUID) for this person. */
+ readonly uuid: string;
+ /**
+ * Timestamp of the last event from this person, or null.
+ * @nullable
+ */
+ readonly last_seen_at: string | null;
+ }
+
export interface PersonSplitRequest {
/**
* The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.
@@ -113125,6 +113162,10 @@ export namespace Schemas {
*/
email?: string;
format?: PersonsListFormat;
+ /**
+ * Tag each search result with `matched_fields`, the searched fields the term was found in. A complete email address that exactly matches a distinct ID then returns that person first, followed by every person whose email or name property contains the address.
+ */
+ include_matched_fields?: boolean;
/**
* Number of results to return per page.
*/
diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.ts
index 0c801db33f34..a81b39998030 100644
--- a/services/mcp/src/generated/persons/api.ts
+++ b/services/mcp/src/generated/persons/api.ts
@@ -33,6 +33,12 @@ export const PersonsListQueryParams = () => zod.object({
distinct_id: zod.string().optional().describe('Filter list by distinct id.'),
email: zod.string().optional().describe('Filter persons by email (exact match)'),
format: zod.enum(['csv', 'json']).optional(),
+ include_matched_fields: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Tag each search result with `matched_fields`, the searched fields the term was found in. A complete email address that exactly matches a distinct ID then returns that person first, followed by every person whose email or name property contains the address.'
+ ),
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.'),
properties: zod
diff --git a/services/mcp/src/tools/generated/persons.ts b/services/mcp/src/tools/generated/persons.ts
index 3adbe12b2cfa..c832d9a32885 100644
--- a/services/mcp/src/tools/generated/persons.ts
+++ b/services/mcp/src/tools/generated/persons.ts
@@ -68,7 +68,7 @@ const personsCohortsRetrieve = (): ToolBase<
const PersonsListSchema = () => {
const PersonsListQueryParams = orvalSchemas.PersonsListQueryParams()
- return PersonsListQueryParams.omit({ format: true, properties: true }).extend({
+ return PersonsListQueryParams.omit({ format: true, include_matched_fields: true, properties: true }).extend({
limit: z.preprocess(castStringToInt, PersonsListQueryParams.shape['limit']).optional(),
offset: z.preprocess(castStringToInt, PersonsListQueryParams.shape['offset']).optional(),
})
@@ -76,13 +76,13 @@ const PersonsListSchema = () => {
const personsList = (): ToolBase<
ReturnType<typeof PersonsListSchema>,
- WithPostHogUrl<Schemas.PaginatedPersonRecordList>
+ WithPostHogUrl<Schemas.PaginatedPersonListRecordList>
> => ({
name: 'persons-list',
schema: PersonsListSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof PersonsListSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedPersonRecordList>({
+ const result = await context.api.request<Schemas.PaginatedPersonListRecordList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/persons/`,
query: {