: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): reset a deleted person through the divergence repair (#112091)
Eli Reisman4cd4496664a9
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 45e77e714128..d3f311067a82 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -61,7 +61,7 @@ from posthog.models.person.bulk_delete import (queue_person_recording_deletion,resolve_persons_for_deletion,)-from posthog.models.person.deletion import reset_deleted_person_distinct_ids+from posthog.models.person.divergence import repair_distinct_idfrom posthog.models.person.missing_person import MissingPersonfrom posthog.models.person.util import (get_distinct_ids_for_persons,@@ -100,6 +100,8 @@ logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)DEFAULT_PAGE_LIMIT = 100+# A reset request waits this long for Kafka to confirm the republished rows; a rerun of the reset is safe.+RESET_DISTINCT_ID_DELIVERY_TIMEOUT_SECONDS = 10# The id reaches the ClickHouse query id and every query_log row for the request, so bound it.# Cancelling matches on `query_id LIKE '<team_id>_<client_query_id>%'`, which makes an id holding@@ -1726,7 +1728,17 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not distinct_id or not isinstance(distinct_id, str):raise ValidationError(detail="distinct_id is required")- reset_deleted_person_distinct_ids(self.team_id, distinct_id)+ summary = repair_distinct_id(+ self.team_id, distinct_id, delivery_timeout_seconds=RESET_DISTINCT_ID_DELIVERY_TIMEOUT_SECONDS+ )+ if summary is not None:+ logger.info(+ "person_reset_distinct_id",+ team_id=self.team_id,+ person_outcomes=summary.person_outcomes,+ mapping_outcomes=summary.mapping_outcomes,+ undelivered=summary.undelivered,+ )return response.Response(status=202)diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 769abc33cbac..c043708b397b 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -28,7 +28,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.exceptions import ValidationError-import posthog.models.person.deletion+import posthog.models.person.divergencefrom posthog.api.person import tag_client_query_idfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags@@ -2399,8 +2399,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert person_after.version is not None and person_after.version > 105@mock.patch(- f"{posthog.models.person.deletion.__name__}.create_person_distinct_id",- wraps=posthog.models.person.deletion.create_person_distinct_id,+ f"{posthog.models.person.divergence.__name__}.create_person_distinct_id",+ wraps=posthog.models.person.divergence.create_person_distinct_id,)@pytest.mark.flaky(reruns=2)def test_reset_person_distinct_id_not_found(self, mocked_ch_call):@@ -2679,6 +2679,23 @@ class TestPersonBatchRestrictedProperties(ClickhouseTestMixin, APIBaseTest):team=self.team, property_definition=restricted, access_level=PropertyAccessLevel.NONE.value)+ @mock.patch(f"{posthog.models.person.divergence.__name__}.capture_internal")+ def test_reset_does_not_copy_a_restricted_property_into_an_event(self, capture: mock.MagicMock) -> None:+ person = create_person(team=self.team, properties={"email": "[email protected]"}, version=5, uuid=str(uuid4()))+ add_distinct_id(person=person, distinct_id="target", version=0)+ create_person_in_ch(+ uuid=str(person.uuid), team_id=self.team.pk, version=10, properties={"email": "[email protected]", "ssn": "1"}+ )++ response = self.client.post(+ f"/api/projects/{self.team.pk}/persons/reset_person_distinct_id/", {"distinct_id": "target"}+ )++ assert response.status_code == status.HTTP_202_ACCEPTED+ capture.assert_not_called()+ person_after = get_person_by_uuid(self.team.pk, str(person.uuid))+ assert person_after is not None and person_after.version == 5+@parameterized.expand(["batch_by_distinct_ids", "batch_by_uuids"])def test_batch_endpoint_strips_restricted_person_properties(self, action: str) -> None:person = _create_person(diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex d569f449a67b..5657cc688ab2 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -413,7 +413,7 @@ class RevivedDistinctIdsTable(SnapshotTable):"""Snapshotted distinct ids that no longer qualify for deletion.A mapping can come back the same way a person can: ingestion re-captures a tombstoned- distinct id, or reset_deleted_person_distinct_ids republishes it at a higher version. The+ distinct id, or a `person_divergence repair` republishes it at a higher version. Thesnapshot froze the reason each key qualified, so without this the delete would strip everyversion of a key that is live again, including the new row."""diff --git a/posthog/management/commands/fix_orphaned_ch_persons.py b/posthog/management/commands/fix_orphaned_ch_persons.pyindex ed3188b70391..33b03f1cdd0a 100644--- a/posthog/management/commands/fix_orphaned_ch_persons.py+++ b/posthog/management/commands/fix_orphaned_ch_persons.py@@ -22,8 +22,8 @@ _FLUSH_TIMEOUT_SECONDS = 5 * 60class Command(BaseCommand):help = (- "Tombstone ClickHouse person rows that are live in ClickHouse but absent from the persons DB "- "(the inverse of fix_person_distinct_ids_after_delete). Dry-run by default."+ "Tombstone ClickHouse person rows that are live in ClickHouse but absent from the persons DB. "+ "Dry-run by default.")def add_arguments(self, parser):@@ -124,7 +124,7 @@ def _log_result(team_id: int, result: OrphanRepairResult) -> None:if result.reverse_drift_mappings:logger.warning("Found distinct_ids tombstoned in ClickHouse whose person is still live in the persons DB "- "(reverse drift). Repair these with fix_person_distinct_ids_after_delete, not this command.",+ "(reverse drift). Repair these with person_divergence repair, not this command.",team_id=team_id,reverse_drift=result.reverse_drift_mappings,)diff --git a/posthog/management/commands/fix_person_distinct_ids_after_delete.py b/posthog/management/commands/fix_person_distinct_ids_after_delete.pydeleted file mode 100644index 21718308e9b1..000000000000--- a/posthog/management/commands/fix_person_distinct_ids_after_delete.py+++ /dev/null@@ -1,52 +0,0 @@-import logging--from django.core.management.base import BaseCommand--import structlog--from posthog.kafka_client.routing import flush_all_producers-from posthog.models.person.deletion import reset_all_deleted_person_distinct_ids, reset_deleted_person_distinct_ids--logger = structlog.get_logger(__name__)-logger.setLevel(logging.INFO)---class Command(BaseCommand):- help = "Fix state for person distinct IDs in ClickHouse after person deletion and id re-use for a single team"-- def add_arguments(self, parser):- parser.add_argument("--team-id", default=None, type=int, help="Specify a team to fix data for.")- parser.add_argument(- "--new-version", default=2500, type=int, help="New version value to use when in --all-distinct-ids mode."- )- parser.add_argument("--distinct-id", default=None, type=str, help="Specify a distinct ID to fix.")- parser.add_argument(- "--all-distinct-ids", action="store_true", help="Whether to fix *all* distinct IDs for the team."- )-- def handle(self, *args, **options):- run(options)---def run(options):- if not options["team_id"]:- logger.error("You must specify --team-id to run this script")- exit(1)-- team_id = options["team_id"]-- distinct_id = options.get("distinct_id")- all_distinct_ids = options.get("all_distinct_ids", False)- if (not distinct_id and not all_distinct_ids) or (distinct_id and all_distinct_ids):- logger.error("You must specify one of --distinct-id or --all-distinct-ids to run this script")- exit(1)-- if all_distinct_ids:- version = options["new_version"]- reset_all_deleted_person_distinct_ids(team_id, version)- else:- reset_deleted_person_distinct_ids(team_id, distinct_id)-- logger.info("Waiting on Kafka producer flush, for up to 5 minutes")- flush_all_producers(5 * 60)- logger.info("Kafka producer queue flushed.")diff --git a/posthog/management/commands/sync_persons_to_clickhouse.py b/posthog/management/commands/sync_persons_to_clickhouse.pyindex fbc726e668ce..422d271d9186 100644--- a/posthog/management/commands/sync_persons_to_clickhouse.py+++ b/posthog/management/commands/sync_persons_to_clickhouse.py@@ -325,8 +325,7 @@ def run_distinct_id_sync(team_id: int, live_run: bool, deletes: bool):is_deleted=False,)elif ch_version > pg_version:- # This could be happening due to person deletions - check out fix_person_distinct_ids_after_delete management cmd.- # Ignoring here to be safe.+ # Republishing below ClickHouse changes nothing; person_divergence repair raises Postgres above it first.logger.info(f"Clickhouse version ({ch_version}) for '{person_distinct_id['distinct_id']}' is higher than in Postgres ({pg_version}). Ignoring.")diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.pyindex fbc1605713d2..b1dfb458169d 100644--- a/posthog/models/person/deletion.py+++ b/posthog/models/person/deletion.py@@ -4,20 +4,15 @@ from typing import Optionalfrom uuid import UUIDimport structlog-from rest_framework.exceptions import NotFoundfrom posthog.clickhouse.client import sync_execute-from posthog.models.person import Personfrom posthog.models.person.util import (PERSONHOG_BATCH_SIZE,PersonTombstone,PersonTombstonePublication,PersonVersionFloor,VersionFloorOutcome,- create_person,- create_person_distinct_id,ensure_person_version_floors,- get_person_by_distinct_id,get_person_tombstones,get_persons_by_uuids,)@@ -28,210 +23,9 @@ logger = structlog.get_logger(__name__)_PERSONHOG_UUID_BATCH = 250-def reset_all_deleted_person_distinct_ids(team_id: int, version: int = 2500):- # NOTE: Version is arbitrary, we just need to make sure it's higher than any existing version- distinct_ids = _get_distinct_ids_tied_to_deleted_persons(team_id)- distinct_ids_and_versions: list[tuple[str, int]] = [(distinct_id, version) for distinct_id in distinct_ids]- _updated_distinct_ids(team_id, distinct_ids_and_versions)---def reset_deleted_person_distinct_ids(team_id: int, distinct_id: str):- existing_version = _get_version_for_distinct_id(team_id, distinct_id)- distinct_ids_and_versions = [(distinct_id, existing_version + 100)]-- logger.info(f"Resetting distinct id {distinct_id} to version {existing_version + 100}")- _updated_distinct_ids(team_id, distinct_ids_and_versions)---def _get_distinct_ids_tied_to_deleted_persons(team_id: int) -> list[str]:- # find distinct_ids where the person is set to be deleted- rows = sync_execute(- """- SELECT distinct_id FROM (- SELECT distinct_id, argMax(person_id, version) AS person_id FROM person_distinct_id2 WHERE team_id = %(team)s GROUP BY distinct_id- ) AS pdi2- WHERE pdi2.person_id NOT IN (SELECT id FROM person WHERE team_id = %(team)s)- OR- pdi2.person_id IN (SELECT id FROM person WHERE team_id = %(team)s AND is_deleted = 1)- """,- {- "team": team_id,- },- )- return [row[0] for row in rows]---def _get_version_for_distinct_id(team_id: int, distinct_id: str) -> int:- rows = sync_execute(- """- SELECT max(version) as version FROM person_distinct_id2 WHERE team_id = %(team)s AND distinct_id = %(distinct_id)s- """,- {- "team": team_id,- "distinct_id": distinct_id,- },- )-- if len(rows) == 0:- raise NotFound(f"Distinct id {distinct_id} not found")- return rows[0][0]---def _updated_distinct_ids(team_id: int, distinct_id_versions: list[tuple[str, int]]):- reset_person_uuids: set[str] = set()-- for distinct_id, version in distinct_id_versions:- # this can throw but this script can safely be re-run as- # updated distinct_ids won't show up in the search anymore- # since they no longer belong to deleted persons- # it's safer to throw and exit if anything went wrong-- # The floor RPC also matches deleted rows, and publishing one as live leaves a ghost the sweep never removes.- # This lookup reads the replica, so the primary is rechecked after the floor RPC.- live_person = get_person_by_distinct_id(team_id, distinct_id, distinct_id_limit=0)- if live_person is None:- logger.info("Skipping distinct id reset: no live person", team_id=team_id, distinct_id=distinct_id)- continue-- # The write goes through personhog (an external RPC that can't join a- # Postgres transaction), so there is no surrounding atomic block.- person = _update_distinct_id_in_postgres(distinct_id, version, team_id)- if person is not None and person.uuid != live_person.uuid:- logger.warning(- "Skipping distinct id reset: distinct id moved to another person",- team_id=team_id,- distinct_id=distinct_id,- )- continue- if person is not None and get_person_tombstones(team_id, [person.uuid]):- logger.warning(- "Skipping distinct id reset: person is deleted in Postgres",- team_id=team_id,- distinct_id=distinct_id,- )- continue-- # Update ClickHouse via Kafka message- if person:- person_uuid = str(person.uuid)-- create_person_distinct_id(- team_id=team_id,- distinct_id=distinct_id,- person_id=person_uuid,- version=version,- is_deleted=False,- )-- # Also reset the person record in ClickHouse — the soft-deleted person row- # has a high version that causes ReplacingMergeTree to keep the deleted state,- # 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)---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). Returns None when the distinct_id doesn't exist (it hasn't been- re-used yet).- """- from posthog.personhog_client.client import personhog_call-- return personhog_call(- "set_person_distinct_id_version_floor",- lambda: _set_distinct_id_version_floor_via_personhog(team_id, distinct_id, version),- )---def _set_distinct_id_version_floor_via_personhog(team_id: int, distinct_id: str, version: int) -> Optional[Person]:- from posthog.personhog_client.client import require_personhog_client- from posthog.personhog_client.converters import proto_person_to_model- from posthog.personhog_client.proto import SetPersonDistinctIdVersionFloorRequest-- client = require_personhog_client()-- resp = client.set_person_distinct_id_version_floor(- SetPersonDistinctIdVersionFloorRequest(team_id=team_id, distinct_id=distinct_id, min_version=version)- )- 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- return proto_person_to_model(resp.person, distinct_ids=[distinct_id])---def _get_person_version_if_deleted(team_id: int, person_uuid: str) -> Optional[int]:- """Returns the max version if the person is soft-deleted in ClickHouse, None otherwise."""- rows = sync_execute(- """- SELECT max(version), argMax(is_deleted, version)- FROM person- WHERE team_id = %(team_id)s AND id = %(person_id)s- """,- {"team_id": team_id, "person_id": person_uuid},- )- if len(rows) == 0:- return None- max_version, is_deleted = rows[0]- if not is_deleted:- return None- return max_version---def _reset_person_in_clickhouse(team_id: int, person: Person) -> None:- person_uuid = str(person.uuid)- max_version = _get_person_version_if_deleted(team_id, person_uuid)- if max_version is None:- return-- new_version = max_version + 100- logger.info(f"Resetting person {person_uuid} in ClickHouse to version {new_version}")-- # 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)-- create_person(- uuid=person_uuid,- team_id=team_id,- version=new_version,- properties=person.properties,- is_identified=person.is_identified,- is_deleted=False,- created_at=person.created_at,- )---def _set_person_version_floor(team_id: int, person_id: int, new_version: int) -> None:- """Raise a person's version to at least `new_version` (guarded — never lowers).-- Routes through SetPersonVersionFloor.- """- from posthog.personhog_client.client import personhog_call-- personhog_call(- "set_person_version_floor",- lambda: _set_person_version_floor_via_personhog(team_id, person_id, new_version),- )---def _set_person_version_floor_via_personhog(team_id: int, person_id: int, new_version: int) -> None:- from posthog.personhog_client.client import require_personhog_client- from posthog.personhog_client.proto import SetPersonVersionFloorRequest-- client = require_personhog_client()-- client.set_person_version_floor(- SetPersonVersionFloorRequest(team_id=team_id, person_id=person_id, min_version=new_version)- )--# ── Orphaned ClickHouse person repair ────────────────────────────────#-# The inverse of the reset helpers above: a person can be hard-deleted from the-# persons DB (posthog_person + posthog_persondistinctid) with no matching+# A person can be hard-deleted from the persons DB (posthog_person + posthog_persondistinctid) with no matching# ClickHouse tombstone. The row then stays visible to every ClickHouse-backed# read path (HogQL `persons`, the UI Persons page) while every persons-DB write# path 404s. This produces the missing tombstones so ClickHouse agrees with the@@ -268,7 +62,7 @@ class OrphanRepairResult:skipped_live_persons: int = 0# (distinct_id, winner_uuid) pairs where the CH mapping is tombstoned but the# winning person is live in the persons DB — the opposite drift, handled by- # reset_all_deleted_person_distinct_ids, reported here rather than repaired.+ # person_divergence repair, reported here rather than repaired.reverse_drift_mappings: list[tuple[str, str]] = field(default_factory=list)dry_run: bool = Falsediff --git a/posthog/models/person/divergence.py b/posthog/models/person/divergence.pyindex 26fb3abb3131..7c53d0a848ad 100644--- a/posthog/models/person/divergence.py+++ b/posthog/models/person/divergence.py@@ -8,24 +8,25 @@ it, so the published row wins and the next ingestion update still outranks it.from __future__ import annotations+import jsonimport timefrom collections import Counter, defaultdictfrom collections.abc import Callable, Sequencefrom dataclasses import field-from datetime import datetime+from datetime import UTC, datetimefrom functools import partialfrom typing import Any, Literal, TypeVarfrom uuid import UUIDimport grpc+from posthog.api.capture import capture_internalfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozenfrom posthog.errors import CH_TRANSIENT_ERRORSfrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom posthog.kafka_client.client import ClickhouseProducer, ProduceResult-from posthog.kafka_client.routing import flush_all_producersfrom posthog.kafka_client.topics import KAFKA_PERSONfrom posthog.models.person import Personfrom posthog.models.person.sql import INSERT_PERSON_SQL@@ -33,8 +34,10 @@ from posthog.models.person.util import (_batched_get_distinct_ids_for_persons,_batched_get_persons_by_distinct_ids,_batched_get_persons_by_uuids,+ _flush_person_producers,_person_row,create_person_distinct_id,+ get_person_by_distinct_id,get_person_tombstones,get_persons_by_uuids,)@@ -49,6 +52,8 @@ from posthog.personhog_client.proto import (SetPersonVersionFloorRequest,)+from products.access_control.backend.facade.api import team_has_property_access_rules+PersonDivergenceKind = Literal["hidden", "swept", "stale", "behind", "absent"]MappingDivergenceKind = Literal["hidden", "other_person", "stale", "absent"]SampleClassification = Literal["equal", "pg_below_ch", "pg_above_ch", "team_gone", "pg_tombstone", "pg_absent"]@@ -64,6 +69,10 @@ RepairOutcome = Literal["skipped_mapping_gone","skipped_reread_lagging","skipped_stale",+ "skipped_stale_merge_failed",+ "skipped_stale_merge_too_large",+ "skipped_stale_merge_restricted",+ "merge_queued","skipped_too_many_distinct_ids",]@@ -97,6 +106,9 @@ _MAPPING_QUERY_CHUNK_SIZE = 1_000_MAX_REPAIR_DISTINCT_IDS_PER_PERSON = 1_000# The waits between re-reads give the replica about 0.5 s to show a raise, far above its usual lag of a few milliseconds._REREAD_BACKOFF_SECONDS = (0.025, 0.05, 0.1, 0.15, 0.175)+# Well under capture's 1,000,000-byte Kafka message limit and ingestion's 655,360-byte person properties limit+# (trimmed to 512 KiB), so ingestion applies the merge whole.+_STALE_MERGE_MAX_BYTES = 256 * 1024_TRANSIENT_RETRY_BACKOFF_SECONDS = (1.0, 2.0)_TRANSIENT_RPC_CODES = frozenset({grpc.StatusCode.INTERNAL, grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED}@@ -665,6 +677,12 @@ WHERE team_id = %(team_id)s AND id IN %(person_uuids)sGROUP BY id"""+_PERSON_WINNER_PROPERTIES_SQL = """+SELECT argMaxIf(properties, version, _row_exists)+FROM person+WHERE team_id = %(team_id)s AND id = %(person_uuid)s+"""+_MAPPING_STATE_SQL = """SELECTdistinct_id,@@ -749,7 +767,7 @@ def _ch_mapping_states(team_id: int, distinct_ids: list[str]) -> dict[str, _ChMareturn states-def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:+def _plan_chunk(team_id: int, person_uuids: Sequence[str], *, only_distinct_id: str | None = None) -> list[_PersonPlan]:live = {str(p.uuid): p for p in get_persons_by_uuids(team_id, list(person_uuids), distinct_id_limit=0)}person_states = _ch_person_states(team_id, list(live)) if live else {}distinct_ids_by_person = (@@ -762,12 +780,19 @@ def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:if liveelse {})- all_distinct_ids = [- d.id- for dids in distinct_ids_by_person.values()- if len(dids) <= _MAX_REPAIR_DISTINCT_IDS_PER_PERSON- for d in dids- ]+ too_many: set[int] = set()+ all_distinct_ids: list[str] = []+ for person_id, dids in list(distinct_ids_by_person.items()):+ over_cap = len(dids) > _MAX_REPAIR_DISTINCT_IDS_PER_PERSON+ if only_distinct_id is not None:+ dids = [d for d in dids if d.id == only_distinct_id]+ distinct_ids_by_person[person_id] = dids+ # The capped read can miss the requested id, which must then be reported rather than dropped.+ over_cap = over_cap and not dids+ if over_cap:+ too_many.add(person_id)+ else:+ all_distinct_ids.extend(d.id for d in dids)mapping_states = _ch_mapping_states(team_id, all_distinct_ids) if all_distinct_ids else {}plans: list[_PersonPlan] = []@@ -790,7 +815,7 @@ def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:state = person_states.get(person_uuid)ch_max_version = state.max_version if state is not None else Noneperson_distinct_ids = distinct_ids_by_person.get(person.pk, [])- too_many_distinct_ids = len(person_distinct_ids) > _MAX_REPAIR_DISTINCT_IDS_PER_PERSON+ too_many_distinct_ids = person.pk in too_manymappings = []for mapping in [] if too_many_distinct_ids else person_distinct_ids:mapping_state = mapping_states.get(mapping.id)@@ -925,6 +950,44 @@ def _reread_person(team_id: int, person_uuid: str, target_version: int | None) -return reread+def _clickhouse_only_properties(plan: _PersonPlan) -> dict[str, Any]:+ """The properties of the ClickHouse winner whose keys the Postgres person lacks."""+ assert plan.person is not None+ rows = _ch(+ _PERSON_WINNER_PROPERTIES_SQL,+ {"team_id": plan.team_id, "person_uuid": plan.person_uuid},+ _REPAIR_READ_SETTINGS,+ )+ ch_properties = json.loads(rows[0][0]) if rows and rows[0][0] else {}+ pg_properties = plan.person.properties or {}+ return {key: value for key, value in ch_properties.items() if key not in pg_properties}+++def _queue_stale_merge(plan: _PersonPlan, distinct_id: str, missing: dict[str, Any]) -> RepairOutcome | None:+ """Send the ClickHouse-only properties to ingestion as $set_once, or return why they were not sent."""+ assert plan.person is not None+ # Every member can read the $set event, and event reads apply event property restrictions only, so a team with+ # any property rule could expose a person property that some member is denied.+ if team_has_property_access_rules(team_id=plan.team_id):+ return "skipped_stale_merge_restricted"+ if len(json.dumps({**missing, **(plan.person.properties or {})})) > _STALE_MERGE_MAX_BYTES:+ return "skipped_stale_merge_too_large"+ try:+ token = Team.objects.only("api_token").get(id=plan.team_id).api_token+ capture_internal(+ token=token,+ event_name="$set",+ event_source="person_divergence_reset",+ distinct_id=distinct_id,+ timestamp=datetime.now(UTC),+ properties={"$set_once": missing},+ process_person_profile=True,+ ).raise_for_status()+ except Exception:+ return "skipped_stale_merge_failed"+ return None++def _is_transient(exc: BaseException) -> bool:return isinstance(exc, (*CH_TRANSIENT_ERRORS, ClickHouseQueryTimeOut)) or is_transient_rpc_error(exc, codes=_TRANSIENT_RPC_CODES@@ -955,19 +1018,29 @@ def _execute_plan(include_stale: bool,before_write: Callable[[], None],published: Callable[[ProduceResult], None],+ stale_merge_distinct_id: str | None = None,) -> list[RepairAction]:person = plan.personif person is None:return [_person_action(plan, "skipped_not_live")]if plan.kind == "stale" and not include_stale:- return [- _person_action(plan, "skipped_stale"),- *(- _mapping_action(plan, m, "skipped_not_divergent" if m.kind is None else "skipped_stale")- for m in plan.mappings- ),- *([_too_many_distinct_ids_action(plan)] if plan.too_many_distinct_ids else []),- ]+ refusal: RepairOutcome | None = "skipped_stale"+ if apply and stale_merge_distinct_id is not None:+ missing = _clickhouse_only_properties(plan)+ # A later reset that finds nothing missing raises Postgres. Capture accepting the $set does not mean+ # ingestion applies it, and a raise without the merged properties lets the next update overwrite them.+ refusal = (+ (_queue_stale_merge(plan, stale_merge_distinct_id, missing) or "merge_queued") if missing else None+ )+ if refusal is not None:+ return [+ _person_action(plan, refusal),+ *(+ _mapping_action(plan, m, "skipped_not_divergent" if m.kind is None else "skipped_stale")+ for m in plan.mappings+ ),+ *([_too_many_distinct_ids_action(plan)] if plan.too_many_distinct_ids else []),+ ]divergent_mappings = [m for m in plan.mappings if m.kind is not None]mapping_actions = [_mapping_action(plan, m, "skipped_not_divergent") for m in plan.mappings if m.kind is None]@@ -1079,7 +1152,7 @@ class _Deliveries:self._prune()def undelivered(self, timeout: float) -> int:- flush_all_producers(timeout)+ _flush_person_producers(timeout)self._prune()return self.failed + len(self.pending)@@ -1096,6 +1169,25 @@ class _Deliveries:self.pending = waiting+@frozen(frozen=False)+class _OutcomeCounts:+ person: Counter[RepairOutcome] = field(default_factory=Counter)+ mapping: Counter[RepairOutcome] = field(default_factory=Counter)++ def add(self, action: RepairAction) -> None:+ is_person_row = action.distinct_id is None and action.outcome != "skipped_too_many_distinct_ids"+ (self.person if is_person_row else self.mapping)[action.outcome] += 1++ def summary(self, *, applied: bool, persons: int, undelivered: int) -> RepairSummary:+ return RepairSummary(+ applied=applied,+ persons=persons,+ person_outcomes=dict(self.person),+ mapping_outcomes=dict(self.mapping),+ undelivered=undelivered,+ )++def repair_persons(targets: Sequence[PersonRef],*,@@ -1120,8 +1212,7 @@ def repair_persons(for target in dict.fromkeys(targets):by_team[target.team_id].append(target.person_uuid)- person_outcomes: Counter[RepairOutcome] = Counter()- mapping_outcomes: Counter[RepairOutcome] = Counter()+ outcomes = _OutcomeCounts()processed = 0undelivered = 0pacer = _WritePacer(max_per_second=max_writes_per_second)@@ -1142,7 +1233,7 @@ def repair_persons(target_version=None,outcome="skipped_team_gone",)- person_outcomes[action.outcome] += 1+ outcomes.add(action)on_action(action)processed += 1log(f"team {team_id}: no longer exists, {len(person_uuids)} persons skipped")@@ -1166,8 +1257,7 @@ def repair_persons(log=log,)for action in actions:- is_person_row = action.distinct_id is None and action.outcome != "skipped_too_many_distinct_ids"- (person_outcomes if is_person_row else mapping_outcomes)[action.outcome] += 1+ outcomes.add(action)on_action(action)processed += 1log(f"team {team_id}: {len(person_uuids)} persons, {processed} processed in total")@@ -1176,10 +1266,34 @@ def repair_persons(undelivered = deliveries.undelivered(_FLUSH_TIMEOUT_SECONDS)if undelivered:log(f"{undelivered} ClickHouse messages were not delivered; rerun the repair for the same input")- return RepairSummary(- applied=apply,- persons=processed,- person_outcomes=dict(person_outcomes),- mapping_outcomes=dict(mapping_outcomes),- undelivered=undelivered,- )+ return outcomes.summary(applied=apply, persons=processed, undelivered=undelivered)+++def repair_distinct_id(team_id: int, distinct_id: str, *, delivery_timeout_seconds: float) -> RepairSummary | None:+ """Repair the live person that owns ``distinct_id``, and that one mapping, where ClickHouse disagrees.++ It always applies. For a stale person whose ClickHouse winner holds properties Postgres lacks, it sends them+ to ingestion as $set_once, so newer Postgres values win, and writes nothing else. A later reset, once+ ingestion applied them, raises Postgres above ClickHouse and republishes. It leaves the person stale when the+ team has property access rules.+ """+ owner = get_person_by_distinct_id(team_id, distinct_id, distinct_id_limit=0)+ if owner is None:+ return None+ outcomes = _OutcomeCounts()+ deliveries = _Deliveries()+ undelivered = 0+ try:+ for plan in _plan_chunk(team_id, [str(owner.uuid)], only_distinct_id=distinct_id):+ for action in _execute_plan(+ plan,+ apply=True,+ include_stale=False,+ before_write=lambda: None,+ published=deliveries.track,+ stale_merge_distinct_id=distinct_id,+ ):+ outcomes.add(action)+ finally:+ undelivered = deliveries.undelivered(delivery_timeout_seconds)+ return outcomes.summary(applied=True, persons=1, undelivered=undelivered)diff --git a/posthog/models/person/test/test_divergence.py b/posthog/models/person/test/test_divergence.pyindex 07e59498cc5e..9fc18888c3a4 100644--- a/posthog/models/person/test/test_divergence.py+++ b/posthog/models/person/test/test_divergence.py@@ -15,10 +15,11 @@ from parameterized import parameterizedfrom personhog.types.v1 import person_pb2from posthog.clickhouse.client import sync_execute+from posthog.constants import AvailableFeaturefrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom posthog.kafka_client.client import ClickhouseProducer, ProduceResultfrom posthog.kafka_client.topics import KAFKA_PERSON-from posthog.models import Team+from posthog.models import OrganizationMembership, PropertyDefinition, Team, Userfrom posthog.models.person import Personfrom posthog.models.person.divergence import (DivergentPerson,@@ -36,6 +37,7 @@ from posthog.models.person.divergence import (_team_check_modulus,_WritePacer,check_team,+ repair_distinct_id,repair_persons,scan_hidden_persons,scan_sample,@@ -52,8 +54,12 @@ from posthog.personhog_client.fake_client import get_active_fakefrom posthog.personhog_client.proto import CONSISTENCY_LEVEL_STRONGfrom posthog.test.persons import add_distinct_id, create_person+from products.access_control.backend.models.property_access_control import PropertyAccessControl+from products.access_control.backend.property_access_control import PropertyAccessLevel+PG_PROPERTIES = {"email": "[email protected]"}CH_PROPERTIES = {"email": "[email protected]"}+CH_ONLY_PROPERTIES = {"plan": "free", "company": "Acme"}_PERSON_COLUMNS = ("id, created_at, team_id, properties, is_identified, _timestamp, _offset, is_deleted, version, last_seen_at"@@ -87,13 +93,14 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):deleted: bool = False,hours_ago: float = 0,team_id: int | None = None,+ properties: dict[str, Any] | None = None,) -> None:create_person_in_ch(team_id=team_id or self.team.pk,uuid=str(person_uuid),version=version,is_deleted=deleted,- properties=CH_PROPERTIES,+ properties=CH_PROPERTIES if properties is None else properties,timestamp=now() - timedelta(hours=hours_ago),)@@ -843,6 +850,150 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):assert self._pg_mapping_versions(person)["divergent"] == stored_versionassert self._ch_mapping("divergent") == (str(person.uuid), *ch_deleted_and_version)+ @parameterized.expand(+ [+ ("within_the_cap", ["target", "other"], 1_000, {"repaired": 1}, (0, 101)),+ (+ "over_the_cap_with_the_target_in_the_capped_read",+ ["target", "other", "another"],+ 1,+ {"repaired": 1},+ (0, 101),+ ),+ (+ "beyond_the_capped_read",+ ["other", "another", "target"],+ 1,+ {"skipped_too_many_distinct_ids": 1},+ (1, 100),+ ),+ ]+ )+ def test_repairing_one_distinct_id_repairs_its_owner_and_leaves_its_other_mappings(+ self,+ _name: str,+ distinct_ids: list[str],+ cap: int,+ mapping_outcomes: dict[str, int],+ target_deleted_and_version: tuple[int, int],+ ) -> None:+ person = self._pg_person(version=3, distinct_ids=dict.fromkeys(distinct_ids, 2))+ self._ch_person_row(person.uuid, 103, deleted=True)+ for distinct_id in distinct_ids:+ self._ch_mapping_row(distinct_id, person.uuid, 100, deleted=True)++ with patch("posthog.models.person.divergence._MAX_REPAIR_DISTINCT_IDS_PER_PERSON", cap):+ summary = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)++ assert summary is not None+ assert (summary.person_outcomes, summary.mapping_outcomes, summary.undelivered) == (+ {"repaired": 1},+ mapping_outcomes,+ 0,+ )+ assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)+ assert self._ch_mapping("target") == (str(person.uuid), *target_deleted_and_version)+ assert self._ch_mapping("other") == (str(person.uuid), 1, 100)++ def _restrict_person_property_for_another_member(self, name: str) -> None:+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=PropertyDefinition.objects.create(+ team=self.team, name=name, property_type="String", type=PropertyDefinition.Type.PERSON+ ),+ organization_member=OrganizationMembership.objects.get(user=other, organization=self.organization),+ access_level=PropertyAccessLevel.NONE.value,+ )++ def _stale_person_with_target(self, ch_properties: dict[str, Any]) -> Person:+ person = self._pg_person(version=5, distinct_ids={"target": 2})+ self._ch_person_row(person.uuid, 10, properties=ch_properties)+ self._ch_mapping_row("target", person.uuid, 100, deleted=True)+ return person++ def test_reset_raises_a_stale_person_only_after_ingestion_applied_its_clickhouse_only_properties(self) -> None:+ person = self._stale_person_with_target({**CH_PROPERTIES, **CH_ONLY_PROPERTIES})+ stored = get_active_fake().stored_person(self.team.pk, str(person.uuid))+ assert stored is not None++ with patch("posthog.models.person.divergence.capture_internal") as capture:+ first = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)++ assert first is not None+ assert (first.person_outcomes, first.mapping_outcomes) == ({"merge_queued": 1}, {"skipped_stale": 1})+ capture.assert_called_once()+ sent = dict(capture.call_args.kwargs)+ sent.pop("timestamp")+ assert sent == {+ "token": self.team.api_token,+ "event_name": "$set",+ "event_source": "person_divergence_reset",+ "distinct_id": "target",+ "properties": {"$set_once": CH_ONLY_PROPERTIES},+ "process_person_profile": True,+ }+ get_active_fake().assert_not_called("set_person_version_floor")+ get_active_fake().assert_not_called("set_person_distinct_id_version_floor")+ assert self._pg_version(person) == 5+ assert self._ch_person(person.uuid) == (0, 10, {**CH_PROPERTIES, **CH_ONLY_PROPERTIES})++ stored.properties = json.dumps({**CH_ONLY_PROPERTIES, **PG_PROPERTIES}).encode()+ with patch("posthog.models.person.divergence.capture_internal") as capture:+ second = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)++ assert second is not None+ assert (second.person_outcomes, second.mapping_outcomes) == ({"repaired": 1}, {"repaired": 1})+ capture.assert_not_called()+ assert self._pg_version(person) == 11+ assert self._ch_person(person.uuid) == (0, 11, {**CH_ONLY_PROPERTIES, **PG_PROPERTIES})+ assert self._ch_mapping("target") == (str(person.uuid), 0, 101)++ def test_reset_republishes_a_stale_person_whose_clickhouse_properties_postgres_already_holds(self) -> None:+ person = self._stale_person_with_target(CH_PROPERTIES)++ with patch("posthog.models.person.divergence.capture_internal") as capture:+ summary = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)++ assert summary is not None+ assert (summary.person_outcomes, summary.mapping_outcomes) == ({"repaired": 1}, {"repaired": 1})+ capture.assert_not_called()+ assert self._ch_person(person.uuid) == (0, 11, PG_PROPERTIES)++ @parameterized.expand(+ [+ ("capture_fails", 256 * 1024, False, "skipped_stale_merge_failed", True),+ ("merge_too_large", 10, False, "skipped_stale_merge_too_large", False),+ ("property_restricted_for_another_member", 256 * 1024, True, "skipped_stale_merge_restricted", False),+ ]+ )+ def test_reset_leaves_a_stale_person_alone_when_its_merge_cannot_be_sent(+ self, _name: str, max_bytes: int, restricted: bool, person_outcome: str, capture_called: bool+ ) -> None:+ person = self._stale_person_with_target({**CH_PROPERTIES, **CH_ONLY_PROPERTIES})+ if restricted:+ self._restrict_person_property_for_another_member("plan")+ failing = MagicMock()+ failing.raise_for_status.side_effect = RuntimeError("capture rejected the event")++ with (+ patch("posthog.models.person.divergence._STALE_MERGE_MAX_BYTES", max_bytes),+ patch("posthog.models.person.divergence.capture_internal", return_value=failing) as capture,+ ):+ summary = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)++ assert summary is not None+ assert (summary.person_outcomes, summary.mapping_outcomes) == ({person_outcome: 1}, {"skipped_stale": 1})+ assert capture.called == capture_called+ get_active_fake().assert_not_called("set_person_version_floor")+ get_active_fake().assert_not_called("set_person_distinct_id_version_floor")+ assert self._pg_version(person) == 5+ assert self._ch_person(person.uuid) == (0, 10, {**CH_PROPERTIES, **CH_ONLY_PROPERTIES})+def test_repairs_the_person_but_reports_its_mappings_when_it_has_too_many_distinct_ids(self) -> None:person = self._pg_person(version=3, distinct_ids={"a": 0, "b": 0, "c": 0})self._ch_person_row(person.uuid, 103, deleted=True)diff --git a/posthog/models/person/test/test_reset_distinct_ids_personhog.py b/posthog/models/person/test/test_reset_distinct_ids_personhog.pydeleted file mode 100644index 0b36e2b1aa22..000000000000--- a/posthog/models/person/test/test_reset_distinct_ids_personhog.py+++ /dev/null@@ -1,97 +0,0 @@-"""Tests for the undelete-repair version writes via personhog RPC.--Covers the two personhog RPC 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 import mock--from django.test import SimpleTestCase--from parameterized import parameterized--from posthog.models.person import Person, deletion-from posthog.models.person.deletion import (- _set_person_version_floor,- _update_distinct_id_in_postgres,- _updated_distinct_ids,-)-from posthog.personhog_client.fake_client import fake_personhog_client---class TestUpdateDistinctIdInPostgresRPC(SimpleTestCase):- def test_personhog_path_returns_converted_person(self):- person_uuid = str(uuid4())- with fake_personhog_client() 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]"}-- def test_personhog_returns_none_when_distinct_id_absent(self):- with fake_personhog_client():- # 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---class TestSetPersonVersionFloorRPC(SimpleTestCase):- def test_personhog_path_calls_rpc_with_floor(self):- with fake_personhog_client() as fake:- _set_person_version_floor(1, 42, 500)-- 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---class TestUpdatedDistinctIdsSkipsDeleted(SimpleTestCase):- @parameterized.expand(- [- ("no_live_person", "none", False),- ("distinct_id_moved_to_another_person", "other", False),- ("replica_lags_a_delete_on_the_primary", "same", True),- ]- )- def test_leaves_the_distinct_id_unpublished(self, _name: str, replica_owner: str, deleted: bool) -> None:- owner_uuid = uuid4()- live_person = {- "none": None,- "other": Person(uuid=uuid4(), team_id=1),- "same": Person(uuid=owner_uuid, team_id=1),- }[replica_owner]- with (- fake_personhog_client() as fake,- mock.patch.object(deletion, "get_person_by_distinct_id", return_value=live_person),- mock.patch.object(deletion, "create_person_distinct_id") as publish_distinct_id,- mock.patch.object(deletion, "create_person") as publish_person,- ):- fake.add_person(- team_id=1, person_id=42, uuid=str(owner_uuid), version=3, distinct_ids=["did-1"], is_deleted=deleted- )-- _updated_distinct_ids(1, [("did-1", 105)])-- fake.assert_not_called("set_person_version_floor")-- publish_distinct_id.assert_not_called()- publish_person.assert_not_called()diff --git a/products/persons/frontend/logics/personsSceneLogic.ts b/products/persons/frontend/logics/personsSceneLogic.tsindex d77a043aba52..7f3ae993e79c 100644--- a/products/persons/frontend/logics/personsSceneLogic.ts+++ b/products/persons/frontend/logics/personsSceneLogic.ts@@ -129,7 +129,9 @@ export const personsSceneLogic = kea<personsSceneLogicType>([listeners({resetDeletedDistinctId: async ({ distinct_id }) => {await api.persons.resetPersonDistinctId(distinct_id)- lemonToast.success('Distinct ID reset. It may take a few minutes to process.')+ lemonToast.success(+ "Distinct ID reset. If the person doesn't show up within a few minutes, run the reset again."+ )},}),