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): move person api to personhog (#57854)

Nick Bestf010aae17158
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 89706dfb5f28..23dede24db24 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -5,7 +5,6 @@ from datetime import UTC, datetime
from typing import Any, List, Optional, TypeVar, Union, cast # noqa: UP035
from django.db.models import Prefetch
-from django.shortcuts import get_object_or_404
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -39,7 +38,7 @@ from posthog.api.documentation import PersonPropertiesSerializer
from posthog.api.insight import capture_legacy_api_call
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.utils import action, format_paginated_url, get_pk_or_uuid, get_target_entity
+from posthog.api.utils import action, format_paginated_url, get_target_entity
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.constants import INSIGHT_FUNNELS, LIMIT, OFFSET, FunnelVizType
@@ -446,12 +445,16 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
person_id = self.kwargs[self.lookup_field]
try:
- queryset = get_pk_or_uuid(queryset, person_id)
+ uuid.UUID(str(person_id))
except ValueError:
- raise ValidationError(
- 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_object_or_404(queryset)
+ try:
+ int(person_id)
+ except (ValueError, TypeError):
+ raise ValidationError(
+ 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))
@extend_schema(
parameters=[
@@ -935,8 +938,10 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=400,
)
- person = get_pk_or_uuid(self.get_queryset(), request.GET["person_id"]).get()
- cohort_ids = get_all_cohort_ids_by_person_uuid(person.uuid, team.pk)
+ person = get_person_by_pk_or_uuid(self.team_id, request.GET["person_id"])
+ if person is None:
+ raise NotFound()
+ cohort_ids = get_all_cohort_ids_by_person_uuid(str(person.uuid), team.pk)
# nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get (IDs from team-scoped ClickHouse query)
cohorts = Cohort.objects.filter(pk__in=cohort_ids, deleted=False)
diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.py
index ee1d8fa81c88..df6e8c7be1bd 100644
--- a/posthog/api/test/test_person_personhog.py
+++ b/posthog/api/test/test_person_personhog.py
@@ -1,8 +1,9 @@
"""Tests that person API endpoints produce identical results
via the ORM and personhog paths.
-Covers delete_property, batch_by_distinct_ids, and person deletion — extracted
-from test_person.py so both code paths are validated with @parameterized_class.
+Covers retrieve, update, split, delete_property, batch_by_distinct_ids, and
+person deletion — extracted from test_person.py so both code paths are
+validated with @parameterized_class.
"""
from posthog.test.base import APIBaseTest
@@ -11,13 +12,174 @@ from unittest import mock
from parameterized import parameterized_class
from rest_framework import status
-from posthog.models import Organization, Person, Team
+from posthog.models import Cohort, Organization, Person, Team
from posthog.models.person import PersonDistinctId
from posthog.personhog_client.test_helpers import PersonhogTestMixin
UUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"
+@parameterized_class(("personhog",), [(False,), (True,)])
+class TestRetrievePerson(PersonhogTestMixin, APIBaseTest):
+ def test_retrieve_by_uuid(self):
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1", "did-2"],
+ properties={"email": "[email protected]"},
+ )
+
+ resp = self.client.get(f"/api/person/{person.uuid}/")
+
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["uuid"] == str(person.uuid)
+ assert data["properties"]["email"] == "[email protected]"
+ assert set(data["distinct_ids"]) == {"did-1", "did-2"}
+ self._assert_personhog_called("get_person_by_uuid")
+
+ def test_retrieve_by_pk(self):
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1"],
+ properties={"name": "Test User"},
+ )
+
+ resp = self.client.get(f"/api/person/{person.pk}/")
+
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["uuid"] == str(person.uuid)
+ assert data["properties"]["name"] == "Test User"
+ self._assert_personhog_not_called("get_person_by_uuid")
+ self._assert_personhog_called("get_person")
+
+ def test_retrieve_nonexistent_returns_404(self):
+ resp = self.client.get(f"/api/person/{UUID_NONEXISTENT}/")
+
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_retrieve_invalid_id_returns_validation_error(self):
+ resp = self.client.get("/api/person/not-a-valid-id/")
+
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "does not look like a personID" in resp.json().get("detail", "")
+
+ def test_retrieve_cross_team_isolation(self):
+ other_org, _, _ = Organization.objects.bootstrap(None, name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ other_person = self._seed_person(team=other_team, distinct_ids=["other-did"])
+
+ resp = self.client.get(f"/api/person/{other_person.uuid}/")
+
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+
+@parameterized_class(("personhog",), [(False,), (True,)])
+class TestUpdatePerson(PersonhogTestMixin, APIBaseTest):
+ @mock.patch("posthog.api.person.capture_internal")
+ def test_update_properties_by_uuid(self, mock_capture):
+ mock_capture.return_value = mock.MagicMock(status_code=200)
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1"],
+ properties={"existing": "value"},
+ )
+
+ resp = self.client.patch(
+ f"/api/person/{person.uuid}/",
+ {"properties": {"new_key": "new_value"}},
+ format="json",
+ )
+
+ assert resp.status_code == status.HTTP_202_ACCEPTED
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args[1]
+ assert call_kwargs["distinct_id"] == "did-1"
+ assert call_kwargs["properties"] == {"$set": {"new_key": "new_value"}}
+ self._assert_personhog_called("get_person_by_uuid")
+
+ @mock.patch("posthog.api.person.capture_internal")
+ def test_update_properties_by_pk(self, mock_capture):
+ mock_capture.return_value = mock.MagicMock(status_code=200)
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1"],
+ properties={},
+ )
+
+ resp = self.client.patch(
+ f"/api/person/{person.pk}/",
+ {"properties": {"key": "val"}},
+ format="json",
+ )
+
+ assert resp.status_code == status.HTTP_202_ACCEPTED
+ self._assert_personhog_not_called("get_person_by_uuid")
+ self._assert_personhog_called("get_person")
+
+
+@parameterized_class(("personhog",), [(False,), (True,)])
+class TestSplitPerson(PersonhogTestMixin, APIBaseTest):
+ @mock.patch("posthog.api.person.split_person")
+ def test_split_by_uuid(self, mock_split):
+ mock_split.delay = mock.MagicMock()
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1", "did-2", "did-3"],
+ )
+
+ resp = self.client.post(f"/api/person/{person.uuid}/split/")
+
+ assert resp.status_code == status.HTTP_201_CREATED
+ assert resp.json() == {"success": True}
+ mock_split.delay.assert_called_once_with(
+ person.pk,
+ self.team.pk,
+ None,
+ None,
+ distinct_ids_to_split=None,
+ )
+ self._assert_personhog_called("get_person_by_uuid")
+
+ @mock.patch("posthog.api.person.split_person")
+ def test_split_nonexistent_returns_404(self, mock_split):
+ resp = self.client.post(f"/api/person/{UUID_NONEXISTENT}/split/")
+
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+ mock_split.delay.assert_not_called()
+
+
+@parameterized_class(("personhog",), [(False,), (True,)])
+class TestCohortsByPerson(PersonhogTestMixin, APIBaseTest):
+ def test_cohorts_by_uuid(self):
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1"],
+ )
+ cohort = Cohort.objects.create(team=self.team, name="Test Cohort")
+
+ with mock.patch(
+ "posthog.api.person.get_all_cohort_ids_by_person_uuid",
+ return_value=[cohort.pk],
+ ):
+ resp = self.client.get(f"/api/person/cohorts/?person_id={person.uuid}")
+
+ assert resp.status_code == status.HTTP_200_OK
+ results = resp.json()["results"]
+ assert len(results) == 1
+ assert results[0]["name"] == "Test Cohort"
+ self._assert_personhog_called("get_person_by_uuid")
+
+ def test_cohorts_nonexistent_person_returns_404(self):
+ with mock.patch(
+ "posthog.api.person.get_all_cohort_ids_by_person_uuid",
+ return_value=[],
+ ):
+ resp = self.client.get(f"/api/person/cohorts/?person_id={UUID_NONEXISTENT}")
+
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+
@parameterized_class(("personhog",), [(False,), (True,)])
class TestDeleteProperty(PersonhogTestMixin, APIBaseTest):
@mock.patch("posthog.api.person.capture_internal")
diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.py
index c07dc96a3273..5f67b1635a89 100644
--- a/posthog/hogql_queries/actor_strategies.py
+++ b/posthog/hogql_queries/actor_strategies.py
@@ -1,8 +1,11 @@
-from typing import Literal, Optional, cast
+import uuid as uuid_mod
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Literal, Optional, cast
from django.db import connections
import orjson as json
+import structlog
from posthog.schema import ActorsQuery, InsightActorsQuery, TrendsQuery
@@ -16,6 +19,18 @@ from posthog.hogql_queries.utils.recordings_helper import RecordingsHelper
from posthog.models import Team
from posthog.models.person import Person, PersonDistinctId
from posthog.person_db_router import PERSONS_DB_FOR_READ
+from posthog.personhog_client.metrics import (
+ PERSONHOG_ROUTING_ERRORS_TOTAL,
+ PERSONHOG_ROUTING_TOTAL,
+ PERSONHOG_TEAM_MISMATCH_TOTAL,
+ get_client_name,
+)
+from posthog.personhog_client.proto import GetDistinctIdsForPersonsRequest, GetPersonsByUuidsRequest
+
+if TYPE_CHECKING:
+ from posthog.personhog_client.client import PersonHogClient
+
+logger = structlog.get_logger(__name__)
# Use centralized database routing constant
READ_DB_FOR_PERSONS = PERSONS_DB_FOR_READ
@@ -55,8 +70,83 @@ class PersonStrategy(ActorStrategy):
# batching is needed to prevent timeouts when reading from Postgres
BATCH_SIZE = 1000
- # This is hand written instead of using the ORM because the ORM was blowing up the memory on exports and taking forever
def get_actors(self, actor_ids, sort_by_created_at_descending: bool = False) -> dict[str, dict]:
+ from posthog.personhog_client.client import get_personhog_client
+
+ client = get_personhog_client()
+ if client is not None:
+ try:
+ result = self._get_actors_via_personhog(client, actor_ids, sort_by_created_at_descending)
+ PERSONHOG_ROUTING_TOTAL.labels(
+ operation="get_actors", source="personhog", client_name=get_client_name()
+ ).inc()
+ return result
+ except Exception:
+ PERSONHOG_ROUTING_ERRORS_TOTAL.labels(
+ operation="get_actors", source="personhog", error_type="grpc_error", client_name=get_client_name()
+ ).inc()
+ logger.warning("personhog_get_actors_failure", team_id=self.team.pk, exc_info=True)
+
+ PERSONHOG_ROUTING_TOTAL.labels(operation="get_actors", source="raw_sql", client_name=get_client_name()).inc()
+ return self._get_actors_via_raw_sql(actor_ids, sort_by_created_at_descending)
+
+ def _get_actors_via_personhog(
+ self,
+ client: "PersonHogClient",
+ actor_ids,
+ sort_by_created_at_descending: bool,
+ ) -> dict[str, dict]:
+ actor_ids_list = [str(uid) for uid in actor_ids]
+ team_id = self.team.pk
+
+ all_persons = []
+ for i in range(0, len(actor_ids_list), self.BATCH_SIZE):
+ batch = actor_ids_list[i : i + self.BATCH_SIZE]
+ resp = client.get_persons_by_uuids(GetPersonsByUuidsRequest(team_id=team_id, uuids=batch))
+
+ present = [p for p in resp.persons if p.id]
+ valid = [p for p in present if p.team_id == team_id]
+
+ mismatched = len(present) - len(valid)
+ if mismatched:
+ PERSONHOG_TEAM_MISMATCH_TOTAL.labels(operation="get_actors", client_name=get_client_name()).inc(
+ mismatched
+ )
+ logger.warning("personhog_team_mismatch", operation="get_actors", team_id=team_id, dropped=mismatched)
+
+ all_persons.extend(valid)
+
+ 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: dict[int, list[str]] = {}
+ for i in range(0, len(person_ids), self.BATCH_SIZE):
+ did_batch = person_ids[i : i + self.BATCH_SIZE]
+ did_resp = client.get_distinct_ids_for_persons(
+ GetDistinctIdsForPersonsRequest(team_id=team_id, person_ids=did_batch)
+ )
+ for pd in did_resp.person_distinct_ids:
+ distinct_ids_by_person[pd.person_id] = [d.distinct_id for d in pd.distinct_ids]
+
+ return {
+ p.uuid: {
+ "id": uuid_mod.UUID(p.uuid),
+ "properties": json.loads(p.properties) if p.properties else {},
+ "is_identified": p.is_identified,
+ "created_at": datetime.fromtimestamp(p.created_at / 1000, tz=UTC) if p.created_at else None,
+ "last_seen_at": datetime.fromtimestamp(p.last_seen_at / 1000, tz=UTC) if p.last_seen_at else None,
+ "distinct_ids": distinct_ids_by_person.get(p.id, []),
+ }
+ for p in all_persons
+ }
+
+ # Hand-written SQL instead of ORM because the ORM was blowing up memory on exports
+ def _get_actors_via_raw_sql(
+ self,
+ actor_ids,
+ sort_by_created_at_descending: bool,
+ ) -> dict[str, dict]:
person_table = Person._meta.db_table
pdi_table = PersonDistinctId._meta.db_table
conn = connections[READ_DB_FOR_PERSONS]
@@ -76,9 +166,9 @@ class PersonStrategy(ActorStrategy):
all_people.extend(cursor.fetchall())
if sort_by_created_at_descending:
- from datetime import datetime
+ from datetime import datetime as _datetime
- min_dt = datetime.min
+ min_dt = _datetime.min
all_people.sort(key=lambda p: (-(p[4] or min_dt).timestamp(), str(p[1])))
person_ids = [x[0] for x in all_people]
diff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.py
new file mode 100644
index 000000000000..247a4fce0176
--- /dev/null
+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py
@@ -0,0 +1,146 @@
+from datetime import timedelta
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized_class
+
+from posthog.schema import ActorsQuery
+
+from posthog.hogql_queries.actor_strategies import PersonStrategy
+from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
+from posthog.models import Team
+from posthog.personhog_client.test_helpers import PersonhogTestMixin
+
+
+def _make_strategy(team) -> PersonStrategy:
+ query = ActorsQuery(kind="ActorsQuery", select=["person"])
+ paginator = HogQLHasMorePaginator(limit=100, offset=0)
+ return PersonStrategy(team=team, query=query, paginator=paginator)
+
+
+@parameterized_class(("personhog",), [(False,), (True,)])
+class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):
+ def test_basic_person_lookup(self):
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-1"],
+ properties={"email": "[email protected]"},
+ )
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([str(person.uuid)])
+
+ assert len(result) == 1
+ entry = result[str(person.uuid)]
+ assert str(entry["id"]) == str(person.uuid)
+ assert entry["properties"] == {"email": "[email protected]"}
+ assert entry["is_identified"] is False
+ assert entry["created_at"] is not None
+ assert "distinct_ids" in entry
+ assert "did-1" in entry["distinct_ids"]
+
+ self._assert_personhog_called("get_persons_by_uuids")
+ self._assert_personhog_called("get_distinct_ids_for_persons")
+
+ def test_distinct_ids_included(self):
+ person = self._seed_person(
+ team=self.team,
+ distinct_ids=["did-a", "did-b", "did-c"],
+ properties={},
+ )
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([str(person.uuid)])
+
+ entry = result[str(person.uuid)]
+ assert set(entry["distinct_ids"]) == {"did-a", "did-b", "did-c"}
+
+ def test_multiple_persons(self):
+ p1 = self._seed_person(team=self.team, distinct_ids=["u1"], properties={"n": "1"})
+ p2 = self._seed_person(team=self.team, distinct_ids=["u2"], properties={"n": "2"})
+ p3 = self._seed_person(team=self.team, distinct_ids=["u3"], properties={"n": "3"})
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([str(p1.uuid), str(p2.uuid), str(p3.uuid)])
+
+ assert len(result) == 3
+ assert result[str(p1.uuid)]["properties"] == {"n": "1"}
+ assert result[str(p2.uuid)]["properties"] == {"n": "2"}
+ assert result[str(p3.uuid)]["properties"] == {"n": "3"}
+
+ def test_missing_persons_excluded(self):
+ person = self._seed_person(team=self.team, distinct_ids=["real"], properties={})
+ fake_uuid = str(uuid4())
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([str(person.uuid), fake_uuid])
+
+ assert len(result) == 1
+ assert str(person.uuid) in result
+ assert fake_uuid not in result
+
+ def test_empty_actor_ids(self):
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([])
+
+ assert result == {}
+
+ def test_batching(self):
+ persons = []
+ for i in range(5):
+ p = self._seed_person(team=self.team, distinct_ids=[f"batch-{i}"], properties={"i": i})
+ persons.append(p)
+
+ strategy = _make_strategy(self.team)
+ with patch.object(PersonStrategy, "BATCH_SIZE", 2):
+ result = strategy.get_actors([str(p.uuid) for p in persons])
+
+ assert len(result) == 5
+ for p in persons:
+ assert str(p.uuid) in result
+
+ def test_sort_by_created_at_descending(self):
+ now = timezone.now()
+ p_old = self._seed_person(team=self.team, distinct_ids=["old"], properties={})
+ p_mid = self._seed_person(team=self.team, distinct_ids=["mid"], properties={})
+ p_new = self._seed_person(team=self.team, distinct_ids=["new"], properties={})
+
+ from posthog.models.person import Person
+
+ Person.objects.filter(pk=p_old.pk).update(created_at=now - timedelta(hours=3))
+ Person.objects.filter(pk=p_mid.pk).update(created_at=now - timedelta(hours=1))
+ Person.objects.filter(pk=p_new.pk).update(created_at=now)
+
+ if self._fake_client is not None:
+ self._fake_client._persons_by_uuid[(self.team.pk, str(p_old.uuid))].created_at = int(
+ (now - timedelta(hours=3)).timestamp() * 1000
+ )
+ self._fake_client._persons_by_uuid[(self.team.pk, str(p_mid.uuid))].created_at = int(
+ (now - timedelta(hours=1)).timestamp() * 1000
+ )
+ self._fake_client._persons_by_uuid[(self.team.pk, str(p_new.uuid))].created_at = int(now.timestamp() * 1000)
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors(
+ [str(p_old.uuid), str(p_mid.uuid), str(p_new.uuid)],
+ sort_by_created_at_descending=True,
+ )
+
+ uuids_in_order = list(result.keys())
+ assert uuids_in_order == [str(p_new.uuid), str(p_mid.uuid), str(p_old.uuid)]
+
+ def test_cross_team_isolation(self):
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_person = self._seed_person(team=other_team, distinct_ids=["other"], properties={})
+ own_person = self._seed_person(team=self.team, distinct_ids=["own"], properties={})
+
+ strategy = _make_strategy(self.team)
+ result = strategy.get_actors([str(own_person.uuid), str(other_person.uuid)])
+
+ assert len(result) == 1
+ assert str(own_person.uuid) in result
+ assert str(other_person.uuid) not in result