:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(django): bound more person calls, add call sites (#63105)
Zach Brownff6ddf1350bc
diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.pyindex 983a5c7e029f..e8ade90e92bd 100644--- a/posthog/hogql_queries/actor_strategies.py+++ b/posthog/hogql_queries/actor_strategies.py@@ -71,13 +71,18 @@ class PersonStrategy(ActorStrategy):origin = "persons"origin_id = "id"- def get_actors(self, actor_ids, sort_by_created_at_descending: bool = False) -> dict[str, dict]:+ # Default 101 matches the canonical ClickHouse person query (groupArray(101)): consumers read+ # distinct_ids[0] or the display-name scorer, none needs the full set. get_serialized_people+ # overrides with its own distinct_id_limit for the persons-list/export API.+ def get_actors(+ self, actor_ids, sort_by_created_at_descending: bool = False, limit_per_person: int | None = 101+ ) -> dict[str, dict]:from posthog.personhog_client.client import get_personhog_clientclient = get_personhog_client()if client is not None:try:- result = self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending)+ result = self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending, limit_per_person)PERSONHOG_ROUTING_TOTAL.labels(operation="get_actors", source="personhog", client_name=get_client_name()).inc()@@ -95,6 +100,7 @@ class PersonStrategy(ActorStrategy):self,actor_ids,sort_by_created_at_descending: bool,+ limit_per_person: int | None,) -> dict[str, dict]:actor_ids_list = [str(uid) for uid in actor_ids]team_id = self.team.pk@@ -105,7 +111,9 @@ class PersonStrategy(ActorStrategy):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)+ 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/models/person/point_in_time_properties.py b/posthog/models/person/point_in_time_properties.pyindex 81102af4078b..24e78ced7c4e 100644--- a/posthog/models/person/point_in_time_properties.py+++ b/posthog/models/person/point_in_time_properties.py@@ -59,12 +59,14 @@ def get_person_and_distinct_ids_for_identifier(raise ValueError("person_id must be a non-empty value")from posthog.models.person.util import get_person_by_uuid, get_persons_by_distinct_ids+ from posthog.personhog_client.caller_tag import personhog_caller_tagif 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# get_person_by_distinct_id times out on large teams.- persons = get_persons_by_distinct_ids(team_id, [distinct_id])+ with personhog_caller_tag("persons/point-in-time"):+ persons = get_persons_by_distinct_ids(team_id, [distinct_id])person = persons[0] if persons else Noneelse:assert person_id is not Nonediff --git a/posthog/personhog_client/caller_tag.py b/posthog/personhog_client/caller_tag.pynew file mode 100644index 000000000000..5e3a006b464f--- /dev/null+++ b/posthog/personhog_client/caller_tag.py@@ -0,0 +1,22 @@+from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVar++# Ambient caller tag sent as the x-caller-tag gRPC header so the personhog router can attribute+# traffic to the originating call site (it is "unknown" otherwise). Follows the fleet convention+# of "{area}/{operation}", e.g. "conversations/widget-allowed-ids".+_caller_tag: ContextVar[str] = ContextVar("personhog_caller_tag", default="unknown")+++def current_caller_tag() -> str:+ return _caller_tag.get()+++@contextmanager+def personhog_caller_tag(tag: str) -> Iterator[None]:+ """Tag personhog calls made within this block so the router attributes them to ``tag``."""+ token = _caller_tag.set(tag)+ try:+ yield+ finally:+ _caller_tag.reset(token)diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.pyindex d9fa7f7d3719..530ded625aae 100644--- a/posthog/personhog_client/interceptor.py+++ b/posthog/personhog_client/interceptor.py@@ -10,6 +10,7 @@ import grpcimport structlogfrom prometheus_client import Counter, Histogram+from posthog.personhog_client.caller_tag import current_caller_tagfrom posthog.personhog_client.metrics import (PERSONHOG_ERRORS_TOTAL,PERSONHOG_RETRIES_TOTAL,@@ -82,7 +83,10 @@ class ClientNameInterceptor(grpc.UnaryUnaryClientInterceptor):client_call_details: grpc.ClientCallDetails,request: Any,) -> Any:- new_details = _with_metadata(client_call_details, [("x-client-name", self._client_name)])+ new_details = _with_metadata(+ client_call_details,+ [("x-client-name", self._client_name), ("x-caller-tag", current_caller_tag())],+ )return continuation(new_details, request)diff --git a/posthog/queries/actor_base_query.py b/posthog/queries/actor_base_query.pyindex 9cb602642e0c..39f793b0fd47 100644--- a/posthog/queries/actor_base_query.py+++ b/posthog/queries/actor_base_query.py@@ -335,7 +335,7 @@ def get_serialized_people(distinct_id_limit: int | None = 1000,) -> list[SerializedPerson]:persons_dict = PersonStrategy(team, ActorsQuery(), HogQLHasMorePaginator()).get_actors(- people_ids, sort_by_created_at_descending=True+ people_ids, sort_by_created_at_descending=True, limit_per_person=distinct_id_limit)from posthog.api.person import get_person_name_helperdiff --git a/products/conversations/backend/ai/suggest.py b/products/conversations/backend/ai/suggest.pyindex b4609427049c..aa70d2a659fb 100644--- a/products/conversations/backend/ai/suggest.py+++ b/products/conversations/backend/ai/suggest.py@@ -211,7 +211,8 @@ MAX_PERSON_PROPERTIES = 30def _load_person_properties(team: Team, distinct_id: str) -> dict:try:- persons = get_persons_by_distinct_ids(team_id=team.pk, distinct_ids=[distinct_id])+ # 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)if persons:return persons[0].properties or {}except Exception:diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex fa6a64ff8b2e..7508591e6242 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -261,7 +261,7 @@ class TestConversationEvents(BaseTest):if is_empty_distinct_id:mock_get_persons.assert_not_called()else:- mock_get_persons.assert_called_once_with(self.team.id, [ticket.distinct_id])+ mock_get_persons.assert_called_once_with(self.team.id, [ticket.distinct_id], distinct_id_limit=0)call_kwargs = mock_capture.call_args.kwargsassert call_kwargs["process_person_profile"] is expect_groups@@ -341,7 +341,7 @@ class TestConversationEvents(BaseTest):if is_empty_distinct_id:mock_get_persons.assert_not_called()else:- mock_get_persons.assert_called_once_with(self.team.id, [ticket.distinct_id])+ mock_get_persons.assert_called_once_with(self.team.id, [ticket.distinct_id], distinct_id_limit=0)call_kwargs = mock_capture.call_args.kwargsassert call_kwargs["process_person_profile"] is Falsediff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 3a4994a13007..4703811a34ab 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -36,6 +36,7 @@ from posthog.models.comment import Commentfrom posthog.models.person.person import Personfrom posthog.models.person.util import get_person_by_distinct_id, get_persons_by_distinct_idsfrom posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission+from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.rate_limit import (AIBurstRateThrottle,AISustainedRateThrottle,@@ -535,7 +536,8 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif not distinct_ids:return- persons = get_persons_by_distinct_ids(self.team_id, distinct_ids)+ with personhog_caller_tag("conversations/ticket-attach-persons"):+ persons = get_persons_by_distinct_ids(self.team_id, distinct_ids)distinct_id_to_person: dict[str, Person] = {}distinct_ids_set = set(distinct_ids)diff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.pyindex 56ecc0a5a513..bbd6c71532ca 100644--- a/products/conversations/backend/cache.py+++ b/products/conversations/backend/cache.py@@ -10,6 +10,7 @@ from django.core.cache import cacheimport structlogfrom posthog.models.person.util import get_persons_by_distinct_ids+from posthog.personhog_client.caller_tag import personhog_caller_tagfrom products.conversations.backend.models.constants import Status@@ -181,7 +182,8 @@ def get_person_distinct_ids(team_id: int, distinct_id: str) -> list[str]:except Exception:logger.warning("conversations_cache_get_error", key=key)- persons = get_persons_by_distinct_ids(team_id, [distinct_id])+ with personhog_caller_tag("conversations/widget-person-distinct-ids"):+ persons = get_persons_by_distinct_ids(team_id, [distinct_id])all_ids = persons[0].distinct_ids if persons and persons[0].distinct_ids else [distinct_id]try:diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex 4825293b52a3..1b2e82e20a43 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -73,7 +73,9 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:# have no org membership, don't guess via email (a shared email could resolve to a# different person's org), so return early instead of falling through.if ticket.distinct_id:- persons = get_persons_by_distinct_ids(team.id, [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)if any(p.is_identified for p in persons):membership = (OrganizationMembership.objects.select_related("organization")diff --git a/products/conversations/backend/person_lookup.py b/products/conversations/backend/person_lookup.pyindex 30fd83d5ad9d..ae6d3b69d49b 100644--- a/products/conversations/backend/person_lookup.py+++ b/products/conversations/backend/person_lookup.py@@ -7,6 +7,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.person.person import Personfrom posthog.models.person.util import get_persons_by_uuidsfrom posthog.models.team import Team+from posthog.personhog_client.caller_tag import personhog_caller_tag# Case-insensitive batch email lookup. Exposed so tests can EXPLAIN the exact query that runs.PERSON_EMAIL_LOOKUP_QUERY = """@@ -51,7 +52,8 @@ def _get_persons_by_email(if lower not in email_to_uuid:email_to_uuid[lower] = str(person_uuid)- persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))+ with personhog_caller_tag("conversations/email-person-lookup"):+ persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))uuid_to_person: dict[str, Person] = {str(p.uuid): p for p in persons}result: dict[str, Person] = {}