Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(persons): answer exact identifier searches without ClickHouse (#87850)

Thomas Obermüller112b7d15533a
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 0b4e0ae4fab4..0ce03b6b6d67 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1,3 +1,4 @@
+import re
import json
import uuid
import builtins
@@ -61,7 +62,9 @@ from posthog.models.person.deletion import reset_deleted_person_distinct_ids
from posthog.models.person.missing_person import MissingPerson
from posthog.models.person.util import (
get_distinct_ids_for_persons,
+ get_person_by_distinct_id,
get_person_by_pk_or_uuid,
+ get_person_by_uuid,
get_persons_by_uuids,
get_persons_mapped_by_distinct_id,
)
@@ -135,6 +138,12 @@ API_PERSON_LIST_BYTES_READ_FROM_POSTGRES_COUNTER = Counter(
labelnames=[LABEL_TEAM_ID],
)
+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.",
+ labelnames=["answered_by"],
+)
+
class PersonLimitOffsetPagination(LimitOffsetPagination):
def get_paginated_response_schema(self, schema):
@@ -477,6 +486,46 @@ _GET_OBJECT_DISTINCT_ID_LIMITS: dict[str, int] = {
}
+# A term shaped like a full email address or a UUID names one person, so an exact identifier
+# hit answers the search. Shorter terms stay fuzzy: a partial numeric or alphanumeric ID often
+# matches one person exactly while the user is still typing, and short-circuiting there would
+# hide the other matches.
+_COMPLETE_EMAIL_TERM = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+
+
+def _is_canonical_uuid(value: str) -> bool:
+ # Only the dashed form counts, so the fast path answers the same terms the fuzzy search
+ # matches. UUID() also accepts braced and undashed input, which no stored ID string carries.
+ try:
+ return str(uuid.UUID(value)) == value.lower()
+ except ValueError:
+ 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.
+
+ 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
+ ClickHouse query slot, and pasted emails and IDs are most of what people search for.
+ """
+ term_is_uuid = _is_canonical_uuid(search)
+ if not term_is_uuid and not _COMPLETE_EMAIL_TERM.match(search):
+ return []
+
+ matches: 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))
+ 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
+
+
@extend_schema(extensions={"x-product": ProductKey.PERSONS})
@extend_schema_view(
retrieve=_id_schema,
@@ -562,7 +611,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
OpenApiParameter(
"search",
OpenApiTypes.STR,
- description="Search persons, either by email (full text search) or distinct_id (exact match).",
+ description=(
+ "Search persons by email, name, person ID, or distinct ID. Partial values match. "
+ "When the term is a complete email address or UUID that exactly matches a distinct ID "
+ "or person ID, only that person is returned."
+ ),
),
OpenApiParameter(
"client_query_id",
@@ -595,7 +648,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415
- from posthog.models.person.util import get_person_by_distinct_id # noqa: PLC0415
person_properties: list[dict] = []
raw_properties = request.GET.get("properties")
@@ -607,31 +659,13 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
person_properties.append(prop)
if filter.email:
person_properties.append({"type": "person", "key": "email", "value": filter.email, "operator": "exact"})
- 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)
- if matched is None:
- # Return early: a constant-false predicate can't be pushed into the persons
- # lazy table, so ClickHouse would still aggregate every person row for the
- # team before filtering everything out.
- return Response(
- {
- "results": [],
- "next": None,
- "previous": None,
- **({"count": 0} if "include_total" in request.GET else {}),
- }
- )
- person_properties.append({"type": "hogql", "key": f"id = toUUID('{matched.uuid}')"})
- actors_query = ActorsQuery(
- select=["id"],
- properties=person_properties,
- search=filter.search or None,
- orderBy=["created_at DESC", "id DESC"],
- limit=filter.limit,
- offset=filter.offset,
- )
+
include_total = "include_total" in request.GET
+ search = (filter.search or "").strip()
+ # 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
+
# 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
# duration. The search term itself is never recorded - it is user data.
@@ -648,6 +682,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"limit": filter.limit,
"offset": filter.offset,
}
+ # The block wraps the identifier fast paths too, not just the ClickHouse one. Measuring
+ # only the slow path would drop every fast answer out of the sample, so the endpoint would
+ # look slower the more requests it answers without ClickHouse. `answered_by` separates them.
with slo_operation(
spec=SloSpec(
# `User.distinct_id` is nullable, so fall back to the team like the query service does.
@@ -659,6 +696,49 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
properties=slo_properties,
) as slo:
+ 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)
+ if matched is None:
+ # Return early: a constant-false predicate can't be pushed into the persons
+ # lazy table, so ClickHouse would still aggregate every person row for the
+ # team before filtering everything out.
+ 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)
+ return self._person_list_response(
+ request,
+ [str(matched.uuid)],
+ 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]
+ 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,
+ )
+
+ actors_query = ActorsQuery(
+ select=["id"],
+ properties=person_properties,
+ search=filter.search or None,
+ orderBy=["created_at DESC", "id DESC"],
+ limit=filter.limit,
+ offset=filter.offset,
+ )
# Use .calculate() (not .run()) — it applies the limit/offset paginator but skips the
# 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.
@@ -668,20 +748,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
try:
actor_ids = [row[0] for row in actors_runner.calculate().results]
- with personhog_caller_tag("persons/list"):
- serialized_actors = get_serialized_people(team, actor_ids)
-
- restricted_person_properties = self.get_serializer_context().get("restricted_person_properties")
- if restricted_person_properties:
- for person_dict in serialized_actors:
- properties = person_dict.get("properties")
- if isinstance(properties, dict):
- person_dict["properties"] = {
- k: v for k, v in properties.items() if k not in restricted_person_properties
- }
-
- _should_paginate = len(actor_ids) >= filter.limit
-
# 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
@@ -708,7 +774,34 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
slo.tag(cancelled=True)
return Response(status=HTTP_CLIENT_CLOSED_REQUEST)
- slo.tag(result_count=len(actor_ids))
+ slo.tag(answered_by="clickhouse", result_count=len(actor_ids))
+ return self._person_list_response(request, actor_ids, filter, total_count=total_count)
+
+ def _person_list_response(
+ self,
+ request: request.Request,
+ person_uuids: builtins.list[Any],
+ filter: Filter,
+ total_count: Optional[int] = None,
+ has_next: Optional[bool] = None,
+ ) -> Response:
+ team = self.team
+ with personhog_caller_tag("persons/list"):
+ serialized_actors = get_serialized_people(team, person_uuids) if person_uuids else []
+
+ restricted_person_properties = self.get_serializer_context().get("restricted_person_properties")
+ if restricted_person_properties:
+ for person_dict in serialized_actors:
+ properties = person_dict.get("properties")
+ if isinstance(properties, dict):
+ person_dict["properties"] = {
+ k: v for k, v in properties.items() if k not in restricted_person_properties
+ }
+
+ # 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.
+ _should_paginate = len(person_uuids) >= filter.limit if has_next is None else has_next
next_url = format_query_params_absolute_url(request, filter.offset + filter.limit) if _should_paginate else None
previous_url = (
diff --git a/posthog/api/test/__snapshots__/test_person.ambr b/posthog/api/test/__snapshots__/test_person.ambr
index 1bf95770eba9..0cf69b677367 100644
--- a/posthog/api/test/__snapshots__/test_person.ambr
+++ b/posthog/api/test/__snapshots__/test_person.ambr
@@ -35,78 +35,6 @@
'''
# ---
# name: TestPerson.test_filter_person_list
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestPerson.test_filter_person_list.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestPerson.test_filter_person_list.2
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS id
@@ -141,7 +69,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPerson.test_filter_person_list.3
+# name: TestPerson.test_filter_person_list.1
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS id
@@ -426,58 +354,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPerson.test_search_person_id
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(where_optimization.id), '%00000000-0000-4000-8000-000000000000%'), in(where_optimization.id,
- (SELECT person_distinct_ids.person_id AS person_id
- FROM
- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
- FROM person_distinct_id2
- WHERE equals(person_distinct_id2.team_id, 99999)
- GROUP BY person_distinct_id2.distinct_id
- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
- WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE or(ifNull(ilike(toString(persons.properties___email), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(persons.properties___name), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(persons.id), '%00000000-0000-4000-8000-000000000000%'), in(persons.id,
- (SELECT person_distinct_ids.person_id AS person_id
- FROM
- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
- FROM person_distinct_id2
- WHERE equals(person_distinct_id2.team_id, 99999)
- GROUP BY person_distinct_id2.distinct_id
- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
- WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestPersonFromClickhouse.test_filter_person_email
'''
/* user_id:0 request:_snapshot_ */
@@ -514,78 +390,6 @@
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestPersonFromClickhouse.test_filter_person_list.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
- and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestPersonFromClickhouse.test_filter_person_list.2
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS id
@@ -620,7 +424,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonFromClickhouse.test_filter_person_list.3
+# name: TestPersonFromClickhouse.test_filter_person_list.1
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS id
@@ -905,55 +709,3 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonFromClickhouse.test_search_person_id
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
- tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(where_optimization.id), '%00000000-0000-4000-8000-000000000000%'), in(where_optimization.id,
- (SELECT person_distinct_ids.person_id AS person_id
- FROM
- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
- FROM person_distinct_id2
- WHERE equals(person_distinct_id2.team_id, 99999)
- GROUP BY person_distinct_id2.distinct_id
- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
- WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE or(ifNull(ilike(toString(persons.properties___email), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(persons.properties___name), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(persons.id), '%00000000-0000-4000-8000-000000000000%'), in(persons.id,
- (SELECT person_distinct_ids.person_id AS person_id
- FROM
- (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
- FROM person_distinct_id2
- WHERE equals(person_distinct_id2.team_id, 99999)
- GROUP BY person_distinct_id2.distinct_id
- HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
- WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 08c176887026..a8cf22a09db3 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -101,18 +101,26 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@parameterized.expand(
[
- ("?search=another@gm", True, False),
- ("", False, False),
- ("?search=another@gm&client_query_id=abc-123", True, True),
+ ("partial search", "?search=another@gm", True, False, "clickhouse", "person"),
+ ("no search", "", False, False, "clickhouse", "person"),
+ ("exact identifier", "[email protected]", True, False, "exact_identifier", None),
+ ("client query id", "?search=another@gm&client_query_id=abc-123", True, True, "clickhouse", "person"),
]
)
def test_person_list_emits_slo_event(
- self, query: str, expected_has_search: bool, expected_has_client_query_id: bool
+ self,
+ _name: str,
+ query: str,
+ expected_has_search: bool,
+ expected_has_client_query_id: bool,
+ expected_answered_by: str,
+ expected_actor_type: Optional[str],
) -> None:
_create_person(
team=self.team,
- distinct_ids=["distinct_id"],
+ distinct_ids=["[email protected]"],
properties={"email": "[email protected]"},
+ immediate=True,
)
flush_persons_and_events()
@@ -124,10 +132,12 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(len(completed), 1)
self.assertEqual(completed[0]["has_search"], expected_has_search)
self.assertEqual(completed[0]["has_client_query_id"], expected_has_client_query_id)
- self.assertEqual(completed[0]["actor_type"], "person")
+ self.assertEqual(completed[0]["answered_by"], expected_answered_by)
self.assertEqual(completed[0]["outcome"], "success")
self.assertEqual(completed[0]["result_count"], 1)
self.assertGreater(completed[0]["duration_ms"], 0)
+ # Only the ClickHouse path runs the actors query runner, which is what tags the actor type.
+ self.assertEqual(completed[0].get("actor_type"), expected_actor_type)
def test_cancelled_search_is_marked_on_the_slo_event(self) -> None:
with (
@@ -191,6 +201,58 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
+ def test_search_by_exact_identifier_skips_clickhouse(self) -> None:
+ person = _create_person(
+ team=self.team,
+ distinct_ids=["[email protected]"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ anonymous_distinct_id = "0198f3c1-6c2a-7a5b-9d41-9a1b2c3d4e5f"
+ anonymous = _create_person(
+ team=self.team,
+ distinct_ids=[anonymous_distinct_id],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ flush_persons_and_events()
+
+ # `limit=1` fills the page with the single match, so a page-full paginator would offer a
+ # 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),
+ ]:
+ 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.assertIsNone(response.json()["next"])
+ self.assertEqual(clickhouse_queries, [])
+
+ def test_search_by_exact_identifier_still_applies_other_filters(self) -> None:
+ _create_person(
+ team=self.team,
+ distinct_ids=["[email protected]"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ flush_persons_and_events()
+
+ other_email = json.dumps(
+ [{"key": "email", "value": "[email protected]", "operator": "exact", "type": "person"}]
+ )
+ response = self.client.get(f"/api/person/[email protected]&properties={other_email}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ response = self.client.get("/api/person/[email protected]&offset=1")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
@also_test_with_materialized_columns(event_properties=["email"], person_properties=["email"])
@snapshot_clickhouse_queries
def test_properties(self) -> None:
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 8fc97f973117..5c5af89a30b0 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -432,7 +432,7 @@ export type PersonsListParams = {
*/
properties?: PropertyApi[]
/**
- * Search persons, either by email (full text search) or distinct_id (exact match).
+ * Search persons by email, name, person ID, or distinct ID. Partial values match. When the term is a complete email address or UUID that exactly matches a distinct ID or person ID, only that person is returned.
*/
search?: string
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 440f14ed2af8..7c6bdb411b14 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -95147,7 +95147,7 @@ export namespace Schemas {
*/
properties?: Property[];
/**
- * Search persons, either by email (full text search) or distinct_id (exact match).
+ * Search persons by email, name, person ID, or distinct ID. Partial values match. When the term is a complete email address or UUID that exactly matches a distinct ID or person ID, only that person is returned.
*/
search?: string;
};
diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.ts
index eb1c1d039eb8..f47e02e2f2c6 100644
--- a/services/mcp/src/generated/persons/api.ts
+++ b/services/mcp/src/generated/persons/api.ts
@@ -142,7 +142,9 @@ export const PersonsListQueryParams = /* @__PURE__ */ zod.object({
search: zod
.string()
.optional()
- .describe('Search persons, either by email (full text search) or distinct_id (exact match).'),
+ .describe(
+ 'Search persons by email, name, person ID, or distinct ID. Partial values match. When the term is a complete email address or UUID that exactly matches a distinct ID or person ID, only that person is returned.'
+ ),
})
/**
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json
index 11704cf0ed6e..f8ffe246dcda 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json
@@ -22,7 +22,7 @@
"type": "number"
},
"search": {
- "description": "Search persons, either by email (full text search) or distinct_id (exact match).",
+ "description": "Search persons by email, name, person ID, or distinct ID. Partial values match. When the term is a complete email address or UUID that exactly matches a distinct ID or person ID, only that person is returned.",
"type": "string"
}
},