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): wire in repair distinct id (#64698)

Zach Brown49c0d490a5d2
diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.py
index 9e687729e8ef..8efff3bfcf69 100644
--- a/posthog/models/person/deletion.py
+++ b/posthog/models/person/deletion.py
@@ -62,7 +62,7 @@ def _get_version_for_distinct_id(team_id: int, distinct_id: str) -> int:
def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, int]]):
- # Determine the correct database for PersonDistinctId writes (handles persons_db_writer routing in production)
+ # DB alias for the ORM-fallback person-version write below (handles persons_db_writer routing in production)
db_alias = router.db_for_write(PersonDistinctId) or "default"
reset_person_uuids: set[str] = set()
@@ -72,12 +72,14 @@ def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, in
# since they no longer belong to deleted persons
# it's safer to throw and exit if anything went wrong
- with transaction.atomic(using=db_alias):
- person_distinct_id = _update_distinct_id_in_postgres(distinct_id, version, team_id)
+ # No transaction here: the write goes through personhog (an external RPC that
+ # can't join a Postgres transaction) or, on fallback, an ORM write that scopes
+ # its own atomic block. See _set_distinct_id_version_floor_via_orm.
+ person = _update_distinct_id_in_postgres(distinct_id, version, team_id)
# Update ClickHouse via Kafka message
- if person_distinct_id:
- person_uuid = str(person_distinct_id.person.uuid)
+ if person:
+ person_uuid = str(person.uuid)
create_person_distinct_id(
team_id=team_id,
@@ -92,21 +94,64 @@ def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, in
# making the person invisible to analytics queries
if person_uuid not in reset_person_uuids:
reset_person_uuids.add(person_uuid)
- _reset_person_in_clickhouse(team_id, person_distinct_id.person, db_alias)
+ _reset_person_in_clickhouse(team_id, person, db_alias)
-def _update_distinct_id_in_postgres(distinct_id: str, version: int, team_id: int) -> Optional[PersonDistinctId]:
- person_distinct_id = (
- PersonDistinctId.objects.filter(team_id=team_id, distinct_id=distinct_id) # nosemgrep: no-direct-persons-db-orm
- .select_related("person")
- .first() # nosemgrep: no-direct-persons-db-orm
+def _update_distinct_id_in_postgres(distinct_id: str, version: int, team_id: int) -> Optional[Person]:
+ """Raise the distinct_id's version to at least `version` and return its person.
+
+ Routes through SetPersonDistinctIdVersionFloor (guarded — never lowers the
+ version), falling back to a direct ORM read+save. Returns None when the
+ distinct_id doesn't exist (it hasn't been re-used yet).
+ """
+ from posthog.models.person.util import _personhog_routed
+
+ return _personhog_routed(
+ "set_person_distinct_id_version_floor",
+ lambda: _set_distinct_id_version_floor_via_personhog(team_id, distinct_id, version),
+ lambda: _set_distinct_id_version_floor_via_orm(team_id, distinct_id, version),
+ team_id=team_id,
+ )
+
+
+def _set_distinct_id_version_floor_via_personhog(team_id: int, distinct_id: str, version: int) -> Optional[Person]:
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.converters import proto_person_to_model
+ from posthog.personhog_client.proto import SetPersonDistinctIdVersionFloorRequest
+
+ client = get_personhog_client()
+ if client is None:
+ raise RuntimeError("personhog client not configured")
+
+ resp = client.set_person_distinct_id_version_floor(
+ SetPersonDistinctIdVersionFloorRequest(team_id=team_id, distinct_id=distinct_id, min_version=version)
)
- if person_distinct_id is None:
+ if not resp.HasField("person"):
logger.info(f"Distinct id {distinct_id} hasn't been re-used yet and can cause problems in the future")
return None
- person_distinct_id.version = version
- person_distinct_id.save()
- return person_distinct_id
+ return proto_person_to_model(resp.person, distinct_ids=[distinct_id])
+
+
+def _set_distinct_id_version_floor_via_orm(team_id: int, distinct_id: str, version: int) -> Optional[Person]:
+ # Scope the transaction to exactly this local read+write. The personhog path makes
+ # no Postgres writes, so the caller must not wrap the routed call in an atomic block.
+ db_alias = router.db_for_write(PersonDistinctId) or "default"
+ with transaction.atomic(using=db_alias):
+ person_distinct_id = (
+ PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm
+ team_id=team_id, distinct_id=distinct_id
+ )
+ .select_related("person")
+ .first()
+ )
+ if person_distinct_id is None:
+ logger.info(f"Distinct id {distinct_id} hasn't been re-used yet and can cause problems in the future")
+ return None
+ # Guarded floor: never lower the stored version (matches the RPC semantics).
+ if person_distinct_id.version is None or person_distinct_id.version < version:
+ person_distinct_id.version = version
+ person_distinct_id.save()
+ return person_distinct_id.person
def _get_person_version_if_deleted(team_id: int, person_uuid: str) -> Optional[int]:
@@ -136,14 +181,9 @@ def _reset_person_in_clickhouse(team_id: int, person: Person, db_alias: str) ->
new_version = max_version + 100
logger.info(f"Resetting person {person_uuid} in ClickHouse to version {new_version}")
- # Update Postgres version so future updates from the plugin-server
- # (which reads version from Postgres) won't be ignored by ClickHouse
- # nosemgrep: no-direct-persons-db-orm
- Person.objects.using(db_alias).filter(
- pk=person.pk, version__lt=new_version
- ).update( # nosemgrep: no-direct-persons-db-orm
- version=new_version
- ) # nosemgrep: no-direct-persons-db-orm
+ # Raise the Postgres version so future updates from the plugin-server (which
+ # reads version from Postgres) won't be ignored by ClickHouse.
+ _set_person_version_floor(team_id, person.pk, new_version, db_alias)
create_person(
uuid=person_uuid,
@@ -154,3 +194,39 @@ def _reset_person_in_clickhouse(team_id: int, person: Person, db_alias: str) ->
is_deleted=False,
created_at=person.created_at,
)
+
+
+def _set_person_version_floor(team_id: int, person_id: int, new_version: int, db_alias: str) -> None:
+ """Raise a person's version to at least `new_version` (guarded — never lowers).
+
+ Routes through SetPersonVersionFloor, falling back to a guarded ORM update.
+ """
+ from posthog.models.person.util import _personhog_routed
+
+ _personhog_routed(
+ "set_person_version_floor",
+ lambda: _set_person_version_floor_via_personhog(team_id, person_id, new_version),
+ lambda: _set_person_version_floor_via_orm(person_id, new_version, db_alias),
+ team_id=team_id,
+ )
+
+
+def _set_person_version_floor_via_personhog(team_id: int, person_id: int, new_version: int) -> None:
+ from posthog.personhog_client.client import get_personhog_client
+ from posthog.personhog_client.proto import SetPersonVersionFloorRequest
+
+ client = get_personhog_client()
+ if client is None:
+ raise RuntimeError("personhog client not configured")
+
+ client.set_person_version_floor(
+ SetPersonVersionFloorRequest(team_id=team_id, person_id=person_id, min_version=new_version)
+ )
+
+
+def _set_person_version_floor_via_orm(person_id: int, new_version: int, db_alias: str) -> None:
+ Person.objects.using(db_alias).filter( # nosemgrep: no-direct-persons-db-orm
+ pk=person_id, version__lt=new_version
+ ).update( # nosemgrep: no-direct-persons-db-orm
+ version=new_version
+ )
diff --git a/posthog/models/person/test/test_reset_distinct_ids_personhog.py b/posthog/models/person/test/test_reset_distinct_ids_personhog.py
new file mode 100644
index 000000000000..e004d26ae267
--- /dev/null
+++ b/posthog/models/person/test/test_reset_distinct_ids_personhog.py
@@ -0,0 +1,107 @@
+"""Tests for the undelete-repair version writes via personhog RPC.
+
+Covers routing/fallback for the two persons-DB writes in the repair flow:
+- _update_distinct_id_in_postgres → SetPersonDistinctIdVersionFloor
+- _set_person_version_floor (used by _reset_person_in_clickhouse) → SetPersonVersionFloor
+"""
+
+from uuid import uuid4
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.person.deletion import _set_person_version_floor, _update_distinct_id_in_postgres
+from posthog.personhog_client.fake_client import fake_personhog_client
+
+
+class TestUpdateDistinctIdInPostgresRouting(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("personhog_success", True, None),
+ ("personhog_error_falls_back_to_orm", True, RuntimeError("grpc timeout")),
+ ("gate_off_uses_orm_directly", False, None),
+ ]
+ )
+ @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")
+ def test_routing(self, _name, gate_on, grpc_exception, mock_orm):
+ mock_orm.return_value = None
+ with fake_personhog_client(gate_enabled=gate_on) as fake:
+ if grpc_exception is not None:
+ fake.set_person_distinct_id_version_floor = MagicMock(side_effect=grpc_exception)
+
+ _update_distinct_id_in_postgres("did-1", 100, team_id=1)
+
+ if gate_on and grpc_exception is None:
+ mock_orm.assert_not_called()
+ else:
+ mock_orm.assert_called_once_with(1, "did-1", 100)
+
+ @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")
+ def test_personhog_path_returns_converted_person(self, mock_orm):
+ person_uuid = str(uuid4())
+ with fake_personhog_client(gate_enabled=True) as fake:
+ fake.add_person(
+ team_id=1,
+ person_id=42,
+ uuid=person_uuid,
+ properties={"email": "[email protected]"},
+ distinct_ids=["did-1"],
+ )
+
+ result = _update_distinct_id_in_postgres("did-1", 100, team_id=1)
+
+ calls = fake.assert_called("set_person_distinct_id_version_floor")
+ assert calls[0].request.team_id == 1
+ assert calls[0].request.distinct_id == "did-1"
+ assert calls[0].request.min_version == 100
+
+ assert result is not None
+ assert str(result.uuid) == person_uuid
+ assert result.properties == {"email": "[email protected]"}
+ mock_orm.assert_not_called()
+
+ @patch("posthog.models.person.deletion._set_distinct_id_version_floor_via_orm")
+ def test_personhog_returns_none_when_distinct_id_absent(self, mock_orm):
+ with fake_personhog_client(gate_enabled=True):
+ # Fake not seeded → no person for this distinct_id.
+ result = _update_distinct_id_in_postgres("never-used", 100, team_id=1)
+
+ assert result is None
+ mock_orm.assert_not_called()
+
+
+class TestSetPersonVersionFloorRouting(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("personhog_success", True, None),
+ ("personhog_error_falls_back_to_orm", True, RuntimeError("grpc timeout")),
+ ("gate_off_uses_orm_directly", False, None),
+ ]
+ )
+ @patch("posthog.models.person.deletion._set_person_version_floor_via_orm")
+ def test_routing(self, _name, gate_on, grpc_exception, mock_orm):
+ with fake_personhog_client(gate_enabled=gate_on) as fake:
+ if grpc_exception is not None:
+ fake.set_person_version_floor = MagicMock(side_effect=grpc_exception)
+
+ _set_person_version_floor(1, 42, 500, "default")
+
+ if gate_on and grpc_exception is None:
+ mock_orm.assert_not_called()
+ else:
+ mock_orm.assert_called_once_with(42, 500, "default")
+
+ @patch("posthog.models.person.deletion._set_person_version_floor_via_orm")
+ def test_personhog_path_calls_rpc_with_floor(self, mock_orm):
+ with fake_personhog_client(gate_enabled=True) as fake:
+ _set_person_version_floor(1, 42, 500, "default")
+
+ calls = fake.assert_called("set_person_version_floor")
+ assert calls[0].request.team_id == 1
+ assert calls[0].request.person_id == 42
+ assert calls[0].request.min_version == 500
+
+ mock_orm.assert_not_called()