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(django): personhog queries inefficient (#59723)

Nick Best9847c5b8e55b
diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.py
index 0fe0f7afc177..ebea882e0565 100644
--- a/ee/hogai/session_summaries/session_group/patterns.py
+++ b/ee/hogai/session_summaries/session_group/patterns.py
@@ -8,7 +8,7 @@ from pydantic import BaseModel, Field, ValidationError, field_serializer, field_
from temporalio.exceptions import ApplicationError
from posthog.models.person import Person
-from posthog.models.person.util import get_persons_by_distinct_ids
+from posthog.models.person.util import get_persons_mapped_by_distinct_id
from ee.hogai.session_summaries import SummaryValidationError
from ee.hogai.session_summaries.constants import FAILED_PATTERNS_ENRICHMENT_MIN_RATIO
@@ -531,15 +531,14 @@ def get_persons_for_sessions_from_distinct_ids(
# No ids to search for persons - return empty mapping
return {}
try:
- persons = get_persons_by_distinct_ids(team_id=team_id, distinct_ids=distinct_ids)
+ 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 person in persons:
- for distinct_id in person.distinct_ids:
- person_session_ids = distinct_id_to_session_id_mapping.get(distinct_id)
- if not person_session_ids:
- continue
- for person_session_id in person_session_ids:
- session_id_to_person_mapping[person_session_id] = person
+ for distinct_id, person in distinct_to_person.items():
+ person_session_ids = distinct_id_to_session_id_mapping.get(distinct_id)
+ if not person_session_ids:
+ continue
+ for person_session_id in person_session_ids:
+ session_id_to_person_mapping[person_session_id] = person
return session_id_to_person_mapping
except Exception as err:
# As access to persons DB could fail, return empty mapping to avoid failing the activity
diff --git a/posthog/api/event.py b/posthog/api/event.py
index fd5e059722a6..143441a26a1b 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -44,7 +44,7 @@ from posthog.models import Element, Filter, Person, PropertyDefinition, User
from posthog.models.event.query_event_list import query_events_list
from posthog.models.event.sql import SELECT_ONE_EVENT_SQL
from posthog.models.event.util import ClickhouseEventSerializer
-from posthog.models.person.util import get_persons_by_distinct_ids
+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.rate_limit import (
@@ -415,14 +415,9 @@ class EventViewSet(
capture_exception(ex)
raise
- def _get_people(self, query_result: List[dict], team: Team) -> dict[str, Any]: # noqa: UP006
- distinct_ids = [event["distinct_id"] for event in query_result]
- persons = get_persons_by_distinct_ids(team.pk, distinct_ids)
- distinct_to_person: dict[str, Person] = {}
- for person in persons:
- for distinct_id in person.distinct_ids:
- distinct_to_person[distinct_id] = person
- return distinct_to_person
+ 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)
@extend_schema(
parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index 0603173cf0bb..fd7b7779417e 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -99,7 +99,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
# Django session, PostHog user, PostHog team, PostHog org membership,
# instance setting check, person and distinct id
- with self.assertNumQueries(11):
+ with self.assertNumQueries(10):
response = self.client.get(f"/api/projects/{self.team.id}/events/?event=event_name").json()
assert response["results"][0]["event"] == "event_name"
@@ -126,7 +126,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
# Django session, PostHog user, PostHog team, PostHog org membership,
# access control, instance settings (poe, rate limit), person and distinct id
- expected_queries = 12
+ expected_queries = 11
with self.assertNumQueries(expected_queries):
response = self.client.get(
diff --git a/posthog/api/test/test_event_get_people.py b/posthog/api/test/test_event_get_people.py
new file mode 100644
index 000000000000..63d7e1fc9eb2
--- /dev/null
+++ b/posthog/api/test/test_event_get_people.py
@@ -0,0 +1,209 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.api.event import EventViewSet
+from posthog.hogql_queries.events_query_runner import EventsQueryRunner
+
+# ---------------------------------------------------------------------------
+# EventViewSet._get_people
+# ---------------------------------------------------------------------------
+
+
+class TestEventViewSetGetPeople:
+ def _make_viewset(self) -> EventViewSet:
+ viewset = EventViewSet.__new__(EventViewSet)
+ return viewset
+
+ def _make_team(self, pk: int = 1) -> MagicMock:
+ team = MagicMock()
+ team.pk = pk
+ return team
+
+ def _make_person(self, uuid: str = "uuid-1") -> MagicMock:
+ person = MagicMock()
+ person.uuid = uuid
+ person.properties = {}
+ person.distinct_ids = []
+ return person
+
+ @patch("posthog.api.event.get_persons_mapped_by_distinct_id")
+ def test_returns_mapping_from_single_rpc(self, mock_get_persons):
+ viewset = self._make_viewset()
+ team = self._make_team(pk=42)
+ person = self._make_person()
+ mock_get_persons.return_value = {"user-1": person}
+
+ query_result = [{"distinct_id": "user-1"}, {"distinct_id": "user-1"}]
+ result = viewset._get_people(query_result, team)
+
+ assert result == {"user-1": person}
+
+ @patch("posthog.api.event.get_persons_mapped_by_distinct_id")
+ def test_deduplicates_distinct_ids_before_rpc(self, mock_get_persons):
+ viewset = self._make_viewset()
+ team = self._make_team(pk=5)
+ mock_get_persons.return_value = {}
+
+ # 3000 events, only 3 distinct users
+ query_result = [{"distinct_id": f"user-{i % 3}"} for i in range(3000)]
+ viewset._get_people(query_result, team)
+
+ assert mock_get_persons.call_count == 1
+ _team_id, passed_ids = mock_get_persons.call_args.args
+ assert _team_id == 5
+ assert set(passed_ids) == {"user-0", "user-1", "user-2"}
+ assert len(passed_ids) == 3
+
+ @patch("posthog.api.event.get_persons_mapped_by_distinct_id")
+ def test_passes_team_pk_to_rpc(self, mock_get_persons):
+ viewset = self._make_viewset()
+ team = self._make_team(pk=99)
+ mock_get_persons.return_value = {}
+
+ viewset._get_people([{"distinct_id": "x"}], team)
+
+ team_id_used = mock_get_persons.call_args.args[0]
+ assert team_id_used == 99
+
+ @patch("posthog.api.event.get_persons_mapped_by_distinct_id")
+ def test_empty_query_result_returns_empty_dict_without_rpc(self, mock_get_persons):
+ viewset = self._make_viewset()
+ team = self._make_team()
+ mock_get_persons.return_value = {}
+
+ result = viewset._get_people([], team)
+
+ assert result == {}
+ # The RPC is still called — deduplicated empty list is passed through.
+ # This matches the current implementation which always delegates to the helper.
+ assert mock_get_persons.call_count == 1
+ _, passed_ids = mock_get_persons.call_args.args
+ assert passed_ids == []
+
+ @parameterized.expand(
+ [
+ ("single_event", [{"distinct_id": "alice"}], {"alice"}),
+ ("two_distinct_users", [{"distinct_id": "alice"}, {"distinct_id": "bob"}], {"alice", "bob"}),
+ (
+ "many_events_few_users",
+ [{"distinct_id": f"u{i % 5}"} for i in range(100)],
+ {"u0", "u1", "u2", "u3", "u4"},
+ ),
+ ]
+ )
+ @patch("posthog.api.event.get_persons_mapped_by_distinct_id")
+ def test_distinct_id_set_passed_to_rpc(self, _name, query_result, expected_ids, mock_get_persons):
+ mock_get_persons.return_value = {}
+ viewset = self._make_viewset()
+ team = self._make_team()
+
+ viewset._get_people(query_result, team)
+
+ _, passed_ids = mock_get_persons.call_args.args
+ assert set(passed_ids) == expected_ids
+
+
+# ---------------------------------------------------------------------------
+# EventsQueryRunner person enrichment batching
+# ---------------------------------------------------------------------------
+
+
+class TestEventsQueryRunnerPersonBatching:
+ def _make_runner(self, team_pk: int = 1) -> EventsQueryRunner:
+ runner = EventsQueryRunner.__new__(EventsQueryRunner)
+ runner.team = MagicMock()
+ runner.team.pk = team_pk
+ return runner
+
+ def _make_person(self, uuid: str) -> MagicMock:
+ person = MagicMock()
+ person.uuid = uuid
+ return person
+
+ @patch("posthog.hogql_queries.events_query_runner.get_persons_mapped_by_distinct_id")
+ def test_single_batch_when_ids_fit_within_limit(self, mock_get_persons):
+ runner = self._make_runner(team_pk=7)
+ person_a = self._make_person("uuid-a")
+ person_b = self._make_person("uuid-b")
+ mock_get_persons.return_value = {"user-a": person_a, "user-b": person_b}
+
+ distinct_ids = ["user-a", "user-b"]
+ distinct_to_person: dict = {}
+ batch_size = 1000
+ for i in range(0, len(distinct_ids), batch_size):
+ batch = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(mock_get_persons(runner.team.pk, batch))
+
+ assert mock_get_persons.call_count == 1
+ assert distinct_to_person == {"user-a": person_a, "user-b": person_b}
+
+ @patch("posthog.hogql_queries.events_query_runner.get_persons_mapped_by_distinct_id")
+ def test_splits_into_batches_of_1000(self, mock_get_persons):
+ runner = self._make_runner(team_pk=3)
+ # 2500 distinct ids → should produce 3 RPC calls (1000, 1000, 500)
+ distinct_ids = [f"user-{i}" for i in range(2500)]
+ mock_get_persons.side_effect = lambda team_id, batch: {d: self._make_person(d) for d in batch}
+
+ distinct_to_person: dict = {}
+ batch_size = 1000
+ for i in range(0, len(distinct_ids), batch_size):
+ batch = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(mock_get_persons(runner.team.pk, batch))
+
+ assert mock_get_persons.call_count == 3
+ # Each call should have received exactly the right batch size
+ call_args_list = mock_get_persons.call_args_list
+ assert len(call_args_list[0].args[1]) == 1000
+ assert len(call_args_list[1].args[1]) == 1000
+ assert len(call_args_list[2].args[1]) == 500
+
+ @patch("posthog.hogql_queries.events_query_runner.get_persons_mapped_by_distinct_id")
+ def test_merges_results_from_multiple_batches(self, mock_get_persons):
+ runner = self._make_runner(team_pk=4)
+ batch_1_ids = [f"a-{i}" for i in range(1000)]
+ batch_2_ids = [f"b-{i}" for i in range(500)]
+ distinct_ids = batch_1_ids + batch_2_ids
+
+ batch_1_result = {d: self._make_person(d) for d in batch_1_ids}
+ batch_2_result = {d: self._make_person(d) for d in batch_2_ids}
+ mock_get_persons.side_effect = [batch_1_result, batch_2_result]
+
+ distinct_to_person: dict = {}
+ batch_size = 1000
+ for i in range(0, len(distinct_ids), batch_size):
+ batch = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(mock_get_persons(runner.team.pk, batch))
+
+ assert set(distinct_to_person.keys()) == set(batch_1_ids + batch_2_ids)
+ assert len(distinct_to_person) == 1500
+
+ @patch("posthog.hogql_queries.events_query_runner.get_persons_mapped_by_distinct_id")
+ def test_exact_batch_boundary_produces_correct_call_count(self, mock_get_persons):
+ runner = self._make_runner()
+ # Exactly 2000 ids → 2 calls of 1000 each
+ distinct_ids = [f"user-{i}" for i in range(2000)]
+ mock_get_persons.side_effect = lambda team_id, batch: {d: self._make_person(d) for d in batch}
+
+ distinct_to_person: dict = {}
+ batch_size = 1000
+ for i in range(0, len(distinct_ids), batch_size):
+ batch = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(mock_get_persons(runner.team.pk, batch))
+
+ assert mock_get_persons.call_count == 2
+ for c in mock_get_persons.call_args_list:
+ assert len(c.args[1]) == 1000
+
+ @patch("posthog.hogql_queries.events_query_runner.get_persons_mapped_by_distinct_id")
+ def test_empty_distinct_ids_calls_no_rpc(self, mock_get_persons):
+ runner = self._make_runner()
+ distinct_ids: list = []
+ distinct_to_person: dict = {}
+ batch_size = 1000
+ for i in range(0, len(distinct_ids), batch_size):
+ batch = distinct_ids[i : i + batch_size]
+ distinct_to_person.update(mock_get_persons(runner.team.pk, batch))
+
+ assert mock_get_persons.call_count == 0
+ assert distinct_to_person == {}
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index df522a13f5f5..ac1b4cb476bb 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -30,7 +30,7 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_r
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.util import get_person_by_pk_or_uuid, get_persons_by_distinct_ids
+from posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_mapped_by_distinct_id
from posthog.utils import relative_date_parse
from products.actions.backend.models.action import Action, ActionStepJSON
@@ -478,17 +478,10 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
distinct_ids = list({event[person_idx] for event in self.paginator.results})
distinct_to_person: dict[str, Person] = {}
- # Process distinct_ids in batches to avoid overwhelming PostgreSQL
batch_size = 1000
for i in range(0, len(distinct_ids), batch_size):
batch_distinct_ids = distinct_ids[i : i + batch_size]
- requested_batch = set(batch_distinct_ids)
- persons = get_persons_by_distinct_ids(self.team.pk, batch_distinct_ids)
- for person in persons:
- if person:
- for person_distinct_id in person.distinct_ids:
- if person_distinct_id in requested_batch:
- distinct_to_person[person_distinct_id] = person
+ 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/temporal/tests/session_replay/session_summary_group/test_workflow.py b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
index f14fbf588fd0..1ddce845d3b4 100644
--- a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
+++ b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
@@ -1878,6 +1878,133 @@ async def test_combine_patterns_from_chunks_activity_fails_when_no_chunks(
await combine_patterns_from_chunks_activity(inputs)
+def test_get_persons_for_sessions_from_distinct_ids_maps_session_to_person():
+ from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
+ from ee.models.session_summaries import SingleSessionSummary
+
+ person = MagicMock()
+ person.uuid = "person-uuid-1"
+
+ summary = MagicMock(spec=SingleSessionSummary)
+ summary.distinct_id = "distinct-1"
+
+ mapping: dict[str, SingleSessionSummary] = {"session-1": summary}
+ with patch(
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
+ return_value={"distinct-1": person},
+ ):
+ result = get_persons_for_sessions_from_distinct_ids(
+ session_id_to_ready_summaries_mapping=mapping,
+ team_id=1,
+ )
+
+ assert result == {"session-1": person}
+
+
+def test_get_persons_for_sessions_from_distinct_ids_handles_multiple_sessions_same_distinct_id():
+ from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
+ from ee.models.session_summaries import SingleSessionSummary
+
+ person = MagicMock()
+ person.uuid = "person-uuid-shared"
+
+ summary_a = MagicMock(spec=SingleSessionSummary)
+ summary_a.distinct_id = "shared-distinct-id"
+ summary_b = MagicMock(spec=SingleSessionSummary)
+ summary_b.distinct_id = "shared-distinct-id"
+
+ mapping: dict[str, SingleSessionSummary] = {"session-a": summary_a, "session-b": summary_b}
+ with patch(
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
+ return_value={"shared-distinct-id": person},
+ ):
+ result = get_persons_for_sessions_from_distinct_ids(
+ session_id_to_ready_summaries_mapping=mapping,
+ team_id=1,
+ )
+
+ assert result == {"session-a": person, "session-b": person}
+
+
+def test_get_persons_for_sessions_from_distinct_ids_excludes_sessions_with_no_distinct_id():
+ from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
+ from ee.models.session_summaries import SingleSessionSummary
+
+ person = MagicMock()
+ person.uuid = "person-uuid-1"
+
+ summary_with_id = MagicMock(spec=SingleSessionSummary)
+ summary_with_id.distinct_id = "distinct-1"
+ summary_no_id = MagicMock(spec=SingleSessionSummary)
+ summary_no_id.distinct_id = None
+
+ mapping: dict[str, SingleSessionSummary] = {
+ "session-with-id": summary_with_id,
+ "session-no-id": summary_no_id,
+ }
+ with patch(
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
+ return_value={"distinct-1": person},
+ ) as mock_rpc:
+ result = get_persons_for_sessions_from_distinct_ids(
+ session_id_to_ready_summaries_mapping=mapping,
+ team_id=1,
+ )
+
+ # Session with no distinct_id is omitted from result and from RPC call
+ assert "session-no-id" not in result
+ assert result == {"session-with-id": person}
+ passed_ids = mock_rpc.call_args.kwargs["distinct_ids"]
+ assert "distinct-1" in passed_ids
+ assert len(passed_ids) == 1
+
+
+def test_get_persons_for_sessions_from_distinct_ids_returns_empty_when_all_sessions_lack_distinct_id():
+ from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
+ from ee.models.session_summaries import SingleSessionSummary
+
+ summary = MagicMock(spec=SingleSessionSummary)
+ summary.distinct_id = None
+
+ mapping: dict[str, SingleSessionSummary] = {"session-1": summary}
+ with patch(
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
+ ) as mock_rpc:
+ result = get_persons_for_sessions_from_distinct_ids(
+ session_id_to_ready_summaries_mapping=mapping,
+ team_id=1,
+ )
+
+ assert result == {}
+ mock_rpc.assert_not_called()
+
+
+def test_get_persons_for_sessions_from_distinct_ids_deduplicates_distinct_ids_sent_to_rpc():
+ from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
+ from ee.models.session_summaries import SingleSessionSummary
+
+ person = MagicMock()
+ summaries: dict[str, SingleSessionSummary] = {}
+ for i in range(5):
+ s = MagicMock(spec=SingleSessionSummary)
+ s.distinct_id = "same-id"
+ summaries[f"session-{i}"] = s
+
+ with patch(
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
+ return_value={"same-id": person},
+ ) as mock_rpc:
+ result = get_persons_for_sessions_from_distinct_ids(
+ session_id_to_ready_summaries_mapping=summaries,
+ team_id=1,
+ )
+
+ assert mock_rpc.call_count == 1
+ passed_ids = mock_rpc.call_args.kwargs["distinct_ids"]
+ assert passed_ids == ["same-id"]
+ assert len(result) == 5
+
+
def test_get_persons_for_sessions_from_distinct_ids_handles_db_failure():
"""Test that get_persons_for_sessions_from_distinct_ids returns empty dict on DB failure."""
from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids
@@ -1887,7 +2014,7 @@ def test_get_persons_for_sessions_from_distinct_ids_handles_db_failure():
mock_summary.distinct_id = "test-distinct-id"
session_id_to_summaries: dict[str, SingleSessionSummary] = {"session-1": mock_summary}
with patch(
- "ee.hogai.session_summaries.session_group.patterns.get_persons_by_distinct_ids",
+ "ee.hogai.session_summaries.session_group.patterns.get_persons_mapped_by_distinct_id",
side_effect=Exception('relation "posthog_person" does not exist'),
):
result = get_persons_for_sessions_from_distinct_ids(