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.

chore(django): add call bounds and caller tags (#64153)

Zach Brown167183ad0ba0
diff --git a/ee/clickhouse/queries/related_actors_query.py b/ee/clickhouse/queries/related_actors_query.py
index 4b242914d6d0..c38e12f26b01 100644
--- a/ee/clickhouse/queries/related_actors_query.py
+++ b/ee/clickhouse/queries/related_actors_query.py
@@ -11,6 +11,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.models import Team
from posthog.models.filters.utils import validate_group_type_index
from posthog.models.property import GroupTypeIndex
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.queries.actor_base_query import (
SerializedActor,
SerializedGroup,
@@ -64,7 +65,8 @@ class RelatedActorsQuery:
return []
tag_queries(name="related-people")
person_ids = self._query_related_people_ids()
- return get_serialized_people(self.team, person_ids)
+ with personhog_caller_tag("persons/related-actors"):
+ return get_serialized_people(self.team, person_ids)
def _query_related_people_ids(self) -> list:
return self._take_first(
diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.py
index 69256682e7cc..ad3369f5a9e7 100644
--- a/ee/hogai/session_summaries/session_group/patterns.py
+++ b/ee/hogai/session_summaries/session_group/patterns.py
@@ -9,6 +9,7 @@ from temporalio.exceptions import ApplicationError
from posthog.models.person import Person
from posthog.models.person.util import get_persons_mapped_by_distinct_id
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from products.replay.backend.models.session_summaries import SingleSessionSummary
@@ -532,7 +533,8 @@ def get_persons_for_sessions_from_distinct_ids(
# No ids to search for persons - return empty mapping
return {}
try:
- distinct_to_person = get_persons_mapped_by_distinct_id(team_id=team_id, distinct_ids=distinct_ids)
+ with personhog_caller_tag("session-summaries/persons"):
+ distinct_to_person = get_persons_mapped_by_distinct_id(team_id=team_id, distinct_ids=distinct_ids)
session_id_to_person_mapping: dict[str, Person | None] = {}
for distinct_id, person in distinct_to_person.items():
person_session_ids = distinct_id_to_session_id_mapping.get(distinct_id)
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 86d835509130..3b73f90ffd29 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -62,6 +62,7 @@ from posthog.models.person.util import get_person_by_uuid, validate_person_uuids
from posthog.models.property.property import Property
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.queries.actor_base_query import get_serialized_people
from posthog.queries.base import determine_parsed_date_for_property_matching
from posthog.queries.person_query import PersonQuery
@@ -1547,7 +1548,8 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
# workload=Workload.OFFLINE, # this endpoint is only used by external API requests
)
actor_ids = [row[0] for row in raw_result]
- serialized_actors = get_serialized_people(team, actor_ids, distinct_id_limit=10)
+ with personhog_caller_tag("cohorts/persons"):
+ serialized_actors = get_serialized_people(team, actor_ids, distinct_id_limit=10)
_should_paginate = len(actor_ids) >= filter.limit
@@ -1643,8 +1645,10 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
except ValueError:
raise ValidationError("person_id must be a valid UUID")
- # Check if person exists and belongs to this team
- person = get_person_by_uuid(team_id=self.team_id, uuid=person_id)
+ # Check if person exists and belongs to this team. Only person.uuid is used, so skip the
+ # distinct-id fetch.
+ with personhog_caller_tag("cohorts/remove-person"):
+ person = get_person_by_uuid(team_id=self.team_id, uuid=person_id, distinct_id_limit=0)
if person is None:
raise NotFound("Person with this UUID does not exist in the cohort's team")
person_uuid = person.uuid
diff --git a/posthog/api/event.py b/posthog/api/event.py
index 1f88fadc6d4e..e5ff36601b75 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -47,6 +47,7 @@ from posthog.models.event.util import ClickhouseEventSerializer
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team import Team
from posthog.models.utils import UUIDT
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
@@ -424,7 +425,8 @@ class EventViewSet(
def _get_people(self, query_result: List[dict], team: Team) -> "dict[str, Person]": # noqa: UP006
distinct_ids = list({event["distinct_id"] for event in query_result})
- return get_persons_mapped_by_distinct_id(team.pk, distinct_ids)
+ with personhog_caller_tag("persons/events-api"):
+ return get_persons_mapped_by_distinct_id(team.pk, distinct_ids)
@extend_schema(
parameters=[
diff --git a/posthog/api/person.py b/posthog/api/person.py
index dca3ceffb246..c27dcd44d2a1 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -63,6 +63,7 @@ from posthog.models.person.util import (
get_persons_by_uuids,
get_persons_mapped_by_distinct_id,
)
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.queries.actor_base_query import ActorBaseQuery, get_serialized_people
from posthog.queries.funnels import ClickhouseFunnelActors, ClickhouseFunnelTrendsActors
from posthog.queries.funnels.funnel_strict_persons import ClickhouseFunnelStrictActors
@@ -422,6 +423,22 @@ _PERSON_ID_PARAMETER = OpenApiParameter(
_id_schema = extend_schema(parameters=[_PERSON_ID_PARAMETER])
+# Per-action distinct-id fetch caps for the person loaded by ``safely_get_object``. Listed actions
+# read only one distinct_id (property updates) or none (``destroy``/``activity`` use the uuid/pk;
+# ``properties_timeline``/``delete_events`` don't read distinct_ids), so the fetch is capped here.
+# Any action not listed falls back to an unbounded fetch — the same default as the underlying client
+# — which is what the full-set actions (``retrieve``, ``split``, ``delete_recordings``) need.
+_GET_OBJECT_DISTINCT_ID_LIMITS: dict[str, int] = {
+ "destroy": 0,
+ "activity": 0,
+ "properties_timeline": 0,
+ "delete_events": 0,
+ "update": 1,
+ "partial_update": 1,
+ "update_property": 1,
+}
+
+
@extend_schema(extensions={"x-product": ProductKey.PERSONS})
@extend_schema_view(
retrieve=_id_schema,
@@ -487,7 +504,10 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
f"The ID provided does not look like a personID. If you are using a distinctId, please use /persons?distinct_id={person_id} instead."
)
- return get_person_by_pk_or_uuid(self.team_id, str(person_id))
+ with personhog_caller_tag(f"persons/{self.action.replace('_', '-')}"):
+ return get_person_by_pk_or_uuid(
+ self.team_id, str(person_id), distinct_id_limit=_GET_OBJECT_DISTINCT_ID_LIMITS.get(self.action)
+ )
@extend_schema(
parameters=[
@@ -535,7 +555,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# workload=Workload.OFFLINE, # this endpoint is only used by external API requests
)
actor_ids = [row[0] for row in raw_paginated_result]
- serialized_actors = get_serialized_people(team, actor_ids)
+ 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:
@@ -931,7 +952,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@extend_schema(request=PersonDeletePropertyRequestSerializer, parameters=[_PERSON_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["person:write"])
def delete_property(self, request: request.Request, pk=None, **kwargs) -> response.Response:
- person = get_person_by_pk_or_uuid(self.team_id, pk)
+ # Only distinct_ids[0] is used (to attribute the property-update event), so bound the fetch to one.
+ with personhog_caller_tag("persons/delete-property"):
+ person = get_person_by_pk_or_uuid(self.team_id, pk, distinct_id_limit=1)
if person is None:
raise Person.DoesNotExist
@@ -1028,7 +1051,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=400,
)
- person = get_person_by_pk_or_uuid(self.team_id, request.GET["person_id"])
+ # Only person.uuid is used below, so skip the distinct-id fetch entirely.
+ with personhog_caller_tag("persons/cohorts"):
+ person = get_person_by_pk_or_uuid(self.team_id, request.GET["person_id"], distinct_id_limit=0)
if person is None:
raise NotFound()
cohort_ids = get_all_cohort_ids_by_person_uuid(str(person.uuid), team.pk)
@@ -1275,10 +1300,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
filter = LifecycleFilter(request=request, data=request.GET.dict(), team=self.team)
filter = prepare_actor_query_filter(filter)
- people = self.lifecycle_class().get_people(
- filter=filter,
- team=team,
- )
+ with personhog_caller_tag("persons/lifecycle"):
+ people = self.lifecycle_class().get_people(
+ filter=filter,
+ team=team,
+ )
next_url = paginated_result(request, len(people), filter.offset, filter.limit)
return response.Response({"results": [{"people": people, "count": len(people)}], "next": next_url})
@@ -1338,7 +1364,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
MAX_BATCH_SIZE = 200
distinct_ids = distinct_ids[:MAX_BATCH_SIZE]
- persons_by_distinct_id = get_persons_mapped_by_distinct_id(self.team_id, distinct_ids)
+ with personhog_caller_tag("persons/batch-by-distinct-ids"):
+ persons_by_distinct_id = get_persons_mapped_by_distinct_id(self.team_id, distinct_ids)
# The mapped lookup carries only the matched distinct_id; fetch up to 10
# per person with a bounded follow-up for display, rather than the
@@ -1348,9 +1375,10 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
for person in persons_by_distinct_id.values():
persons_by_id.setdefault(person.id, []).append(person)
if persons_by_id:
- distinct_ids_by_person = get_distinct_ids_for_persons(
- self.team_id, list(persons_by_id.keys()), limit_per_person=10
- )
+ with personhog_caller_tag("persons/batch-by-distinct-ids"):
+ distinct_ids_by_person = get_distinct_ids_for_persons(
+ self.team_id, list(persons_by_id.keys()), limit_per_person=10
+ )
for person_id, persons in persons_by_id.items():
ids = distinct_ids_by_person.get(person_id)
if ids is not None:
@@ -1379,7 +1407,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
raise ValidationError("One or more UUIDs are invalid.")
# MinimalPersonSerializer only renders 10 distinct_ids, so bound the fetch to match.
- persons = get_persons_by_uuids(self.team_id, uuids, distinct_id_limit=10)
+ with personhog_caller_tag("persons/batch-by-uuids"):
+ persons = get_persons_by_uuids(self.team_id, uuids, distinct_id_limit=10)
results: dict[str, Any] = {}
for person in persons:
diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.py
index e8ade90e92bd..0370af59ed60 100644
--- a/posthog/hogql_queries/actor_strategies.py
+++ b/posthog/hogql_queries/actor_strategies.py
@@ -25,6 +25,7 @@ from posthog.models.person.util import (
)
from posthog.models.user import User
from posthog.person_db_router import PERSONS_DB_FOR_READ
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
logger = structlog.get_logger(__name__)
@@ -105,15 +106,16 @@ class PersonStrategy(ActorStrategy):
actor_ids_list = [str(uid) for uid in actor_ids]
team_id = self.team.pk
- all_persons = _batched_get_persons_by_uuids(team_id, actor_ids_list, operation="get_actors")
+ with personhog_caller_tag("persons/hogql-actors"):
+ all_persons = _batched_get_persons_by_uuids(team_id, actor_ids_list, operation="get_actors")
- if sort_by_created_at_descending:
- all_persons.sort(key=lambda p: (-p.created_at, p.uuid))
+ if sort_by_created_at_descending:
+ all_persons.sort(key=lambda p: (-p.created_at, p.uuid))
- person_ids = [p.id for p in all_persons]
- distinct_ids_by_person = _batched_get_distinct_ids_for_persons(
- team_id, person_ids, limit_per_person=limit_per_person
- )
+ person_ids = [p.id for p in all_persons]
+ distinct_ids_by_person = _batched_get_distinct_ids_for_persons(
+ team_id, person_ids, limit_per_person=limit_per_person
+ )
return {
p.uuid: {
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index f73dc0a99538..3efe63c0aba4 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -31,8 +31,9 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_r
from posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprs
from posthog.models import Person, PropertyDefinition
from posthog.models.element import chain_to_elements
-from posthog.models.person.person import get_distinct_ids_for_subquery
+from posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_mapped_by_distinct_id
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import relative_date_parse
from products.actions.backend.models.action import Action, ActionStepJSON
@@ -273,8 +274,10 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
]
where_exprs.append(steps_to_expr(steps, self.team))
if self.query.personId:
- with self.timings.measure("person_id"):
- person: Person | None = get_person_by_pk_or_uuid(self.team.pk, self.query.personId)
+ with self.timings.measure("person_id"), personhog_caller_tag("persons/events-query"):
+ person: Person | None = get_person_by_pk_or_uuid(
+ self.team.pk, self.query.personId, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS
+ )
where_exprs.append(
ast.CompareOperation(
left=ast.Call(name="cityHash64", args=[ast.Field(chain=["distinct_id"])]),
@@ -477,9 +480,10 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
distinct_to_person: dict[str, Person] = {}
batch_size = 1000
- for i in range(0, len(distinct_ids), batch_size):
- batch_distinct_ids = distinct_ids[i : i + batch_size]
- distinct_to_person.update(get_persons_mapped_by_distinct_id(self.team.pk, batch_distinct_ids))
+ with personhog_caller_tag("persons/events-person-column"):
+ for i in range(0, len(distinct_ids), batch_size):
+ batch_distinct_ids = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(get_persons_mapped_by_distinct_id(self.team.pk, batch_distinct_ids))
# Load restricted person properties to strip from the side-channel result
from products.access_control.backend.property_access_control import (
diff --git a/posthog/hogql_queries/sessions_query_runner.py b/posthog/hogql_queries/sessions_query_runner.py
index 7aaa1b201b61..8f4574d14f24 100644
--- a/posthog/hogql_queries/sessions_query_runner.py
+++ b/posthog/hogql_queries/sessions_query_runner.py
@@ -23,9 +23,10 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprs
from posthog.models import Person
-from posthog.models.person.person import get_distinct_ids_for_subquery
+from posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid
from posthog.models.property import Property
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import relative_date_parse
from products.actions.backend.models.action import Action
@@ -322,8 +323,10 @@ class SessionsQueryRunner(AnalyticsQueryRunner[SessionsQueryResponse]):
for property in self.query.fixedProperties
)
if self.query.personId:
- with self.timings.measure("person_id"):
- person: Optional[Person] = get_person_by_pk_or_uuid(self.team.pk, self.query.personId)
+ with self.timings.measure("person_id"), personhog_caller_tag("persons/sessions-query"):
+ person: Optional[Person] = get_person_by_pk_or_uuid(
+ self.team.pk, self.query.personId, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS
+ )
# Qualify distinct_id with sessions. when person join is present to avoid ambiguity
distinct_id_chain: list[str | int] = (
["sessions", "distinct_id"] if self._needs_person_join() else ["distinct_id"]
diff --git a/posthog/models/event/query_event_list.py b/posthog/models/event/query_event_list.py
index a81e0d9e2367..f33d40f5ad52 100644
--- a/posthog/models/event/query_event_list.py
+++ b/posthog/models/event/query_event_list.py
@@ -16,9 +16,10 @@ from posthog.models.event.sql import (
SELECT_EVENT_BY_TEAM_AND_CONDITIONS_FILTERS_SQL,
SELECT_EVENT_BY_TEAM_AND_CONDITIONS_SQL,
)
-from posthog.models.person.person import get_distinct_ids_for_subquery
+from posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid
from posthog.models.property.util import parse_prop_grouped_clauses
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.queries.insight import insight_query_with_columns
from posthog.utils import relative_date_parse
@@ -52,7 +53,8 @@ def parse_request_params(
params.update({"before": v})
elif k == "person_id":
result += """AND distinct_id IN (%(distinct_ids)s) """
- person = get_person_by_pk_or_uuid(team.pk, v)
+ with personhog_caller_tag("persons/event-list"):
+ person = get_person_by_pk_or_uuid(team.pk, v, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS)
params.update({"distinct_ids": get_distinct_ids_for_subquery(person, team)})
elif k == "distinct_id":
result += "AND distinct_id = %(distinct_id)s "
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index 325904862643..a07b3b6d3070 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -22,6 +22,7 @@ from posthog.models.person.util import (
delete_persons_from_postgres,
)
from posthog.models.user import User
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.temporal.common.client import sync_connect
from posthog.temporal.session_replay.delete_recordings.types import DeletionConfig, RecordingsWithPersonInput
@@ -60,10 +61,12 @@ def resolve_persons_for_deletion(
client = get_personhog_client()
if client is not None:
try:
- if uuids:
- return _fetch_persons_by_uuids_via_personhog(team_id, uuids)
- else:
- return _fetch_persons_by_distinct_ids_via_personhog(team_id, cast(builtins.list[str], distinct_ids))
+ # Unbounded distinct_ids: downstream recording deletion needs the full set per person.
+ with personhog_caller_tag("persons/deletion-resolve"):
+ if uuids:
+ return _fetch_persons_by_uuids_via_personhog(team_id, uuids)
+ else:
+ return _fetch_persons_by_distinct_ids_via_personhog(team_id, cast(builtins.list[str], distinct_ids))
except Exception:
logger.warning("resolve_persons_for_deletion_personhog_failure", team_id=team_id, exc_info=True)
diff --git a/posthog/models/person/person.py b/posthog/models/person/person.py
index 64e3a3bad815..acd6e01176e5 100644
--- a/posthog/models/person/person.py
+++ b/posthog/models/person/person.py
@@ -309,6 +309,7 @@ class Person(models.Model):
If ``main_distinct_id`` is also None, the first distinct_id is kept. The
original person always retains its properties.
"""
+ from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.client import get_personhog_client
from posthog.personhog_client.proto import GetPersonRequest
@@ -318,25 +319,28 @@ class Person(models.Model):
"split_person requires personhog, but the client is not configured (PERSONHOG_ADDR is unset)"
)
- person_resp = client.get_person(GetPersonRequest(team_id=self.team_id, person_id=self.pk))
- if not person_resp.person or not person_resp.person.id:
- raise ValueError(f"Person not found: person_id={self.pk}, team_id={self.team_id}")
+ # Tag every personhog call made during the split (get_person, the paged
+ # get_distinct_ids_for_person, and the split_person RPCs) so the traffic is attributable.
+ with personhog_caller_tag("persons/split"):
+ person_resp = client.get_person(GetPersonRequest(team_id=self.team_id, person_id=self.pk))
+ if not person_resp.person or not person_resp.person.id:
+ raise ValueError(f"Person not found: person_id={self.pk}, team_id={self.team_id}")
- logger.info(
- "split_person queried person",
- person_id=self.pk,
- person_uuid=person_resp.person.uuid,
- team_id=self.team_id,
- version=person_resp.person.version,
- main_distinct_id=main_distinct_id,
- max_splits=max_splits,
- explicit_distinct_ids_count=len(distinct_ids_to_split) if distinct_ids_to_split is not None else None,
- )
+ logger.info(
+ "split_person queried person",
+ person_id=self.pk,
+ person_uuid=person_resp.person.uuid,
+ team_id=self.team_id,
+ version=person_resp.person.version,
+ main_distinct_id=main_distinct_id,
+ max_splits=max_splits,
+ explicit_distinct_ids_count=len(distinct_ids_to_split) if distinct_ids_to_split is not None else None,
+ )
- if distinct_ids_to_split is not None:
- self._split_explicit_ids(distinct_ids_to_split)
- else:
- self._split_all_ids(client, main_distinct_id, max_splits)
+ if distinct_ids_to_split is not None:
+ self._split_explicit_ids(distinct_ids_to_split)
+ else:
+ self._split_all_ids(client, main_distinct_id, max_splits)
def _split_explicit_ids(self, distinct_ids_to_split: list[str]) -> None:
"""Partial split: caller specifies exactly which IDs to move.
diff --git a/posthog/models/person/point_in_time_properties.py b/posthog/models/person/point_in_time_properties.py
index 24e78ced7c4e..14e0db4dd691 100644
--- a/posthog/models/person/point_in_time_properties.py
+++ b/posthog/models/person/point_in_time_properties.py
@@ -61,6 +61,9 @@ def get_person_and_distinct_ids_for_identifier(
from posthog.models.person.util import get_person_by_uuid, get_persons_by_distinct_ids
from posthog.personhog_client.caller_tag import personhog_caller_tag
+ # The returned distinct_ids are consumed in full by callers — the point-in-time API echoes them
+ # back with an exact count, and flag evaluation picks a deterministic (lexicographically smallest)
+ # distinct_id — so the fetch is intentionally unbounded here, only tagged for attribution.
if distinct_id is not None:
# Plural lookup: index-friendly __in query that also prefetches distinct_ids_cache,
# which the person.distinct_ids return below relies on. The singular
@@ -70,7 +73,8 @@ def get_person_and_distinct_ids_for_identifier(
person = persons[0] if persons else None
else:
assert person_id is not None
- person = get_person_by_uuid(team_id, person_id)
+ with personhog_caller_tag("persons/point-in-time"):
+ person = get_person_by_uuid(team_id, person_id)
if person is None:
return None, []
diff --git a/posthog/models/person/test/test_util_personhog_routing.py b/posthog/models/person/test/test_util_personhog_routing.py
index 5f41ac59e72c..5806c8ef6cea 100644
--- a/posthog/models/person/test/test_util_personhog_routing.py
+++ b/posthog/models/person/test/test_util_personhog_routing.py
@@ -913,7 +913,7 @@ class TestGetPersonByPkOrUuid(SimpleTestCase):
result = get_person_by_pk_or_uuid(1, "550e8400-e29b-41d4-a716-446655440000")
assert result == mock_person
- mock_get_by_uuid.assert_called_once_with(1, "550e8400-e29b-41d4-a716-446655440000")
+ mock_get_by_uuid.assert_called_once_with(1, "550e8400-e29b-41d4-a716-446655440000", distinct_id_limit=None)
@patch("posthog.models.person.util.get_person_by_id")
def test_routes_int_key_to_get_person_by_id(self, mock_get_by_id):
@@ -923,7 +923,7 @@ class TestGetPersonByPkOrUuid(SimpleTestCase):
result = get_person_by_pk_or_uuid(1, "42")
assert result == mock_person
- mock_get_by_id.assert_called_once_with(1, 42)
+ mock_get_by_id.assert_called_once_with(1, 42, distinct_id_limit=None)
def test_returns_none_for_invalid_key(self):
result = get_person_by_pk_or_uuid(1, "not-a-uuid-or-int")
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index ba1f04d1d91a..35b15f8de0be 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -56,6 +56,7 @@ PERSONHOG_BATCH_SIZE: int = settings.PERSONHOG_BATCH_SIZE
if TYPE_CHECKING:
+ from posthog.personhog_client.client import PersonHogClient
from posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2
@@ -523,7 +524,22 @@ def get_persons_by_uuids(
)
-def _fetch_person_by_id_via_personhog(team_id: int, person_id: int) -> Optional[Person]:
+def _distinct_ids_for_person(client: PersonHogClient, team_id: int, person_id: int, limit: int | None) -> list[str]:
+ # Callers needing only person fields (not distinct_ids) pass distinct_id_limit=0 to skip the
+ # per-person distinct-id fetch, which is otherwise unbounded and pulls thousands of rows for
+ # merge-heavy persons. A positive limit bounds the fetch; None leaves it unbounded.
+ if limit == 0:
+ return []
+ request = GetDistinctIdsForPersonRequest(team_id=team_id, person_id=person_id)
+ if limit is not None:
+ request.limit = limit
+ resp = client.get_distinct_ids_for_person(request)
+ return [d.distinct_id for d in resp.distinct_ids]
+
+
+def _fetch_person_by_id_via_personhog(
+ team_id: int, person_id: int, *, distinct_id_limit: int | None = None
+) -> Optional[Person]:
from posthog.personhog_client.client import get_personhog_client
client = get_personhog_client()
@@ -540,23 +556,22 @@ def _fetch_person_by_id_via_personhog(team_id: int, person_id: int) -> Optional[
logger.warning("personhog_team_mismatch", operation="get_person_by_id", team_id=team_id)
return None
- did_resp = client.get_distinct_ids_for_person(
- GetDistinctIdsForPersonRequest(team_id=team_id, person_id=resp.person.id)
- )
-
- return proto_person_to_model(resp.person, distinct_ids=[d.distinct_id for d in did_resp.distinct_ids])
+ distinct_ids = _distinct_ids_for_person(client, team_id, resp.person.id, distinct_id_limit)
+ return proto_person_to_model(resp.person, distinct_ids=distinct_ids)
-def get_person_by_id(team_id: int, person_id: int) -> Optional[Person]:
+def get_person_by_id(team_id: int, person_id: int, *, distinct_id_limit: int | None = None) -> Optional[Person]:
return _personhog_routed(
"get_person_by_id",
- lambda: _fetch_person_by_id_via_personhog(team_id, person_id),
+ lambda: _fetch_person_by_id_via_personhog(team_id, person_id, distinct_id_limit=distinct_id_limit),
lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(team_id=team_id, pk=person_id).first(),
team_id=team_id,
)
-def _fetch_person_by_uuid_via_personhog(team_id: int, uuid: str) -> Optional[Person]:
+def _fetch_person_by_uuid_via_personhog(
+ team_id: int, uuid: str, *, distinct_id_limit: int | None = None
+) -> Optional[Person]:
from posthog.personhog_client.client import get_personhog_client
client = get_personhog_client()
@@ -573,23 +588,22 @@ def _fetch_person_by_uuid_via_personhog(team_id: int, uuid: str) -> Optional[Per
logger.warning("personhog_team_mismatch", operation="get_person_by_uuid", team_id=team_id)
return None
- did_resp = client.get_distinct_ids_for_person(
- GetDistinctIdsForPersonRequest(team_id=team_id, person_id=resp.person.id)
- )
-
- return proto_person_to_model(resp.person, distinct_ids=[d.distinct_id for d in did_resp.distinct_ids])
+ distinct_ids = _distinct_ids_for_person(client, team_id, resp.person.id, distinct_id_limit)
+ return proto_person_to_model(resp.person, distinct_ids=distinct_ids)
-def get_person_by_uuid(team_id: int, uuid: str) -> Optional[Person]:
+def get_person_by_uuid(team_id: int, uuid: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:
return _personhog_routed(
"get_person_by_uuid",
- lambda: _fetch_person_by_uuid_via_personhog(team_id, uuid),
+ lambda: _fetch_person_by_uuid_via_personhog(team_id, uuid, distinct_id_limit=distinct_id_limit),
lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(team_id=team_id, uuid=uuid).first(),
team_id=team_id,
)
-def _fetch_person_by_distinct_id_via_personhog(team_id: int, distinct_id: str) -> Optional[Person]:
+def _fetch_person_by_distinct_id_via_personhog(
+ team_id: int, distinct_id: str, *, distinct_id_limit: int | None = None
+) -> Optional[Person]:
from posthog.personhog_client.client import get_personhog_client
client = get_personhog_client()
@@ -606,17 +620,16 @@ def _fetch_person_by_distinct_id_via_personhog(team_id: int, distinct_id: str) -
logger.warning("personhog_team_mismatch", operation="get_person_by_distinct_id", team_id=team_id)
return None
- did_resp = client.get_distinct_ids_for_person(
- GetDistinctIdsForPersonRequest(team_id=team_id, person_id=resp.person.id)
- )
-
- return proto_person_to_model(resp.person, distinct_ids=[d.distinct_id for d in did_resp.distinct_ids])
+ distinct_ids = _distinct_ids_for_person(client, team_id, resp.person.id, distinct_id_limit)
+ return proto_person_to_model(resp.person, distinct_ids=distinct_ids)
-def get_person_by_distinct_id(team_id: int, distinct_id: str) -> Optional[Person]:
+def get_person_by_distinct_id(
+ team_id: int, distinct_id: str, *, distinct_id_limit: int | None = None
+) -> Optional[Person]:
return _personhog_routed(
"get_person_by_distinct_id",
- lambda: _fetch_person_by_distinct_id_via_personhog(team_id, distinct_id),
+ lambda: _fetch_person_by_distinct_id_via_personhog(team_id, distinct_id, distinct_id_limit=distinct_id_limit),
lambda: (
Person.objects.db_manager(READ_DB_FOR_PERSONS)
.filter(team_id=team_id, persondistinctid__distinct_id=distinct_id)
@@ -626,14 +639,14 @@ def get_person_by_distinct_id(team_id: int, distinct_id: str) -> Optional[Person
)
-def get_person_by_pk_or_uuid(team_id: int, key: str) -> Optional[Person]:
+def get_person_by_pk_or_uuid(team_id: int, key: str, *, distinct_id_limit: int | None = None) -> Optional[Person]:
"""Look up a person by UUID or integer PK, routing through personhog when enabled."""
try:
UUID(key)
- return get_person_by_uuid(team_id, key)
+ return get_person_by_uuid(team_id, key, distinct_id_limit=distinct_id_limit)
except ValueError:
try:
- return get_person_by_id(team_id, int(key))
+ return get_person_by_id(team_id, int(key), distinct_id_limit=distinct_id_limit)
except ValueError:
return None
diff --git a/posthog/queries/actor_base_query.py b/posthog/queries/actor_base_query.py
index 39f793b0fd47..9de555769f6d 100644
--- a/posthog/queries/actor_base_query.py
+++ b/posthog/queries/actor_base_query.py
@@ -20,6 +20,7 @@ from posthog.models.group import Group
from posthog.models.person import Person
from posthog.models.person.person import READ_DB_FOR_PERSONS
from posthog.models.person.util import _batched_get_distinct_ids_for_persons, _batched_get_persons_by_uuids
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.converters import proto_person_to_model
from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
from posthog.queries.insight import insight_sync_execute
@@ -233,7 +234,8 @@ class ActorBaseQuery:
value_per_actor_id,
)
else:
- actors, serialized_actors = get_people(self._team, actor_ids, value_per_actor_id)
+ with personhog_caller_tag("persons/actor-query"):
+ actors, serialized_actors = get_people(self._team, actor_ids, value_per_actor_id)
if self.ACTOR_VALUES_INCLUDED:
# We fetched actors from Postgres in get_groups/get_people, so `ORDER BY actor_value DESC` no longer holds
diff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.py
index 84d4b7869aa3..d4b2fa068383 100644
--- a/posthog/session_recordings/models/session_recording.py
+++ b/posthog/session_recordings/models/session_recording.py
@@ -22,6 +22,7 @@ logger = structlog.get_logger(__name__)
def _fetch_person_by_distinct_id_via_personhog(team_id: int, distinct_id: str) -> Person | None:
+ from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.client import get_personhog_client
from posthog.personhog_client.converters import proto_person_to_model
from posthog.personhog_client.proto import GetPersonByDistinctIdRequest
@@ -30,7 +31,8 @@ def _fetch_person_by_distinct_id_via_personhog(team_id: int, distinct_id: str) -
if client is None:
raise RuntimeError("personhog client not configured")
- resp = client.get_person_by_distinct_id(GetPersonByDistinctIdRequest(team_id=team_id, distinct_id=distinct_id))
+ with personhog_caller_tag("replay/recording-person"):
+ resp = client.get_person_by_distinct_id(GetPersonByDistinctIdRequest(team_id=team_id, distinct_id=distinct_id))
if resp.person and resp.person.id and resp.person.team_id == team_id:
# Only pass the queried distinct_id — the list endpoint also intentionally
# sets a single distinct_id to avoid expensive all-distinct-ids lookups.
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 4b3c184398bc..2c4662b1d198 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -80,6 +80,7 @@ from posthog.models.comment import Comment
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import hash_key_value
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
@@ -2155,7 +2156,8 @@ def list_recordings_from_query(
with timer("load_persons"), tracer.start_as_current_span("load_persons"):
distinct_ids = sorted([x.distinct_id for x in recordings if x.distinct_id])
- distinct_id_to_person = get_persons_mapped_by_distinct_id(team.pk, distinct_ids)
+ with personhog_caller_tag("replay/recordings-persons"):
+ distinct_id_to_person = get_persons_mapped_by_distinct_id(team.pk, distinct_ids)
with timer("process_persons"), tracer.start_as_current_span("process_persons"):
for recording in recordings:
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index f48e43b9424d..57803e857dd1 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -29,6 +29,7 @@ from posthog.models.person import Person
from posthog.models.person.util import get_person_by_uuid
from posthog.models.property import Property, PropertyGroup
from posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.schema_enums import ProductKey
from posthog.settings.base_variables import TEST
@@ -444,7 +445,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
start_idx = batch_index * batch_size
end_idx = start_idx + batch_size
- return get_person_uuids_by_distinct_ids(team_id, items[start_idx:end_idx])
+ with personhog_caller_tag("cohorts/uuid-batch"):
+ return get_person_uuids_by_distinct_ids(team_id, items[start_idx:end_idx])
batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))
return self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)
@@ -700,7 +702,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
from products.cohorts.backend.models.util import insert_static_cohort
# Cohort membership only needs id/uuid, so skip the unbounded per-person distinct-id fetch.
- persons = get_persons_by_uuids(team_id, batch, distinct_id_limit=0)
+ with personhog_caller_tag("cohorts/static-insert"):
+ persons = get_persons_by_uuids(team_id, batch, distinct_id_limit=0)
if not persons:
return
@@ -762,8 +765,9 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
)
try:
- # Get person by UUID
- person = get_person_by_uuid(team_id, str(user_uuid))
+ # Only person.id/uuid are used (to resolve and remove the row), so skip the distinct-id fetch.
+ with personhog_caller_tag("cohorts/static-remove"):
+ person = get_person_by_uuid(team_id, str(user_uuid), distinct_id_limit=0)
if person is None:
raise Person.DoesNotExist
diff --git a/products/conversations/backend/ai/suggest.py b/products/conversations/backend/ai/suggest.py
index aa70d2a659fb..d91e4e2df61c 100644
--- a/products/conversations/backend/ai/suggest.py
+++ b/products/conversations/backend/ai/suggest.py
@@ -15,6 +15,7 @@ from posthog.hogql_queries.ai.session_batch_events_query_runner import (
)
from posthog.models.comment import Comment
from posthog.models.person.util import get_persons_by_distinct_ids
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from products.conversations.backend.ai.runner import SupportAgentRunner
from products.posthog_ai.backend.models.assistant import Conversation
@@ -212,7 +213,8 @@ MAX_PERSON_PROPERTIES = 30
def _load_person_properties(team: Team, distinct_id: str) -> dict:
try:
# Only properties are read here, so skip the per-person distinct-id fetch entirely.
- persons = get_persons_by_distinct_ids(team_id=team.pk, distinct_ids=[distinct_id], distinct_id_limit=0)
+ with personhog_caller_tag("conversations/suggest-person"):
+ persons = get_persons_by_distinct_ids(team_id=team.pk, distinct_ids=[distinct_id], distinct_id_limit=0)
if persons:
return persons[0].properties or {}
except Exception:
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 4703811a34ab..4c6b2704172c 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -1207,7 +1207,9 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod
person: Person | None = None
if distinct_id != recipient_email:
- person = get_person_by_distinct_id(team.id, distinct_id)
+ # Only person.properties is read for this lookup, so skip the distinct-id fetch.
+ with personhog_caller_tag("conversations/ticket-recipient-lookup"):
+ person = get_person_by_distinct_id(team.id, distinct_id, distinct_id_limit=0)
if person is None:
person = _get_persons_by_email(team, [recipient_email]).get(recipient_email.lower())
diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.py
index bb1f705da75a..d662370c20d2 100644
--- a/products/conversations/backend/events.py
+++ b/products/conversations/backend/events.py
@@ -18,6 +18,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.person.util import get_persons_by_distinct_ids
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.settings import SITE_URL
from products.conversations.backend.cache import get_cached_resolved_groups, set_cached_resolved_groups
@@ -164,7 +165,8 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:
if ticket.distinct_id:
# Only is_identified is read, and the membership lookup below keys off the ticket's own
# distinct_id — so skip fetching the person's distinct_ids.
- persons = get_persons_by_distinct_ids(team.id, [ticket.distinct_id], distinct_id_limit=0)
+ with personhog_caller_tag("conversations/ticket-event-person"):
+ persons = get_persons_by_distinct_ids(team.id, [ticket.distinct_id], distinct_id_limit=0)
if any(p.is_identified for p in persons):
membership = (
OrganizationMembership.objects.select_related("organization")
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index 4ddfc3d42fa6..cb615a767e1d 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -14,6 +14,7 @@ from posthog.models.person import Person
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import generate_cache_key
from products.mcp_analytics.backend import intent_generation
@@ -272,7 +273,8 @@ def _resolve_persons(team_id: int, distinct_ids: list[str]) -> dict[str, Person]
unique_ids = list({distinct_id for distinct_id in distinct_ids if distinct_id})
if not unique_ids:
return {}
- return get_persons_mapped_by_distinct_id(team_id, unique_ids)
+ with personhog_caller_tag("mcp-analytics/persons"):
+ return get_persons_mapped_by_distinct_id(team_id, unique_ids)
def _person_display(person: Person | None) -> dict[str, str]:
diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
index 2054b7ed2bbd..0cad152d34ca 100644
--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py
@@ -13,6 +13,7 @@ from posthog.models.person.util import create_person, create_person_distinct_id,
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.models.utils import uuid7
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from products.mcp_analytics.backend.models import MCPSession
@@ -215,7 +216,10 @@ class Command(BaseCommand):
) -> tuple[str, dict[str, Any]]:
if distinct_id in person_cache:
return person_cache[distinct_id]
- existing_person = get_person_by_distinct_id(team_id=team.id, distinct_id=distinct_id)
+ with personhog_caller_tag("mcp-analytics/seed-sessions"):
+ existing_person = get_person_by_distinct_id(
+ team_id=team.id, distinct_id=distinct_id, distinct_id_limit=0
+ )
if existing_person:
person = existing_person
if properties: