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): mv split person reads to personhog (#61934)

Nick Bestb23448ebde14
diff --git a/posthog/models/person/person.py b/posthog/models/person/person.py
index 06824dce8771..dcfa5a9f2dd2 100644
--- a/posthog/models/person/person.py
+++ b/posthog/models/person/person.py
@@ -294,12 +294,11 @@ class Person(models.Model):
``max_splits`` of them). If ``main_distinct_id`` is also None, properties are
wiped from the original person and the first distinct_id becomes the main.
"""
- # nosemgrep: no-direct-persons-db-orm
- original_person = Person.objects.only(
- "id", "team_id", "uuid", "version"
- ).get( # nosemgrep: no-direct-persons-db-orm
- team_id=self.team_id, pk=self.pk
- ) # nosemgrep: no-direct-persons-db-orm
+ from posthog.models.person.util import get_person_by_id
+
+ original_person = get_person_by_id(self.team_id, self.pk)
+ if original_person is None:
+ raise ValueError(f"Person not found: person_id={self.pk}, team_id={self.team_id}")
distinct_ids = original_person.distinct_ids
original_person_version = original_person.version or 0
@@ -331,8 +330,9 @@ class Person(models.Model):
distinct_ids_to_process.append(did)
else:
if not main_distinct_id:
- self.properties = {}
- self.save(update_fields=["properties"])
+ Person.objects.filter(team_id=self.team_id, pk=self.pk).update( # nosemgrep: no-direct-persons-db-orm
+ properties={}
+ )
main_distinct_id = distinct_ids[0]
if max_splits is not None and len(distinct_ids) > max_splits:
diff --git a/posthog/models/person/test/test_split_person.py b/posthog/models/person/test/test_split_person.py
index 398900b1bc24..c05b71b7fd2d 100644
--- a/posthog/models/person/test/test_split_person.py
+++ b/posthog/models/person/test/test_split_person.py
@@ -7,6 +7,7 @@ from posthog.models import Person
from posthog.models.person import PersonDistinctId
from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.models.person.util import person_created, person_distinct_id_created
+from posthog.personhog_client.fake_client import fake_personhog_client
@patch("posthog.models.person.util.create_person")
@@ -334,3 +335,129 @@ class TestSplitPerson(BaseTest):
assert mock_create_pdi.call_count == 100
assert mock_create_person.call_count == 100
+
+
+@patch("posthog.models.person.util.create_person")
+@patch("posthog.models.person.util.create_person_distinct_id")
+class TestSplitPersonPersonhogRouting(BaseTest):
+ """Verify split_person routes reads through personhog when enabled."""
+
+ def setUp(self):
+ super().setUp()
+ post_save.disconnect(person_created, sender=Person)
+ post_save.disconnect(person_distinct_id_created, sender=PersonDistinctId)
+
+ def tearDown(self):
+ post_save.connect(person_created, sender=Person)
+ post_save.connect(person_distinct_id_created, sender=PersonDistinctId)
+ super().tearDown()
+
+ def _create_person_with_distinct_ids(
+ self,
+ distinct_ids: list[str],
+ mock_create_pdi,
+ mock_create_person,
+ properties: dict | None = None,
+ version: int = 0,
+ ) -> Person:
+ person = Person.objects.create(
+ team=self.team,
+ properties=properties or {},
+ version=version,
+ )
+ for distinct_id in distinct_ids:
+ PersonDistinctId.objects.create(
+ team=self.team,
+ person=person,
+ distinct_id=distinct_id,
+ )
+ mock_create_pdi.reset_mock()
+ mock_create_person.reset_mock()
+ return person
+
+ def test_split_uses_personhog_data_not_orm(self, mock_create_pdi, mock_create_person):
+ # DB has version=5, but personhog returns version=20.
+ # If the split uses personhog data, new persons get version 20+101=121.
+ # If it fell through to ORM, they'd get 5+101=106.
+ person = self._create_person_with_distinct_ids(
+ ["id1", "id2", "id3"], mock_create_pdi, mock_create_person, version=5
+ )
+
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person.id,
+ uuid=str(person.uuid),
+ distinct_ids=["id1", "id2", "id3"],
+ version=20,
+ )
+
+ person.split_person(main_distinct_id="id1")
+
+ fake.assert_called("get_person", times=1)
+ fake.assert_called("get_distinct_ids_for_person", times=1)
+
+ pdi_id1 = PersonDistinctId.objects.get(team=self.team, distinct_id="id1")
+ pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
+ assert pdi_id1.person_id == person.id
+ assert pdi_id2.person_id != person.id
+
+ new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
+ assert new_person.version == 20 + 101
+
+ def test_split_falls_back_to_orm_on_personhog_failure(self, mock_create_pdi, mock_create_person):
+ person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person, version=3)
+
+ with fake_personhog_client() as fake:
+ # Don't seed the fake — get_person returns empty, which triggers
+ # a None return from the converter, causing _personhog_routed to
+ # catch the error and fall back to ORM.
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person.id,
+ uuid=str(person.uuid),
+ distinct_ids=["id1", "id2"],
+ version=3,
+ )
+ # Simulate a gRPC failure by making get_person raise
+ call_count = 0
+
+ def failing_get_person(request):
+ nonlocal call_count
+ call_count += 1
+ raise RuntimeError("simulated gRPC failure")
+
+ fake.get_person = failing_get_person
+
+ person.split_person(main_distinct_id="id1")
+
+ assert call_count == 1
+
+ pdi_id1 = PersonDistinctId.objects.get(team=self.team, distinct_id="id1")
+ pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
+ assert pdi_id1.person_id == person.id
+ assert pdi_id2.person_id != person.id
+
+ new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
+ assert new_person.version == 3 + 101
+
+ def test_split_from_stub_person_clears_properties(self, mock_create_pdi, mock_create_person):
+ """Verify split works when called on a stub Person(pk=..., team_id=...)
+ rather than a DB-fetched instance — this is how the Celery task invokes it."""
+ person = self._create_person_with_distinct_ids(
+ ["id1", "id2"],
+ mock_create_pdi,
+ mock_create_person,
+ properties={"email": "[email protected]"},
+ )
+
+ stub = Person(pk=person.id, team_id=self.team.id)
+ stub.split_person(main_distinct_id=None)
+
+ person.refresh_from_db()
+ assert person.properties == {}
+
+ pdi_id1 = PersonDistinctId.objects.get(team=self.team, distinct_id="id1")
+ pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
+ assert pdi_id1.person_id == person.id
+ assert pdi_id2.person_id != person.id
diff --git a/posthog/tasks/split_person.py b/posthog/tasks/split_person.py
index ea122c106e45..d2c376fcf1c3 100644
--- a/posthog/tasks/split_person.py
+++ b/posthog/tasks/split_person.py
@@ -1,4 +1,4 @@
-from typing import Optional, Union
+from typing import Optional
import structlog
from celery import shared_task
@@ -13,7 +13,7 @@ logger = structlog.get_logger(__name__)
@skip_team_scope_audit
def split_person(
person_id: int,
- team_id: Union[int, str, None] = None,
+ team_id: int,
main_distinct_id: Optional[str] = None,
max_splits: Optional[int] = None,
distinct_ids_to_split: Optional[list[str]] = None,
@@ -21,10 +21,6 @@ def split_person(
"""
Split all distinct ids into separate persons
- Note: team_id is now required for efficient querying on partitioned tables.
- For backward compatibility during rolling deploys, if team_id looks like a string
- (old main_distinct_id position), we fall back to legacy behavior.
-
When ``distinct_ids_to_split`` is provided, only those specific distinct_ids are
moved off of the original person; everything else (including properties) stays
intact. See ``Person.split_person`` for details.
@@ -38,84 +34,22 @@ def split_person(
distinct_ids_to_split_count=len(distinct_ids_to_split) if distinct_ids_to_split is not None else None,
)
- resolved_team_id: Union[int, None] = None
-
try:
- # Backward compatibility: detect old 3-arg signature (person_id, main_distinct_id, max_splits)
- # where second arg would be a string (distinct_id) or None
- is_legacy = isinstance(team_id, str) or (team_id is None and main_distinct_id is None)
- logger.info(
- "split_person path determined",
- person_id=person_id,
- is_legacy=is_legacy,
- team_id_type=type(team_id).__name__,
- )
- if is_legacy:
- # Old signature: split_person(person_id, main_distinct_id, max_splits)
- # Get team_id from PersonDistinctId to avoid scanning all partitions
- from posthog.models import PersonDistinctId
-
- old_main_distinct_id: Optional[str] = team_id if isinstance(team_id, str) else None
- old_max_splits: Optional[int] = int(main_distinct_id) if main_distinct_id is not None else None
-
- logger.info(
- "split_person legacy path: querying PersonDistinctId for team_id",
- person_id=person_id,
- )
- # Lookup team_id via PersonDistinctId which has person_id FK
- pdi = (
- # nosemgrep: no-direct-persons-db-orm
- PersonDistinctId.objects.filter(person_id=person_id)
- .only("team_id")
- .first() # nosemgrep: no-direct-persons-db-orm
- ) # nosemgrep: no-direct-persons-db-orm
- if not pdi:
- raise ValueError(f"Cannot find team_id for person_id={person_id}")
-
- resolved_team_id = pdi.team_id
- logger.info(
- "split_person legacy path: fetching Person",
- person_id=person_id,
- team_id=resolved_team_id,
- )
- person = Person.objects.get(team_id=resolved_team_id, pk=person_id) # nosemgrep: no-direct-persons-db-orm
- logger.info(
- "split_person legacy path: calling split_person on model",
- person_id=person_id,
- team_id=resolved_team_id,
- main_distinct_id=old_main_distinct_id,
- max_splits=old_max_splits,
- )
- person.split_person(old_main_distinct_id, old_max_splits, distinct_ids_to_split=distinct_ids_to_split)
- else:
- # New signature: split_person(person_id, team_id, main_distinct_id, max_splits)
- assert team_id is not None and isinstance(team_id, int), "team_id must be an int in new signature"
- resolved_team_id = team_id
- logger.info(
- "split_person new path: fetching Person",
- person_id=person_id,
- team_id=resolved_team_id,
- )
- person = Person.objects.get(team_id=resolved_team_id, pk=person_id) # nosemgrep: no-direct-persons-db-orm
- logger.info(
- "split_person new path: calling split_person on model",
- person_id=person_id,
- team_id=resolved_team_id,
- main_distinct_id=main_distinct_id,
- max_splits=max_splits,
- )
- person.split_person(main_distinct_id, max_splits, distinct_ids_to_split=distinct_ids_to_split)
+ # split_person() fetches the person via get_person_by_id internally,
+ # so we only construct a stub here to avoid a redundant fetch.
+ person = Person(pk=person_id, team_id=team_id)
+ person.split_person(main_distinct_id, max_splits, distinct_ids_to_split=distinct_ids_to_split)
logger.info(
"split_person task completed",
person_id=person_id,
- team_id=resolved_team_id,
+ team_id=team_id,
)
except Exception as e:
logger.exception(
"split_person task failed",
person_id=person_id,
- team_id=resolved_team_id,
+ team_id=team_id,
main_distinct_id=main_distinct_id,
max_splits=max_splits,
distinct_ids_to_split_count=len(distinct_ids_to_split) if distinct_ids_to_split is not None else None,