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): consume personhog person split rpc in django (#63362)

Nick Best8217e92cf9ef
diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.yml
index a061cbf08aa9..2c36762c5202 100644
--- a/.github/workflows/ci-e2e-playwright.yml
+++ b/.github/workflows/ci-e2e-playwright.yml
@@ -72,6 +72,7 @@ env:
INKEEP_API_KEY: ${{ secrets.INKEEP_API_KEY }}
AZURE_INFERENCE_CREDENTIAL: ${{ secrets.AZURE_INFERENCE_CREDENTIAL }}
AZURE_INFERENCE_ENDPOINT: ${{ secrets.AZURE_INFERENCE_ENDPOINT }}
+ PERSONHOG_ADDR: 'localhost:50052'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 0b7a8f2d491a..9c5613247e0a 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -589,6 +589,8 @@ services:
extends:
file: docker-compose.base.yml
service: personhog-router
+ ports:
+ - '50052:50052'
depends_on:
personhog-replica:
condition: service_started
diff --git a/posthog/api/person.py b/posthog/api/person.py
index ad9a6af809cc..dca3ceffb246 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -239,7 +239,8 @@ class PersonSplitRequestSerializer(serializers.Serializer):
help_text=(
"The distinct_id to **keep** on this person; every *other* distinct_id is moved "
"to its own new single-id person. If omitted, the first distinct_id on the person "
- "is used and the person's properties are wiped. "
+ "is kept. The original person always retains its properties; to clear individual "
+ "properties afterward, use the delete_property endpoint. "
"To surgically *remove* one or more distinct_ids while leaving the merge intact, "
"use `distinct_ids_to_split` instead — these parameters are inverses of each other "
"and cannot be combined."
@@ -826,10 +827,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"- **`distinct_ids_to_split`** (recommended for surgical edits): moves only the "
"listed distinct_ids off this person onto new single-id persons. The original "
"person keeps every other distinct_id and its properties.\n"
- "- **`main_distinct_id`** (legacy semantics): keeps only the specified distinct_id "
+ "- **`main_distinct_id`**: keeps only the specified distinct_id "
"on this person; moves every *other* distinct_id off onto its own new person. If "
- "omitted, the person's properties are wiped and the first distinct_id is treated "
- "as the one to keep.\n\n"
+ "omitted, the first distinct_id is kept.\n\n"
+ "The original person always retains its properties. To clear individual "
+ "properties afterward, use the `delete_property` endpoint.\n\n"
"The split runs asynchronously: a 201 response means the task was enqueued. "
"Newly-created split-off persons get a deterministic UUID derived from "
"`(team_id, distinct_id)`, so they can be located client-side without polling. "
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 13038a98efb6..15d9ebee3c7a 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -28,8 +28,10 @@ from posthog.clickhouse.client import sync_execute
from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import PersonDistinctId
+from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE
from posthog.models.person.util import create_person, create_person_distinct_id
+from posthog.personhog_client.fake_client import fake_personhog_client
from products.cohorts.backend.models.cohort import Cohort
@@ -841,14 +843,27 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties={"$browser": "whatever", "$os": "Mac OS X"},
)
- self.client.post("/api/person/{}/split/".format(person1.pk), {"main_distinct_id": "1"})
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person1.pk,
+ uuid=str(person1.uuid),
+ distinct_ids=["1", "2", "3"],
+ )
+
+ self.client.post("/api/person/{}/split/".format(person1.pk), {"main_distinct_id": "1"})
+
+ split_calls = fake.assert_called("split_person", times=1)
+ self.assertEqual(list(split_calls[0].request.distinct_ids_to_split), ["2", "3"])
+ # "1" stays on the original; "2" and "3" each land on their own new person
+ self.assertEqual(fake._persons_by_distinct_id[(self.team.id, "1")].id, person1.pk)
+ moved = {did: fake._persons_by_distinct_id[(self.team.id, did)].id for did in ["2", "3"]}
+ self.assertNotIn(person1.pk, moved.values())
+ self.assertNotEqual(moved["2"], moved["3"])
- people = Person.objects.filter(team_id=self.team.id).order_by("id")
- self.assertEqual(people.count(), 3)
- self.assertEqual(people[0].distinct_ids, ["1"])
- self.assertEqual(people[0].properties, {"$browser": "whatever", "$os": "Mac OS X"})
- self.assertEqual(people[1].distinct_ids, ["2"])
- self.assertEqual(people[2].distinct_ids, ["3"])
+ # Properties stay on the original person when a main_distinct_id is given
+ person1.refresh_from_db()
+ self.assertEqual(person1.properties, {"$browser": "whatever", "$os": "Mac OS X"})
self._assert_person_activity(
person_id=person1.uuid,
@@ -887,13 +902,24 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
immediate=True,
)
- response = self.client.post("/api/person/{}/split/".format(person1.pk))
- people = Person.objects.filter(team_id=self.team.id).order_by("id")
- self.assertEqual(people.count(), 3)
- self.assertEqual(people[0].distinct_ids, ["1"])
- self.assertEqual(people[0].properties, {})
- self.assertEqual(people[1].distinct_ids, ["2"])
- self.assertEqual(people[2].distinct_ids, ["3"])
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person1.pk,
+ uuid=str(person1.uuid),
+ distinct_ids=["1", "2", "3"],
+ )
+
+ response = self.client.post("/api/person/{}/split/".format(person1.pk))
+
+ # Without a main_distinct_id the first distinct_id stays; the rest split off
+ split_calls = fake.assert_called("split_person", times=1)
+ self.assertEqual(list(split_calls[0].request.distinct_ids_to_split), ["2", "3"])
+ self.assertEqual(fake._persons_by_distinct_id[(self.team.id, "1")].id, person1.pk)
+
+ # Properties are always kept on the original person
+ person1.refresh_from_db()
+ self.assertEqual(person1.properties, {"$browser": "whatever", "$os": "Mac OS X"})
self.assertTrue(response.json()["success"])
def test_split_people_partial_moves_only_specified_ids(self) -> None:
@@ -904,23 +930,35 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
immediate=True,
)
- response = self.client.post(
- "/api/person/{}/split/".format(person1.pk),
- {"distinct_ids_to_split": ["move1", "move2"]},
- )
- self.assertEqual(response.status_code, 201, response.content)
- self.assertTrue(response.json()["success"])
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person1.pk,
+ uuid=str(person1.uuid),
+ distinct_ids=["keep1", "move1", "keep2", "move2"],
+ )
+
+ response = self.client.post(
+ "/api/person/{}/split/".format(person1.pk),
+ {"distinct_ids_to_split": ["move1", "move2"]},
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ self.assertTrue(response.json()["success"])
+ split_calls = fake.assert_called("split_person", times=1)
+ self.assertEqual(list(split_calls[0].request.distinct_ids_to_split), ["move1", "move2"])
+
+ # Kept distinct_ids stay on the original; each moved one lands on its own new person.
+ for did in ["keep1", "keep2"]:
+ self.assertEqual(fake._persons_by_distinct_id[(self.team.id, did)].id, person1.pk)
+ moved = {did: fake._persons_by_distinct_id[(self.team.id, did)].id for did in ["move1", "move2"]}
+ self.assertNotIn(person1.pk, moved.values())
+ self.assertNotEqual(moved["move1"], moved["move2"])
+
+ # The partial-split guarantee: the original person keeps its properties.
original = Person.objects.get(team_id=self.team.id, pk=person1.pk)
- self.assertCountEqual(original.distinct_ids, ["keep1", "keep2"])
self.assertEqual(original.properties, {"$browser": "whatever", "$os": "Mac OS X"})
- # Two new persons, one per moved distinct_id.
- other_people = Person.objects.filter(team_id=self.team.id).exclude(pk=person1.pk).order_by("id")
- self.assertEqual(other_people.count(), 2)
- moved_ids = {did for p in other_people for did in p.distinct_ids}
- self.assertEqual(moved_ids, {"move1", "move2"})
-
def test_split_people_partial_rejects_unknown_distinct_id(self) -> None:
person1 = _create_person(
team=self.team,
@@ -1383,27 +1421,39 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
immediate=True,
)
- response = self.client.post("/api/person/{}/split/".format(person.uuid)).json()
- self.assertTrue(response["success"])
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person.pk,
+ uuid=str(person.uuid),
+ distinct_ids=["1", "2", "3"],
+ )
+
+ response = self.client.post("/api/person/{}/split/".format(person.uuid)).json()
+ self.assertTrue(response["success"])
- people = Person.objects.filter(team_id=self.team.id).order_by("id")
+ # ClickHouse ends up with the original person plus one new person per
+ # split distinct_id, each with its deterministic UUID.
+ expected_person_by_did = {
+ "1": person.uuid,
+ "2": uuidFromDistinctId(self.team.pk, "2"),
+ "3": uuidFromDistinctId(self.team.pk, "3"),
+ }
clickhouse_people = sync_execute(
"SELECT id FROM person FINAL WHERE team_id = %(team_id)s",
{"team_id": self.team.pk},
)
- self.assertCountEqual(clickhouse_people, [(person.uuid,) for person in people])
+ self.assertCountEqual(clickhouse_people, [(uuid,) for uuid in expected_person_by_did.values()])
pdis2 = sync_execute(
"SELECT person_id, distinct_id, is_deleted FROM person_distinct_id2 FINAL WHERE team_id = %(team_id)s",
{"team_id": self.team.pk},
)
- self.assertEqual(len(pdis2), PersonDistinctId.objects.count())
-
- for person in people:
- self.assertEqual(len(person.distinct_ids), 1)
- matching_row = next(row for row in pdis2 if row[0] == person.uuid)
- self.assertEqual(matching_row, (person.uuid, person.distinct_ids[0], 0))
+ self.assertEqual(len(pdis2), 3)
+ for distinct_id, expected_uuid in expected_person_by_did.items():
+ matching_row = next(row for row in pdis2 if row[1] == distinct_id)
+ self.assertEqual(matching_row, (expected_uuid, distinct_id, 0))
def test_split_person_overrides_delete_version(self):
"""
@@ -1413,7 +1463,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
When splitting, the new person should use version + 101 (e.g., version 101) to ensure
ClickHouse sees the split person as more recent than the delete event.
"""
- from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.models.person.util import delete_person
# Create person A with UUID derived from the distinct_id (same UUID that split will use)
@@ -1472,8 +1521,17 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(set(person_b.distinct_ids), {"active_user", "deleted_user"})
# Split person B
- response = self.client.post("/api/person/{}/split/".format(person_b.uuid)).json()
- self.assertTrue(response["success"])
+ with fake_personhog_client() as fake:
+ fake.add_person(
+ team_id=self.team.pk,
+ person_id=person_b.pk,
+ uuid=str(person_b.uuid),
+ distinct_ids=["active_user", "deleted_user"],
+ distinct_id_versions={"deleted_user": 2},
+ )
+
+ response = self.client.post("/api/person/{}/split/".format(person_b.uuid)).json()
+ self.assertTrue(response["success"])
# Verify ClickHouse has the correct state
ch_persons = sync_execute(
diff --git a/posthog/models/person/person.py b/posthog/models/person/person.py
index dcfa5a9f2dd2..64e3a3bad815 100644
--- a/posthog/models/person/person.py
+++ b/posthog/models/person/person.py
@@ -1,4 +1,6 @@
-from typing import Any, Optional, cast
+from datetime import UTC, datetime
+from typing import Any, NamedTuple, Optional, cast
+from uuid import UUID
from django.conf import settings
from django.core.exceptions import EmptyResultSet
@@ -11,12 +13,25 @@ from posthog.models.utils import UUIDT
from posthog.person_db_router import PERSONS_DB_FOR_READ
from ..team import Team
-from .missing_person import uuidFromDistinctId
logger = structlog.get_logger(__name__)
MAX_LIMIT_DISTINCT_IDS = 2500
+# Mirrors MAX_SPLIT_BATCH_SIZE enforced by the personhog SplitPerson RPC.
+PERSONHOG_SPLIT_BATCH_SIZE = 250
+
+
+class SplitOutcome(NamedTuple):
+ """One distinct_id split onto a new person — the data needed to publish to Kafka."""
+
+ distinct_id: str
+ new_person_uuid: UUID
+ new_person_version: int
+ pdi_version: int
+ new_person_created_at: datetime
+
+
# Use centralized database routing constant
READ_DB_FOR_PERSONS = PERSONS_DB_FOR_READ
@@ -289,181 +304,188 @@ class Person(models.Model):
ignored. This is the "partial split" path — useful to surgically extract IDs
that were over-merged into a mega-person.
- When ``distinct_ids_to_split`` is None, the legacy behavior applies: every
- distinct_id except ``main_distinct_id`` is split off (or only the last
- ``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.
+ When ``distinct_ids_to_split`` is None, every distinct_id except
+ ``main_distinct_id`` is split off (or only the first ``max_splits`` of them).
+ If ``main_distinct_id`` is also None, the first distinct_id is kept. The
+ original person always retains its properties.
"""
- from posthog.models.person.util import get_person_by_id
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import GetPersonRequest
- original_person = get_person_by_id(self.team_id, self.pk)
- if original_person is None:
+ client = get_personhog_client()
+ if client is None:
+ raise RuntimeError(
+ "split_person requires personhog, but the client is not configured (PERSONHOG_ADDR is unset)"
+ )
+
+ person_resp = client.get_person(GetPersonRequest(team_id=self.team_id, person_id=self.pk))
+ if not person_resp.person or not person_resp.person.id:
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
logger.info(
"split_person queried person",
person_id=self.pk,
- person_uuid=str(original_person.uuid),
+ person_uuid=person_resp.person.uuid,
team_id=self.team_id,
- version=original_person_version,
- distinct_ids_count=len(distinct_ids),
+ version=person_resp.person.version,
main_distinct_id=main_distinct_id,
max_splits=max_splits,
explicit_distinct_ids_count=len(distinct_ids_to_split) if distinct_ids_to_split is not None else None,
)
if distinct_ids_to_split is not None:
- unknown = set(distinct_ids_to_split) - set(distinct_ids)
- if unknown:
- raise ValueError(
- f"split_person: distinct_ids {sorted(unknown)} do not belong to "
- f"person_id={self.pk} (team_id={self.team_id})"
- )
- # Dedupe while preserving order for deterministic logging.
- seen: set[str] = set()
- distinct_ids_to_process: list[str] = []
- for did in distinct_ids_to_split:
- if did not in seen:
- seen.add(did)
- distinct_ids_to_process.append(did)
+ self._split_explicit_ids(distinct_ids_to_split)
else:
- if not main_distinct_id:
- 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]
+ self._split_all_ids(client, main_distinct_id, max_splits)
- if max_splits is not None and len(distinct_ids) > max_splits:
- # Split the last N distinct_ids of the list
- distinct_ids = distinct_ids[-1 * max_splits :]
+ def _split_explicit_ids(self, distinct_ids_to_split: list[str]) -> None:
+ """Partial split: caller specifies exactly which IDs to move.
- distinct_ids_to_process = [did for did in distinct_ids if did != main_distinct_id]
+ The RPC validates that every ID belongs to this person — no need to
+ fetch all distinct IDs upfront.
+ """
+ seen: set[str] = set()
+ distinct_ids_to_process: list[str] = []
+ for did in distinct_ids_to_split:
+ if did not in seen:
+ seen.add(did)
+ distinct_ids_to_process.append(did)
if not distinct_ids_to_process:
return
logger.info(
- "split_person will split distinct_ids",
+ "split_person will split explicit distinct_ids",
person_id=self.pk,
team_id=self.team_id,
- main_distinct_id=main_distinct_id,
distinct_ids_to_split_count=len(distinct_ids_to_process),
)
- db_alias = router.db_for_write(PersonDistinctId) or "default"
- new_uuid_by_distinct_id = {
- distinct_id: uuidFromDistinctId(self.team_id, distinct_id) for distinct_id in distinct_ids_to_process
- }
+ for start in range(0, len(distinct_ids_to_process), PERSONHOG_SPLIT_BATCH_SIZE):
+ batch = distinct_ids_to_process[start : start + PERSONHOG_SPLIT_BATCH_SIZE]
+ outcomes = self._split_distinct_ids_batch(batch)
+ self._publish_split_to_kafka(outcomes)
+
+ def _split_all_ids(self, client: Any, main_distinct_id: Optional[str], max_splits: Optional[int]) -> None:
+ """Full split: fetch pages of distinct IDs and split each page.
+
+ Each split removes the IDs from this person, so the next fetch returns
+ a shrinking set. No ordering is needed — the loop terminates when only
+ the main distinct_id remains (or max_splits is reached).
+ """
+ from posthog.personhog_client.proto import GetDistinctIdsForPersonRequest
+
+ splits_done = 0
+ # +1 so the main_distinct_id can appear in the page without eating a split slot
+ fetch_limit = PERSONHOG_SPLIT_BATCH_SIZE + 1
+
+ while True:
+ did_resp = client.get_distinct_ids_for_person(
+ GetDistinctIdsForPersonRequest(
+ team_id=self.team_id,
+ person_id=self.pk,
+ limit=fetch_limit,
+ )
+ )
+ page = [d.distinct_id for d in did_resp.distinct_ids]
- with transaction.atomic(using=db_alias):
- # 1. Lock all PDIs in one query — hits unique index (team_id, distinct_id)
- locked_pdis = self._lock_person_distinct_ids(distinct_ids_to_process)
+ if not page:
+ break
- # 2. Create or update persons for each split distinct_id
- new_person_by_uuid = self._create_split_persons(new_uuid_by_distinct_id, original_person_version)
+ if not main_distinct_id:
+ main_distinct_id = page[0]
- # 3. Reassign PDIs to new persons
- self._assign_person_distinct_ids(locked_pdis, new_person_by_uuid, new_uuid_by_distinct_id)
+ to_split = [did for did in page if did != main_distinct_id]
- # 4. Publish Kafka messages after transaction commits — DB is source of truth,
- # Kafka/ClickHouse catches up via versioning
- self._publish_split_to_kafka(locked_pdis, new_person_by_uuid, new_uuid_by_distinct_id)
+ if not to_split:
+ break
- def _lock_person_distinct_ids(self, distinct_ids: list[str]) -> dict[str, "PersonDistinctId"]:
- """Lock and return PDIs for the given distinct_ids. Raises if any are missing."""
- locked = {
- person_distinct_id.distinct_id: person_distinct_id
- for person_distinct_id in PersonDistinctId.objects.select_for_update().filter( # nosemgrep: no-direct-persons-db-orm
- team_id=self.team_id, person=self, distinct_id__in=distinct_ids
- )
- }
+ if max_splits is not None:
+ remaining = max_splits - splits_done
+ if remaining <= 0:
+ break
+ to_split = to_split[:remaining]
- missing = set(distinct_ids) - set(locked.keys())
- if missing:
- raise ValueError(
- f"split_person: PDIs missing for distinct_ids {missing} (team_id={self.team_id}, person_id={self.pk})"
+ logger.info(
+ "split_person splitting page",
+ person_id=self.pk,
+ team_id=self.team_id,
+ main_distinct_id=main_distinct_id,
+ page_size=len(page),
+ splitting_count=len(to_split),
+ splits_done=splits_done,
)
- logger.info(
- "split_person locked PDIs",
- person_id=self.pk,
- team_id=self.team_id,
- locked_count=len(locked),
- )
+ outcomes = self._split_distinct_ids_batch(to_split)
+ self._publish_split_to_kafka(outcomes)
+ splits_done += len(outcomes)
- return locked
+ if len(page) < fetch_limit:
+ break
- def _create_split_persons(self, new_uuid_by_distinct_id: dict, original_person_version: int) -> dict:
- """Create or update a Person for each split distinct_id.
+ def _split_distinct_ids_batch(self, distinct_ids: list[str]) -> list[SplitOutcome]:
+ """Split one batch of distinct_ids onto new persons via the personhog
+ SplitPerson RPC. Personhog owns this write — there is no ORM path.
- update_or_create handles pre-existing persons (e.g., from a previous partial run)
- by bumping their version, so the Kafka message carries the correct version.
- Set version higher than delete events (which use version + 100).
- Keep in sync with: posthog/models/person/util.py:222 (_delete_person)
- and plugin-server/src/utils/db/utils.ts:152 (generateKafkaPersonUpdateMessage)
+ The server creates each new person with a deterministic UUIDv5
+ (matching ``uuidFromDistinctId``) and bumps versions by 101, higher
+ than delete events (which use version + 100) so the split overrides
+ any deleted rows. Keep in sync with:
+ posthog/models/person/util.py (_delete_person) and
+ rust/personhog-replica/src/storage/postgres/person.rs (SPLIT_VERSION_OFFSET).
"""
- new_person_by_uuid = {}
- for new_uuid in new_uuid_by_distinct_id.values():
- new_person, _created = Person.objects.update_or_create( # nosemgrep: no-direct-persons-db-orm
- uuid=new_uuid,
- team_id=self.team_id,
- defaults={"version": original_person_version + 101},
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import SplitPersonRequest
+
+ client = get_personhog_client()
+ if client is None:
+ raise RuntimeError(
+ "split_person requires personhog, but the client is not configured (PERSONHOG_ADDR is unset)"
)
- new_person_by_uuid[new_uuid] = new_person
- logger.info(
- "split_person created persons",
- person_id=self.pk,
- team_id=self.team_id,
- created_count=len(new_person_by_uuid),
+ response = client.split_person(
+ SplitPersonRequest(
+ team_id=self.team_id,
+ person_id=self.pk,
+ distinct_ids_to_split=distinct_ids,
+ )
)
+ if len(response.splits) != len(distinct_ids):
+ logger.error(
+ "split_person RPC returned unexpected number of splits",
+ expected=len(distinct_ids),
+ actual=len(response.splits),
+ team_id=self.team_id,
+ person_id=self.pk,
+ )
+ return [
+ SplitOutcome(
+ distinct_id=split.distinct_id,
+ new_person_uuid=UUID(split.new_person_uuid),
+ new_person_version=split.new_person_version,
+ pdi_version=split.pdi_version,
+ new_person_created_at=datetime.fromtimestamp(split.new_person_created_at_ms / 1000, tz=UTC),
+ )
+ for split in response.splits
+ ]
- return new_person_by_uuid
-
- @staticmethod
- def _assign_person_distinct_ids(
- locked_pdis: dict[str, "PersonDistinctId"],
- new_person_by_uuid: dict,
- new_uuid_by_distinct_id: dict,
- ) -> None:
- """Point each locked PDI to its new person and bump its version."""
- for distinct_id, person_distinct_id in locked_pdis.items():
- new_person = new_person_by_uuid[new_uuid_by_distinct_id[distinct_id]]
- person_distinct_id.person_id = str(new_person.id)
- # Set distinct_id version higher than delete events (which use pdi.version + 100).
- # This ensures the split distinct_id overrides any deleted distinct_id.
- person_distinct_id.version = (person_distinct_id.version or 0) + 101
-
- PersonDistinctId.objects.bulk_update( # nosemgrep: no-direct-persons-db-orm
- list(locked_pdis.values()), ["person_id", "version"]
- ) # nosemgrep: no-direct-persons-db-orm
-
- def _publish_split_to_kafka(
- self,
- locked_pdis: dict[str, "PersonDistinctId"],
- new_person_by_uuid: dict,
- new_uuid_by_distinct_id: dict,
- ) -> None:
+ def _publish_split_to_kafka(self, outcomes: list[SplitOutcome]) -> None:
"""Publish Kafka messages for each split person and PDI reassignment."""
from posthog.models.person.util import create_person, create_person_distinct_id
- for distinct_id, person_distinct_id in locked_pdis.items():
- new_person = new_person_by_uuid[new_uuid_by_distinct_id[distinct_id]]
-
+ for outcome in outcomes:
create_person_distinct_id(
team_id=self.team_id,
- distinct_id=distinct_id,
- person_id=str(new_person.uuid),
+ distinct_id=outcome.distinct_id,
+ person_id=str(outcome.new_person_uuid),
is_deleted=False,
- version=person_distinct_id.version,
+ version=outcome.pdi_version,
)
create_person(
team_id=self.team_id,
- uuid=str(new_person.uuid),
- version=new_person.version,
- created_at=new_person.created_at,
+ uuid=str(outcome.new_person_uuid),
+ version=outcome.new_person_version,
+ created_at=outcome.new_person_created_at,
)
diff --git a/posthog/models/person/test/test_split_person.py b/posthog/models/person/test/test_split_person.py
index c05b71b7fd2d..6d225c13222e 100644
--- a/posthog/models/person/test/test_split_person.py
+++ b/posthog/models/person/test/test_split_person.py
@@ -1,34 +1,27 @@
+from datetime import UTC, datetime
+
from posthog.test.base import BaseTest
from unittest.mock import patch
-from django.db.models.signals import post_save
-
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
+from posthog.personhog_client.fake_client import FakePersonHogClient, fake_personhog_client
@patch("posthog.models.person.util.create_person")
@patch("posthog.models.person.util.create_person_distinct_id")
class TestSplitPerson(BaseTest):
- def setUp(self):
- super().setUp()
- # Disconnect test-only post_save signals (see posthog/models/person/util.py)
- # that automatically call create_person/create_person_distinct_id on every
- # ORM save. split_person publishes to Kafka explicitly, so these signals
- # would double-count calls and make assertions unreliable.
- 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(
+ """split_person reads and writes person data exclusively through personhog.
+
+ The local DB person row only matters for the legacy properties-wipe path;
+ PDI rows are created here purely to prove the split never touches them
+ via the ORM.
+ """
+
+ def _setup_person(
self,
+ fake: FakePersonHogClient,
distinct_ids: list[str],
mock_create_pdi,
mock_create_person,
@@ -46,125 +39,129 @@ class TestSplitPerson(BaseTest):
person=person,
distinct_id=distinct_id,
)
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=person.id,
+ uuid=str(person.uuid),
+ distinct_ids=distinct_ids,
+ version=version,
+ )
# Reset mocks after setup so post_save signal calls from setup don't count
mock_create_pdi.reset_mock()
mock_create_person.reset_mock()
return person
def test_split_with_main_distinct_id(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["id1", "id2", "id3"],
- mock_create_pdi,
- mock_create_person,
- properties={"email": "[email protected]", "name": "Test"},
- )
+ with fake_personhog_client() as fake:
+ person = self._setup_person(
+ fake,
+ ["id1", "id2", "id3"],
+ mock_create_pdi,
+ mock_create_person,
+ properties={"email": "[email protected]", "name": "Test"},
+ )
- person.split_person(main_distinct_id="id1")
+ person.split_person(main_distinct_id="id1")
- pdi_id1 = PersonDistinctId.objects.get(team=self.team, distinct_id="id1")
- pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- pdi_id3 = PersonDistinctId.objects.get(team=self.team, distinct_id="id3")
+ split_calls = fake.assert_called("split_person", times=1)
+ assert set(split_calls[0].request.distinct_ids_to_split) == {"id2", "id3"}
+ assert split_calls[0].request.team_id == self.team.id
+ assert split_calls[0].request.person_id == person.id
- assert pdi_id1.person_id == person.id
- assert pdi_id2.person_id != person.id
- assert pdi_id3.person_id != person.id
- assert pdi_id2.person_id != pdi_id3.person_id
+ # The fake's state reflects the move: id1 stays, id2/id3 land on distinct new persons
+ assert fake._persons_by_distinct_id[(self.team.id, "id1")].id == person.id
+ moved_2 = fake._persons_by_distinct_id[(self.team.id, "id2")]
+ moved_3 = fake._persons_by_distinct_id[(self.team.id, "id3")]
+ assert moved_2.id != person.id
+ assert moved_3.id != person.id
+ assert moved_2.id != moved_3.id
# Original person keeps its properties when main_distinct_id is provided
person.refresh_from_db()
assert person.properties == {"email": "[email protected]", "name": "Test"}
- # New persons have empty properties
- new_person_2 = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
- new_person_3 = Person.objects.get(team_id=self.team.id, id=pdi_id3.person_id)
- assert new_person_2.properties == {}
- assert new_person_3.properties == {}
-
assert mock_create_pdi.call_count == 2
assert mock_create_person.call_count == 2
- def test_split_without_main_distinct_id_clears_properties(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["id1", "id2"],
- mock_create_pdi,
- mock_create_person,
- properties={"email": "[email protected]"},
- )
+ def test_split_does_not_write_orm(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2", "id3"], mock_create_pdi, mock_create_person)
- person.split_person(main_distinct_id=None)
+ person.split_person(main_distinct_id="id1")
- person.refresh_from_db()
- assert person.properties == {}
+ # The write went through the RPC — local DB rows are untouched
+ for did in ["id1", "id2", "id3"]:
+ pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=did)
+ assert pdi.person_id == person.id
+ assert Person.objects.filter(team_id=self.team.id).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
+ def test_split_without_main_distinct_id_keeps_properties(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(
+ fake,
+ ["id1", "id2"],
+ mock_create_pdi,
+ mock_create_person,
+ properties={"email": "[email protected]"},
+ )
- def test_split_with_max_splits(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["id1", "id2", "id3", "id4"], mock_create_pdi, mock_create_person
- )
+ person.split_person(main_distinct_id=None)
+
+ # First distinct_id from the fetch becomes the main; only the rest are split
+ split_calls = fake.assert_called("split_person", times=1)
+ split_ids = set(split_calls[0].request.distinct_ids_to_split)
+ assert len(split_ids) == 1
+ assert split_ids == {"id2"}
- person.split_person(main_distinct_id="id1", max_splits=2)
+ person.refresh_from_db()
+ assert person.properties == {"email": "[email protected]"}
+
+ def test_split_with_max_splits(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2", "id3", "id4"], mock_create_pdi, mock_create_person)
- pdi_id1 = PersonDistinctId.objects.get(team=self.team, distinct_id="id1")
- pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- pdi_id3 = PersonDistinctId.objects.get(team=self.team, distinct_id="id3")
- pdi_id4 = PersonDistinctId.objects.get(team=self.team, distinct_id="id4")
+ person.split_person(main_distinct_id="id1", max_splits=2)
- assert pdi_id1.person_id == person.id
- assert pdi_id2.person_id == person.id
- assert pdi_id3.person_id != person.id
- assert pdi_id4.person_id != person.id
+ split_calls = fake.assert_called("split_person", times=1)
+ assert len(split_calls[0].request.distinct_ids_to_split) == 2
+ assert "id1" not in split_calls[0].request.distinct_ids_to_split
def test_split_single_distinct_id_is_noop(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["only_id"], mock_create_pdi, mock_create_person)
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["only_id"], mock_create_pdi, mock_create_person)
- person.split_person(main_distinct_id="only_id")
+ person.split_person(main_distinct_id="only_id")
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id="only_id")
- assert pdi.person_id == person.id
+ fake.assert_not_called("split_person")
mock_create_pdi.assert_not_called()
mock_create_person.assert_not_called()
- def test_split_sets_correct_person_version(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person, version=5)
-
- person.split_person(main_distinct_id="id1")
-
- pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
-
- assert new_person.version == 5 + 101
-
- def test_split_sets_correct_pdi_version(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person)
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- pdi.version = 3
- pdi.save()
- mock_create_pdi.reset_mock()
-
- person.split_person(main_distinct_id="id1")
+ def test_split_publishes_versions_from_rpc(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person, version=5)
- pdi.refresh_from_db()
- assert pdi.version == 3 + 101
+ person.split_person(main_distinct_id="id1")
- def test_split_creates_deterministic_uuids(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person)
+ assert mock_create_person.call_count == 1
+ assert mock_create_person.call_args.kwargs["version"] == 5 + 101
+ assert mock_create_pdi.call_count == 1
+ assert mock_create_pdi.call_args.kwargs["version"] == 101 # PDI version 0 + 101
- person.split_person(main_distinct_id="id1")
+ def test_split_publishes_deterministic_uuids(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person)
- pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
+ person.split_person(main_distinct_id="id1")
- expected_uuid = uuidFromDistinctId(self.team.id, "id2")
- assert new_person.uuid == expected_uuid
+ expected_uuid = str(uuidFromDistinctId(self.team.id, "id2"))
+ assert mock_create_person.call_args.kwargs["uuid"] == expected_uuid
+ assert mock_create_pdi.call_args.kwargs["person_id"] == expected_uuid
def test_split_publishes_correct_kafka_messages(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2", "id3"], mock_create_pdi, mock_create_person)
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2", "id3"], mock_create_pdi, mock_create_person)
- person.split_person(main_distinct_id="id1")
+ person.split_person(main_distinct_id="id1")
assert mock_create_pdi.call_count == 2
assert mock_create_person.call_count == 2
@@ -179,285 +176,180 @@ class TestSplitPerson(BaseTest):
for call in mock_create_person.call_args_list:
assert call.kwargs["team_id"] == self.team.id
- def test_split_rolls_back_on_failure(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2", "id3"], mock_create_pdi, mock_create_person)
+ def test_split_pre_existing_person_keeps_created_at_and_bumps_version(self, mock_create_pdi, mock_create_person):
+ # A pre-existing split target (e.g. from a previous partial run) keeps
+ # its original created_at but gets the new version; the Kafka message
+ # must carry both so ClickHouse converges on the Postgres state.
+ original_created_at = datetime(2020, 1, 2, 3, 4, 5, tzinfo=UTC)
- original_pdi_ids = {
- did: PersonDistinctId.objects.get(team=self.team, distinct_id=did).person_id
- for did in ["id1", "id2", "id3"]
- }
- original_person_count = Person.objects.filter(team_id=self.team.id).count()
-
- with patch.object(PersonDistinctId.objects, "bulk_update", side_effect=Exception("simulated failure")):
- with self.assertRaises(Exception, msg="simulated failure"):
- person.split_person(main_distinct_id="id1")
-
- # All PDIs should still point to the original person
- for did in ["id1", "id2", "id3"]:
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=did)
- assert pdi.person_id == original_pdi_ids[did]
-
- # No new persons should have been committed
- assert Person.objects.filter(team_id=self.team.id).count() == original_person_count
-
- def test_split_updates_version_on_pre_existing_person(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person, version=5)
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person, version=5)
+ pre_existing_uuid = str(uuidFromDistinctId(self.team.id, "id2"))
+ fake.add_person(
+ team_id=self.team.id,
+ person_id=999_999,
+ uuid=pre_existing_uuid,
+ created_at=int(original_created_at.timestamp() * 1000),
+ )
- # Pre-create a person with the UUID that split would generate, simulating a previous partial run
- expected_uuid = uuidFromDistinctId(self.team.id, "id2")
- pre_existing = Person.objects.create(
- team=self.team,
- uuid=expected_uuid,
- version=0,
- )
- mock_create_person.reset_mock()
- mock_create_pdi.reset_mock()
+ person.split_person(main_distinct_id="id1")
- person.split_person(main_distinct_id="id1")
+ assert fake._persons_by_uuid[(self.team.id, pre_existing_uuid)].version == 5 + 101
- # The pre-existing person's version should be updated to original_version + 101
- pre_existing.refresh_from_db()
- assert pre_existing.version == 5 + 101
+ assert mock_create_person.call_count == 1
+ assert mock_create_person.call_args.kwargs["uuid"] == pre_existing_uuid
+ assert mock_create_person.call_args.kwargs["version"] == 5 + 101
+ assert mock_create_person.call_args.kwargs["created_at"] == original_created_at
- # PDI should point to the pre-existing person
- pdi_id2 = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
- assert pdi_id2.person_id == pre_existing.id
+ def test_partial_split_moves_only_specified_distinct_ids(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(
+ fake,
+ ["keep1", "move1", "keep2", "move2", "keep3"],
+ mock_create_pdi,
+ mock_create_person,
+ properties={"email": "[email protected]", "name": "Mega"},
+ )
- # Kafka message should carry the updated version
- person_calls = [c for c in mock_create_person.call_args_list if c.kwargs.get("uuid") == str(expected_uuid)]
- assert len(person_calls) == 1
- assert person_calls[0].kwargs["version"] == 5 + 101
+ person.split_person(main_distinct_id=None, distinct_ids_to_split=["move1", "move2"])
- def test_partial_split_moves_only_specified_distinct_ids(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["keep1", "move1", "keep2", "move2", "keep3"],
- mock_create_pdi,
- mock_create_person,
- properties={"email": "[email protected]", "name": "Mega"},
- )
+ split_calls = fake.assert_called("split_person", times=1)
+ assert list(split_calls[0].request.distinct_ids_to_split) == ["move1", "move2"]
- person.split_person(main_distinct_id=None, distinct_ids_to_split=["move1", "move2"])
+ for did in ["keep1", "keep2", "keep3"]:
+ assert fake._persons_by_distinct_id[(self.team.id, did)].id == person.id
+ assert fake._persons_by_distinct_id[(self.team.id, "move1")].id != person.id
+ assert fake._persons_by_distinct_id[(self.team.id, "move2")].id != person.id
# Original person keeps its properties intact — this is the key partial-split guarantee.
person.refresh_from_db()
assert person.properties == {"email": "[email protected]", "name": "Mega"}
- # Kept distinct_ids remain on the original person.
- for did in ["keep1", "keep2", "keep3"]:
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=did)
- assert pdi.person_id == person.id
-
- # Moved distinct_ids each land on their own new person.
- pdi_move1 = PersonDistinctId.objects.get(team=self.team, distinct_id="move1")
- pdi_move2 = PersonDistinctId.objects.get(team=self.team, distinct_id="move2")
- assert pdi_move1.person_id != person.id
- assert pdi_move2.person_id != person.id
- assert pdi_move1.person_id != pdi_move2.person_id
-
assert mock_create_pdi.call_count == 2
assert mock_create_person.call_count == 2
def test_partial_split_rejects_unknown_distinct_id(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person)
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person)
- with self.assertRaises(ValueError):
- person.split_person(main_distinct_id=None, distinct_ids_to_split=["id1", "not_on_this_person"])
+ with self.assertRaises(KeyError):
+ person.split_person(main_distinct_id=None, distinct_ids_to_split=["id1", "not_on_this_person"])
- # Nothing should have moved.
- for did in ["id1", "id2"]:
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=did)
- assert pdi.person_id == person.id
mock_create_pdi.assert_not_called()
mock_create_person.assert_not_called()
def test_partial_split_ignores_main_distinct_id_and_max_splits(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["a", "b", "c", "d"],
- mock_create_pdi,
- mock_create_person,
- properties={"email": "[email protected]"},
- )
-
- # main_distinct_id and max_splits should both be ignored when the explicit list is given.
- person.split_person(main_distinct_id="a", max_splits=1, distinct_ids_to_split=["b", "c"])
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["a", "b", "c", "d"], mock_create_pdi, mock_create_person)
- person.refresh_from_db()
- assert person.properties == {"email": "[email protected]"}
+ # main_distinct_id and max_splits should both be ignored when the explicit list is given.
+ person.split_person(main_distinct_id="a", max_splits=1, distinct_ids_to_split=["b", "c"])
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="a").person_id == person.id
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="d").person_id == person.id
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="b").person_id != person.id
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="c").person_id != person.id
+ split_calls = fake.assert_called("split_person", times=1)
+ assert list(split_calls[0].request.distinct_ids_to_split) == ["b", "c"]
def test_partial_split_empty_list_is_noop(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(
- ["id1", "id2"],
- mock_create_pdi,
- mock_create_person,
- properties={"email": "[email protected]"},
- )
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person)
- person.split_person(main_distinct_id=None, distinct_ids_to_split=[])
+ person.split_person(main_distinct_id=None, distinct_ids_to_split=[])
- person.refresh_from_db()
- assert person.properties == {"email": "[email protected]"}
- for did in ["id1", "id2"]:
- assert PersonDistinctId.objects.get(team=self.team, distinct_id=did).person_id == person.id
+ fake.assert_not_called("split_person")
mock_create_pdi.assert_not_called()
mock_create_person.assert_not_called()
def test_partial_split_dedupes_duplicates(self, mock_create_pdi, mock_create_person):
- person = self._create_person_with_distinct_ids(["id1", "id2"], mock_create_pdi, mock_create_person)
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person)
- person.split_person(main_distinct_id=None, distinct_ids_to_split=["id2", "id2"])
+ person.split_person(main_distinct_id=None, distinct_ids_to_split=["id2", "id2"])
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="id1").person_id == person.id
- assert PersonDistinctId.objects.get(team=self.team, distinct_id="id2").person_id != person.id
+ split_calls = fake.assert_called("split_person", times=1)
+ assert list(split_calls[0].request.distinct_ids_to_split) == ["id2"]
assert mock_create_pdi.call_count == 1
assert mock_create_person.call_count == 1
- def test_split_many_distinct_ids(self, mock_create_pdi, mock_create_person):
- distinct_ids = ["main"] + [f"id_{i}" for i in range(100)]
- person = self._create_person_with_distinct_ids(distinct_ids, mock_create_pdi, mock_create_person)
-
- person.split_person(main_distinct_id="main")
-
- pdi_main = PersonDistinctId.objects.get(team=self.team, distinct_id="main")
- assert pdi_main.person_id == person.id
-
- split_person_ids = set()
- for i in range(100):
- pdi = PersonDistinctId.objects.get(team=self.team, distinct_id=f"id_{i}")
- assert pdi.person_id != person.id
- split_person_ids.add(pdi.person_id)
-
- assert len(split_person_ids) == 100
+ def test_split_paginates_fetch_and_splits(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ person = self._setup_person(fake, ["main", "a", "b", "c", "d", "e"], mock_create_pdi, mock_create_person)
- assert mock_create_pdi.call_count == 100
- assert mock_create_person.call_count == 100
+ with patch("posthog.models.person.person.PERSONHOG_SPLIT_BATCH_SIZE", 2):
+ person.split_person(main_distinct_id="main")
+ # Each page fetches limit=3 (batch_size+1), splits up to 2 non-main IDs,
+ # then the next fetch returns a smaller set because the split IDs are gone.
+ split_calls = fake.assert_called("split_person")
+ total_split = sum(len(call.request.distinct_ids_to_split) for call in split_calls)
+ assert total_split == 5
-@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."""
+ # All fetch calls used the limit
+ fetch_calls = [c for c in fake.calls if c.method == "get_distinct_ids_for_person"]
+ for call in fetch_calls:
+ assert call.request.limit == 3 # PERSONHOG_SPLIT_BATCH_SIZE + 1
- 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
- )
+ assert mock_create_person.call_count == 5
+ assert mock_create_pdi.call_count == 5
+ def test_split_raises_when_rpc_fails(self, mock_create_pdi, mock_create_person):
+ # No ORM fallback: an RPC failure propagates and nothing is published.
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")
+ person = self._setup_person(fake, ["id1", "id2"], mock_create_pdi, mock_create_person)
- fake.assert_called("get_person", times=1)
- fake.assert_called("get_distinct_ids_for_person", times=1)
+ def failing_split(request, timeout=None):
+ raise RuntimeError("simulated gRPC failure")
- 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
+ fake.split_person = failing_split
- new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
- assert new_person.version == 20 + 101
+ with self.assertRaises(RuntimeError):
+ person.split_person(main_distinct_id="id1")
- 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)
+ # Local DB rows are untouched and no Kafka messages were published
+ pdi = PersonDistinctId.objects.get(team=self.team, distinct_id="id2")
+ assert pdi.person_id == person.id
+ mock_create_pdi.assert_not_called()
+ mock_create_person.assert_not_called()
+ def test_split_from_stub_person_keeps_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."""
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,
+ person = self._setup_person(
+ fake,
+ ["id1", "id2"],
+ mock_create_pdi,
+ mock_create_person,
+ properties={"email": "[email protected]"},
)
- # 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
+ stub = Person(pk=person.id, team_id=self.team.id)
+ stub.split_person(main_distinct_id=None)
- person.split_person(main_distinct_id="id1")
+ split_calls = fake.assert_called("split_person", times=1)
+ assert list(split_calls[0].request.distinct_ids_to_split) == ["id2"]
- assert call_count == 1
+ person.refresh_from_db()
+ assert person.properties == {"email": "[email protected]"}
- 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
+ def test_split_person_not_found_in_personhog(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client():
+ stub = Person(pk=999_999, team_id=self.team.id)
+ with self.assertRaises(ValueError, msg="Person not found"):
+ stub.split_person(main_distinct_id="anything")
- new_person = Person.objects.get(team_id=self.team.id, id=pdi_id2.person_id)
- assert new_person.version == 3 + 101
+ mock_create_pdi.assert_not_called()
+ mock_create_person.assert_not_called()
- 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]"},
- )
+ def test_max_splits_caps_across_pages(self, mock_create_pdi, mock_create_person):
+ with fake_personhog_client() as fake:
+ ids = ["main"] + [f"id_{i}" for i in range(10)]
+ person = self._setup_person(fake, ids, mock_create_pdi, mock_create_person)
- stub = Person(pk=person.id, team_id=self.team.id)
- stub.split_person(main_distinct_id=None)
+ with patch("posthog.models.person.person.PERSONHOG_SPLIT_BATCH_SIZE", 3):
+ person.split_person(main_distinct_id="main", max_splits=5)
- person.refresh_from_db()
- assert person.properties == {}
+ split_calls = fake.assert_called("split_person")
+ total_split = sum(len(call.request.distinct_ids_to_split) for call in split_calls)
+ assert total_split == 5
- 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
+ assert mock_create_person.call_count == 5
+ assert mock_create_pdi.call_count == 5
diff --git a/posthog/personhog_client/README.md b/posthog/personhog_client/README.md
index 67dc37956a6e..5f783d47dac6 100644
--- a/posthog/personhog_client/README.md
+++ b/posthog/personhog_client/README.md
@@ -73,6 +73,9 @@ The `PersonHogClient` in `client.py` exposes typed methods for every RPC:
**Person deletes:**
`delete_persons`, `delete_persons_batch_for_team`
+**Person split:**
+`split_person` — splits distinct_ids off a person onto new persons (max 250 per request); the sole write path for person splits, with no ORM fallback
+
**Cohort membership:**
`check_cohort_membership`, `count_cohort_members`, `insert_cohort_members`,
`delete_cohort_member`, `delete_cohort_members_bulk`, `list_cohort_member_ids`
diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.py
index 81990d4329ff..d27b6c54069b 100644
--- a/posthog/personhog_client/fake_client.py
+++ b/posthog/personhog_client/fake_client.py
@@ -19,12 +19,14 @@ boundaries are exercised end-to-end. The gate is forced ON by default
from __future__ import annotations
import json
+import time
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any
from unittest.mock import patch
+from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.personhog_client.proto.generated.personhog.types.v1 import cohort_pb2, group_pb2, person_pb2
@@ -67,6 +69,9 @@ class FakePersonHogClient:
# keyed by (cohort_id, person_id) -> True
self._cohort_members: dict[tuple[int, int], bool] = {}
+ # synthetic ids for persons created by split_person
+ self._next_split_person_id = 1_000_000_000
+
# ── Builder methods ──────────────────────────────────────────────
def add_person(
@@ -81,6 +86,7 @@ class FakePersonHogClient:
is_identified: bool = False,
is_user_id: bool | None = None,
distinct_ids: list[str] | None = None,
+ distinct_id_versions: dict[str, int] | None = None,
) -> person_pb2.Person:
person = person_pb2.Person(
id=person_id,
@@ -99,7 +105,7 @@ class FakePersonHogClient:
for did in distinct_ids or []:
self._persons_by_distinct_id[(team_id, did)] = person
self._distinct_ids.setdefault((team_id, person_id), []).append(
- person_pb2.DistinctIdWithVersion(distinct_id=did, version=0)
+ person_pb2.DistinctIdWithVersion(distinct_id=did, version=(distinct_id_versions or {}).get(did, 0))
)
return person
@@ -580,8 +586,63 @@ class FakePersonHogClient:
def split_person(
self, request: person_pb2.SplitPersonRequest, timeout: float | None = None
) -> person_pb2.SplitPersonResponse:
+ """Stateful mirror of the real RPC: validates ownership, creates new
+ persons with deterministic UUIDv5s (preserving created_at for
+ pre-existing ones), moves the distinct_ids, and bumps versions by 101.
+ Results are returned in request order, like the real service.
+ """
self.calls.append(_Call("split_person", request))
- return person_pb2.SplitPersonResponse(splits=[])
+
+ key = (request.team_id, request.person_id)
+ source = self._persons_by_id.get(key)
+ if source is None:
+ raise KeyError(f"person_id={request.person_id} not found (team_id={request.team_id})")
+
+ mappings = self._distinct_ids.get(key, [])
+ mapping_by_did = {m.distinct_id: m for m in mappings}
+ unknown = [did for did in request.distinct_ids_to_split if did not in mapping_by_did]
+ if unknown:
+ raise KeyError(
+ f"distinct_ids {unknown} do not belong to person_id={request.person_id} (team_id={request.team_id})"
+ )
+
+ new_person_version = source.version + 101
+ splits: list[person_pb2.SplitResult] = []
+ for did in request.distinct_ids_to_split:
+ new_uuid = str(uuidFromDistinctId(request.team_id, did))
+
+ existing = self._persons_by_uuid.get((request.team_id, new_uuid))
+ if existing is not None:
+ existing.version = new_person_version
+ new_person = existing
+ else:
+ self._next_split_person_id += 1
+ new_person = self.add_person(
+ team_id=request.team_id,
+ person_id=self._next_split_person_id,
+ uuid=new_uuid,
+ version=new_person_version,
+ created_at=int(time.time() * 1000),
+ )
+
+ pdi_version = (mapping_by_did[did].version or 0) + 101
+ mappings.remove(mapping_by_did[did])
+ target_mappings = self._distinct_ids.setdefault((request.team_id, new_person.id), [])
+ target_mappings[:] = [m for m in target_mappings if m.distinct_id != did]
+ target_mappings.append(person_pb2.DistinctIdWithVersion(distinct_id=did, version=pdi_version))
+ self._persons_by_distinct_id[(request.team_id, did)] = new_person
+
+ splits.append(
+ person_pb2.SplitResult(
+ distinct_id=did,
+ new_person_uuid=new_uuid,
+ new_person_version=new_person_version,
+ pdi_version=pdi_version,
+ new_person_created_at_ms=new_person.created_at,
+ )
+ )
+
+ return person_pb2.SplitPersonResponse(splits=splits)
# ── Assertion helpers ────────────────────────────────────────────
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index bccedfb17445..4504f892b274 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -234,7 +234,7 @@ export interface PersonDeletePropertyRequestApi {
export interface PersonSplitRequestApi {
/**
- * The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is used and the person's properties are wiped. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.
+ * The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.
* @nullable
*/
main_distinct_id?: string | null
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index f018bb86e15a..81c7c955f53a 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -320,7 +320,9 @@ export const getPersonsSplitCreateUrl = (projectId: string, id: string, params?:
* Split distinct_ids off a merged person. Two mutually exclusive modes:
*
* - **`distinct_ids_to_split`** (recommended for surgical edits): moves only the listed distinct_ids off this person onto new single-id persons. The original person keeps every other distinct_id and its properties.
- * - **`main_distinct_id`** (legacy semantics): keeps only the specified distinct_id on this person; moves every *other* distinct_id off onto its own new person. If omitted, the person's properties are wiped and the first distinct_id is treated as the one to keep.
+ * - **`main_distinct_id`**: keeps only the specified distinct_id on this person; moves every *other* distinct_id off onto its own new person. If omitted, the first distinct_id is kept.
+ *
+ * The original person always retains its properties. To clear individual properties afterward, use the `delete_property` endpoint.
*
* The split runs asynchronously: a 201 response means the task was enqueued. Newly-created split-off persons get a deterministic UUID derived from `(team_id, distinct_id)`, so they can be located client-side without polling. If you need to delete a split-off person after this call, prefer looking it up by that deterministic UUID rather than by distinct_id, since the latter still resolves to the original merged person until the async task completes.
*/
diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.ts
index da2ce6a91980..936aac81f73b 100644
--- a/products/persons/frontend/generated/api.zod.ts
+++ b/products/persons/frontend/generated/api.zod.ts
@@ -42,7 +42,9 @@ export const PersonsDeletePropertyCreateBody = /* @__PURE__ */ zod.object({
* Split distinct_ids off a merged person. Two mutually exclusive modes:
*
* - **`distinct_ids_to_split`** (recommended for surgical edits): moves only the listed distinct_ids off this person onto new single-id persons. The original person keeps every other distinct_id and its properties.
- * - **`main_distinct_id`** (legacy semantics): keeps only the specified distinct_id on this person; moves every *other* distinct_id off onto its own new person. If omitted, the person's properties are wiped and the first distinct_id is treated as the one to keep.
+ * - **`main_distinct_id`**: keeps only the specified distinct_id on this person; moves every *other* distinct_id off onto its own new person. If omitted, the first distinct_id is kept.
+ *
+ * The original person always retains its properties. To clear individual properties afterward, use the `delete_property` endpoint.
*
* The split runs asynchronously: a 201 response means the task was enqueued. Newly-created split-off persons get a deterministic UUID derived from `(team_id, distinct_id)`, so they can be located client-side without polling. If you need to delete a split-off person after this call, prefer looking it up by that deterministic UUID rather than by distinct_id, since the latter still resolves to the original merged person until the async task completes.
*/
@@ -51,7 +53,7 @@ export const PersonsSplitCreateBody = /* @__PURE__ */ zod.object({
.string()
.nullish()
.describe(
- "The distinct_id to \*\*keep\*\* on this person; every \*other\* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is used and the person's properties are wiped. To surgically \*remove\* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined."
+ 'The distinct_id to \*\*keep\*\* on this person; every \*other\* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically \*remove\* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.'
),
distinct_ids_to_split: zod
.array(zod.string())
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0927cdf03ae4..da536db2f8af 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38750,7 +38750,7 @@ export namespace Schemas {
export interface PersonSplitRequest {
/**
- * The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is used and the person's properties are wiped. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.
+ * The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.
* @nullable
*/
main_distinct_id?: string | null;