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): better some person calls (#62805)

Zach Browncbc9ea04864a
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 866358da13aa..dfd27be7605e 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -60,7 +60,12 @@ from posthog.models.person.bulk_delete import (
from posthog.models.person.deletion import reset_deleted_person_distinct_ids
from posthog.models.person.missing_person import MissingPerson
from posthog.models.person.person import PersonDistinctId
-from posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_by_distinct_ids, get_persons_by_uuids
+from posthog.models.person.util import (
+ get_distinct_ids_for_persons,
+ get_person_by_pk_or_uuid,
+ get_persons_by_uuids,
+ get_persons_mapped_by_distinct_id,
+)
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
@@ -1350,17 +1355,29 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
MAX_BATCH_SIZE = 200
distinct_ids = distinct_ids[:MAX_BATCH_SIZE]
- persons = get_persons_by_distinct_ids(self.team_id, distinct_ids)
-
- requested = set(distinct_ids)
- results: dict[str, Any] = {}
- for person in persons:
- person_data = MinimalPersonSerializer(person, context={"get_team": lambda: self.team}).data
-
- for distinct_id in person.distinct_ids:
- if distinct_id in requested:
- results[distinct_id] = person_data
-
+ 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
+ # unbounded fetch get_persons_by_distinct_ids would do. A person may appear
+ # under several requested ids, so update every copy.
+ persons_by_id: dict[int, list[Person]] = {}
+ 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
+ )
+ for person_id, persons in persons_by_id.items():
+ ids = distinct_ids_by_person.get(person_id)
+ if ids is not None:
+ for person in persons:
+ person._distinct_ids = ids
+
+ results: dict[str, Any] = {
+ distinct_id: MinimalPersonSerializer(person, context={"get_team": lambda: self.team}).data
+ for distinct_id, person in persons_by_distinct_id.items()
+ }
return response.Response({"results": results})
@action(methods=["POST"], detail=False, url_path="batch_by_uuids")
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 20c5a24cca40..13038a98efb6 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -1877,6 +1877,26 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(results["user_1"]["properties"]["email"], "[email protected]")
self.assertEqual(results["user_2"]["properties"]["email"], "[email protected]")
+ def test_batch_by_distinct_ids_caps_distinct_ids_at_ten(self) -> None:
+ _create_person(
+ team=self.team,
+ distinct_ids=[f"id_{i}" for i in range(12)],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ flush_persons_and_events()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/persons/batch_by_distinct_ids/",
+ {"distinct_ids": ["id_0"]},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertIn("id_0", results)
+ self.assertLessEqual(len(results["id_0"]["distinct_ids"]), 10)
+
def test_batch_by_distinct_ids_missing_ids(self) -> None:
_create_person(
team=self.team,
diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.py
index 435ed610c8e9..ed1c69436613 100644
--- a/posthog/models/group/test_util.py
+++ b/posthog/models/group/test_util.py
@@ -3,7 +3,7 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.db import DatabaseError
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
@@ -168,6 +168,31 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):
self.team_id = 10
self.group_type_index = 0
+ @override_settings(PERSONHOG_BATCH_SIZE=2)
+ @patch(_ROUTING_ERRORS_PATCH)
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CONVERTER_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_chunks_requests(self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter):
+ # 5 keys with batch size 2 → 3 chunks (2 + 2 + 1)
+ protos = [_make_proto_group(id=i + 1, team_id=self.team_id, group_key=f"k{i}") for i in range(5)]
+ mock_client = MagicMock()
+ mock_client.get_groups.side_effect = [
+ MagicMock(groups=protos[0:2]),
+ MagicMock(groups=protos[2:4]),
+ MagicMock(groups=protos[4:5]),
+ ]
+ mock_get_client.return_value = mock_client
+ models = [MagicMock() for _ in range(5)]
+ mock_convert.side_effect = models
+
+ result = get_groups_by_identifiers(self.team_id, self.group_type_index, [f"k{i}" for i in range(5)])
+
+ assert result == models
+ assert mock_client.get_groups.call_count == 3
+ for call in mock_client.get_groups.call_args_list:
+ assert len(call[0][0].group_identifiers) <= 2
+
def test_empty_group_keys_returns_empty_list_without_personhog(self):
with patch(_CLIENT_PATCH) as mock_get_client:
result = get_groups_by_identifiers(self.team_id, self.group_type_index, [])
@@ -420,6 +445,27 @@ class TestGetGroupsByTypeIndices(SimpleTestCase):
def setUp(self):
self.team_id = 10
+ @override_settings(PERSONHOG_BATCH_SIZE=2)
+ @patch(_ROUTING_ERRORS_PATCH)
+ @patch(_ROUTING_TOTAL_PATCH)
+ @patch(_CONVERTER_PATCH)
+ @patch(_CLIENT_PATCH)
+ def test_personhog_chunks_cross_product(
+ self, mock_get_client, mock_convert, mock_routing_counter, mock_errors_counter
+ ):
+ # {0, 1} x {k1, k2, k3} = 6 identifiers; batch size 2 → 3 chunks
+ mock_client = MagicMock()
+ mock_client.get_groups.side_effect = [MagicMock(groups=[]) for _ in range(3)]
+ mock_get_client.return_value = mock_client
+
+ get_groups_by_type_indices(self.team_id, {0, 1}, {"k1", "k2", "k3"})
+
+ assert mock_client.get_groups.call_count == 3
+ total = sum(len(c[0][0].group_identifiers) for c in mock_client.get_groups.call_args_list)
+ assert total == 6
+ for c in mock_client.get_groups.call_args_list:
+ assert len(c[0][0].group_identifiers) <= 2
+
def test_empty_group_type_indices_returns_empty_list(self):
result = get_groups_by_type_indices(self.team_id, set(), {"k1"})
assert result == []
diff --git a/posthog/models/group/util.py b/posthog/models/group/util.py
index 2ef39e8ad02e..c7ce63d5b218 100644
--- a/posthog/models/group/util.py
+++ b/posthog/models/group/util.py
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from typing import Optional, Union
from zoneinfo import ZoneInfo
+from django.conf import settings
from django.db import DatabaseError
from django.db.models import Q
from django.utils.timezone import now
@@ -233,12 +234,18 @@ def get_groups_by_identifiers(team_id: int, group_type_index: int, group_keys: l
client = get_personhog_client()
if client is not None:
try:
- identifiers = [GroupIdentifier(group_type_index=group_type_index, group_key=key) for key in group_keys]
- resp = client.get_groups(GetGroupsRequest(team_id=team_id, group_identifiers=identifiers))
+ groups: list[Group] = []
+ for i in range(0, len(group_keys), settings.PERSONHOG_BATCH_SIZE):
+ identifiers = [
+ GroupIdentifier(group_type_index=group_type_index, group_key=key)
+ for key in group_keys[i : i + settings.PERSONHOG_BATCH_SIZE]
+ ]
+ resp = client.get_groups(GetGroupsRequest(team_id=team_id, group_identifiers=identifiers))
+ groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)
PERSONHOG_ROUTING_TOTAL.labels(
operation="get_groups_by_identifiers", source="personhog", client_name=get_client_name()
).inc()
- return [proto_group_to_model(g) for g in resp.groups if g.id]
+ return groups
except Exception:
PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
operation="get_groups_by_identifiers",
@@ -290,11 +297,18 @@ def get_groups_by_type_indices(team_id: int, group_type_indices: set[int], group
identifiers = [
GroupIdentifier(group_type_index=gti, group_key=key) for gti in group_type_indices for key in group_keys
]
- resp = client.get_groups(GetGroupsRequest(team_id=team_id, group_identifiers=identifiers))
+ groups: list[Group] = []
+ for i in range(0, len(identifiers), settings.PERSONHOG_BATCH_SIZE):
+ resp = client.get_groups(
+ GetGroupsRequest(
+ team_id=team_id, group_identifiers=identifiers[i : i + settings.PERSONHOG_BATCH_SIZE]
+ )
+ )
+ groups.extend(proto_group_to_model(g) for g in resp.groups if g.id)
PERSONHOG_ROUTING_TOTAL.labels(
operation="get_groups_by_type_indices", source="personhog", client_name=get_client_name()
).inc()
- return [proto_group_to_model(g) for g in resp.groups if g.id]
+ return groups
except Exception:
PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
operation="get_groups_by_type_indices",
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index eb8fac9e0047..eccdcf95d76a 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -8,6 +8,7 @@ if TYPE_CHECKING:
from posthog.models.team.team import Team
from posthog.personhog_client.client import PersonHogClient
+from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.db import DatabaseError, models
from django.db.models import Count
@@ -290,14 +291,15 @@ def _fetch_group_types_for_projects_via_personhog(
from posthog.personhog_client.converters import proto_group_type_mapping_to_dict
from posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdsRequest
- resp = client.get_group_type_mappings_by_project_ids(
- GetGroupTypeMappingsByProjectIdsRequest(project_ids=project_ids)
- )
result: dict[int, list[dict[str, Any]]] = {}
- for batch in resp.results:
- mappings = [proto_group_type_mapping_to_dict(m) for m in batch.mappings]
- mappings.sort(key=lambda d: d["group_type_index"])
- result[batch.key] = mappings
+ for i in range(0, len(project_ids), settings.PERSONHOG_BATCH_SIZE):
+ resp = client.get_group_type_mappings_by_project_ids(
+ GetGroupTypeMappingsByProjectIdsRequest(project_ids=project_ids[i : i + settings.PERSONHOG_BATCH_SIZE])
+ )
+ for batch in resp.results:
+ mappings = [proto_group_type_mapping_to_dict(m) for m in batch.mappings]
+ mappings.sort(key=lambda d: d["group_type_index"])
+ result[batch.key] = mappings
return result
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 506476c1fadc..1bb098fcd0a0 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -450,6 +450,40 @@ def get_persons_mapped_by_distinct_id(
)
+def get_distinct_ids_for_persons(
+ team_id: int,
+ person_ids: list[int],
+ *,
+ limit_per_person: int | None = None,
+) -> dict[int, list[str]]:
+ """Map each person_id to its distinct_ids via personhog, falling back to ORM.
+
+ With ``limit_per_person`` set, at most that many distinct_ids are returned per
+ person — bounding the fetch for merge-heavy persons whose full set can be huge.
+ """
+ if not person_ids:
+ return {}
+
+ def orm_fn() -> dict[int, list[str]]:
+ result: dict[int, list[str]] = {}
+ for person_id, distinct_id in (
+ PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS)
+ .filter(team_id=team_id, person_id__in=person_ids)
+ .values_list("person_id", "distinct_id")
+ ):
+ ids = result.setdefault(person_id, [])
+ if limit_per_person is None or len(ids) < limit_per_person:
+ ids.append(distinct_id)
+ return result
+
+ return _personhog_routed(
+ "get_distinct_ids_for_persons",
+ lambda: _batched_get_distinct_ids_for_persons(team_id, person_ids, limit_per_person=limit_per_person),
+ orm_fn,
+ team_id=team_id,
+ )
+
+
def _fetch_persons_by_uuids_via_personhog(team_id: int, uuids: list[str]) -> list[Person]:
valid_persons = _batched_get_persons_by_uuids(team_id, uuids, "get_persons_by_uuids")
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index 7344d93c77cc..f8a7ee182734 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -1,6 +1,6 @@
from unittest.mock import MagicMock, patch
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
@@ -9,6 +9,7 @@ from posthog.models.group_type_mapping import (
GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX,
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
GroupTypesUnavailable,
+ _fetch_group_types_for_projects_via_personhog,
_record_group_types_fetch_failure,
clear_dashboard_from_group_type_mapping,
count_group_type_mappings_per_team,
@@ -319,6 +320,23 @@ class TestGetGroupTypesForProjectsRouting(SimpleTestCase):
def tearDown(self):
self._client_patcher.stop()
+ @override_settings(PERSONHOG_BATCH_SIZE=2)
+ def test_fetch_via_personhog_chunks_project_ids(self):
+ # 5 project_ids with batch size 2 → 3 chunks (2 + 2 + 1)
+ mock_client = MagicMock()
+ mock_client.get_group_type_mappings_by_project_ids.side_effect = [
+ MagicMock(results=[MagicMock(key=1, mappings=[]), MagicMock(key=2, mappings=[])]),
+ MagicMock(results=[MagicMock(key=3, mappings=[]), MagicMock(key=4, mappings=[])]),
+ MagicMock(results=[MagicMock(key=5, mappings=[])]),
+ ]
+
+ result = _fetch_group_types_for_projects_via_personhog(mock_client, [1, 2, 3, 4, 5])
+
+ assert mock_client.get_group_type_mappings_by_project_ids.call_count == 3
+ assert set(result.keys()) == {1, 2, 3, 4, 5}
+ for c in mock_client.get_group_type_mappings_by_project_ids.call_args_list:
+ assert len(c[0][0].project_ids) <= 2
+
@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")
@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")
@patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")