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(persons): remove the reset deleted person endpoint and menu item (#125747)

Nick Bestb4f7a6920470
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 97331fcb354c..63cdde18d2f8 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3660,16 +3660,6 @@ const api = {
determineListUrl(params: PersonListParams = {}): string {
return new ApiRequest().persons().withQueryString(toParams(params)).assembleFullUrl()
},
- async resetPersonDistinctId(distinctId: string): Promise<void> {
- return await new ApiRequest()
- .persons()
- .withAction('reset_person_distinct_id')
- .create({
- data: {
- distinct_id: distinctId,
- },
- })
- },
async getByDistinctIds(distinctIds: string[]): Promise<Record<string, PersonType>> {
const response = await new ApiRequest()
.persons()
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 765df3317c4f..3fbe1f7b4037 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -16,7 +16,6 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiExample,
OpenApiParameter,
- OpenApiResponse,
extend_schema,
extend_schema_field,
extend_schema_serializer,
@@ -65,7 +64,6 @@ from posthog.models.person.bulk_delete import (
queue_person_recording_deletion,
resolve_persons_for_deletion,
)
-from posthog.models.person.divergence.repairs import is_person_busy, is_retryable, repair_distinct_id
from posthog.models.person.missing_person import MissingPerson
from posthog.models.person.util import (
get_distinct_ids_for_persons,
@@ -105,8 +103,6 @@ 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
@@ -1871,47 +1867,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
except Person.DoesNotExist:
raise NotFound(detail="Person not found.")
- @extend_schema(
- description="Fix a distinct_id that stays hidden after its person was deleted and created again. Does nothing if no live person uses this distinct_id. In that case, send a new event for it instead.",
- responses={
- 202: OpenApiResponse(description="The fix was applied, or nothing needed fixing."),
- 409: OpenApiResponse(description="The person is being updated by another operation. Try again shortly."),
- 503: OpenApiResponse(description="Person data is temporarily unavailable. Try again shortly."),
- },
- )
- @action(methods=["POST"], detail=False, required_scopes=["person:write"])
- def reset_person_distinct_id(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
- distinct_id = request.data.get("distinct_id")
- if not distinct_id or not isinstance(distinct_id, str):
- raise ValidationError(detail="distinct_id is required")
-
- try:
- summary = repair_distinct_id(
- self.team_id, distinct_id, delivery_timeout_seconds=RESET_DISTINCT_ID_DELIVERY_TIMEOUT_SECONDS
- )
- except Exception as error:
- if is_person_busy(error):
- return response.Response(
- {"detail": "This person is being updated right now. Try again in a few seconds."},
- status=409,
- )
- if is_retryable(error):
- return response.Response(
- {"detail": "Person data is temporarily unavailable. Try again in a minute."},
- status=503,
- )
- raise
- 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)
-
@action(methods=["POST"], detail=False, url_path="batch_by_distinct_ids", required_scopes=["person:read"])
def batch_by_distinct_ids(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
distinct_ids = request.data.get("distinct_ids", [])
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 3235d57fbd43..59b62fce97b5 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -4,7 +4,6 @@ from datetime import timedelta
from typing import Optional, cast
from uuid import UUID, uuid4
-import pytest
import time_machine
from posthog.test.base import (
APIBaseTest,
@@ -23,14 +22,11 @@ from unittest import mock
from django.test import SimpleTestCase
from django.utils import timezone
-import grpc
from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import ValidationError
-import posthog.models.person.divergence.repairs
-import posthog.models.person.divergence.stale_merge
from posthog.api.person import tag_client_query_id
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags
@@ -40,7 +36,6 @@ from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person.bulk_delete import PersonDeletionFailure, PersonDeletionStep, PersonProfileDeletionResult
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 as create_person_in_ch,
create_person_distinct_id,
@@ -2395,155 +2390,6 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json()["detail"] == "Not found."
- @pytest.mark.flaky(reruns=2)
- def test_reset_person_distinct_id(self):
- # Simulate the real-world scenario: person deleted in CH (soft delete with high version),
- # then the same distinct_id is reused which creates a new person in PG with the same
- # deterministic UUID. The new person's CH row has a lower version than the deletion,
- # so ReplacingMergeTree keeps the deleted state.
- shared_uuid = str(uuid4())
-
- # Phase 1: Person and distinct_id exist in CH as deleted
- create_person_in_ch(
- uuid=shared_uuid,
- team_id=self.team.pk,
- is_deleted=True,
- version=105,
- )
- create_person_distinct_id(
- team_id=self.team.pk,
- distinct_id="distinct_id",
- person_id=shared_uuid,
- is_deleted=True,
- version=107,
- )
-
- # Phase 2: New event reuses the distinct_id, creating a new person in PG
- # with the same deterministic UUID. The signal writes to CH with version=0,
- # which is ignored because 0 < 105.
- person = create_person(team=self.team, properties={"abcdefg": 11112}, version=0, uuid=shared_uuid)
- add_distinct_id(person=person, distinct_id="distinct_id", version=0)
-
- # Phase 3: Reset
- response = self.client.post(
- f"/api/projects/{self.team.pk}/persons/reset_person_distinct_id/",
- {"distinct_id": "distinct_id"},
- )
- assert response.status_code == status.HTTP_202_ACCEPTED
-
- # Verify: personhog distinct_id version was bumped
- resolved = get_person_by_distinct_id(self.team.pk, "distinct_id")
- assert resolved is not None
-
- # Verify: CH distinct_id is reset
- ch_pdi = sync_execute(
- f"""
- SELECT person_id, version, is_deleted
- FROM {PERSON_DISTINCT_ID2_TABLE} FINAL
- WHERE team_id = %(team_id)s AND distinct_id = 'distinct_id'
- """,
- {"team_id": self.team.pk},
- )
- self.assertEqual(len(ch_pdi), 1)
- self.assertEqual(ch_pdi[0][2], 0) # is_deleted
- assert ch_pdi[0][1] > 107 # version beats deletion
-
- # Verify: CH person is also reset
- ch_person = sync_execute(
- """
- SELECT argMax(is_deleted, version), max(version)
- FROM person FINAL
- WHERE team_id = %(team_id)s AND id = %(person_id)s
- """,
- {"team_id": self.team.pk, "person_id": shared_uuid},
- )
- self.assertEqual(len(ch_person), 1)
- self.assertEqual(ch_person[0][0], 0) # is_deleted
- assert ch_person[0][1] > 105 # version beats deletion
-
- # Verify: personhog person version was bumped so future plugin-server updates aren't ignored
- person_after = get_person_by_uuid(self.team.pk, shared_uuid)
- assert person_after is not None
- assert person_after.version is not None and person_after.version > 105
-
- @parameterized.expand(
- [
- ("mark_held_by_another_operation", grpc.StatusCode.FAILED_PRECONDITION, (), 409),
- ("row_lock_timed_out", grpc.StatusCode.DEADLINE_EXCEEDED, (("x-db-timeout", "lock_timeout"),), 409),
- ("statement_timed_out", grpc.StatusCode.DEADLINE_EXCEEDED, (("x-db-timeout", "statement_timeout"),), 503),
- ("personhog_deadline", grpc.StatusCode.DEADLINE_EXCEEDED, (), 503),
- ("personhog_unavailable", grpc.StatusCode.UNAVAILABLE, (), 503),
- ]
- )
- def test_reset_person_distinct_id_asks_for_a_retry_on_a_busy_person_or_an_unavailable_service(
- self, _name: str, code: grpc.StatusCode, trailing: tuple[tuple[str, str], ...], status: int
- ) -> None:
- failure = grpc.RpcError()
- failure.code = mock.MagicMock(return_value=code)
- failure.trailing_metadata = mock.MagicMock(return_value=trailing)
-
- with mock.patch("posthog.api.person.repair_distinct_id", side_effect=failure):
- response = self.client.post(
- f"/api/projects/{self.team.pk}/persons/reset_person_distinct_id/", {"distinct_id": "busy"}
- )
-
- assert response.status_code == status
- assert (
- response.json()["detail"]
- == {
- 409: "This person is being updated right now. Try again in a few seconds.",
- 503: "Person data is temporarily unavailable. Try again in a minute.",
- }[status]
- )
-
- @mock.patch(
- f"{posthog.models.person.divergence.repairs.__name__}.create_person_distinct_id",
- wraps=posthog.models.person.divergence.repairs.create_person_distinct_id,
- )
- @pytest.mark.flaky(reruns=2)
- def test_reset_person_distinct_id_not_found(self, mocked_ch_call):
- # person who shouldn't be changed
- person_not_changed_1 = create_person(team=self.team, properties={"abcdef": 1111}, version=0, uuid=uuid4())
-
- # distinct id no update
- add_distinct_id(person=person_not_changed_1, distinct_id="distinct_id-1", version=0)
-
- # deleted person not re-used
- person_deleted_1 = create_person(team=self.team, properties={"abcdef": 1111}, version=0, uuid=uuid4())
- add_distinct_id(person=person_deleted_1, distinct_id="distinct_id-del-1", version=16)
- delete_person(person_deleted_1)
-
- response = self.client.post(
- f"/api/projects/{self.team.pk}/persons/reset_person_distinct_id/",
- {
- "distinct_id": "distinct_id",
- },
- )
-
- assert response.status_code == status.HTTP_202_ACCEPTED
-
- # personhog: only the non-deleted distinct_id still resolves to its person
- assert get_person_by_distinct_id(self.team.pk, "distinct_id-del-1") is None
- resolved = get_person_by_distinct_id(self.team.pk, "distinct_id-1")
- assert resolved is not None
- assert resolved.uuid == person_not_changed_1.uuid
-
- # clickhouse
- ch_person_distinct_ids = sync_execute(
- f"""
- SELECT person_id, team_id, distinct_id, version, is_deleted FROM {PERSON_DISTINCT_ID2_TABLE} FINAL WHERE team_id = %(team_id)s ORDER BY version
- """,
- {"team_id": self.team.pk},
- )
- self.assertEqual(
- ch_person_distinct_ids,
- [
- (person_not_changed_1.uuid, self.team.pk, "distinct_id-1", 0, False),
- (person_deleted_1.uuid, self.team.pk, "distinct_id-del-1", 116, True),
- ],
- )
- mocked_ch_call.assert_not_called()
-
def test_batch_by_distinct_ids_happy_path(self) -> None:
_create_person(
team=self.team,
@@ -2777,23 +2623,6 @@ class TestPersonBatchRestrictedProperties(ClickhouseTestMixin, APIBaseTest):
team=self.team, property_definition=restricted, access_level=PropertyAccessLevel.NONE.value
)
- @mock.patch(f"{posthog.models.person.divergence.stale_merge.__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/models/person/divergence/repairs.py b/posthog/models/person/divergence/repairs.py
index b094078de243..b7ccf539e7d9 100644
--- a/posthog/models/person/divergence/repairs.py
+++ b/posthog/models/person/divergence/repairs.py
@@ -24,7 +24,6 @@ from posthog.models.person.util import (
_flush_person_producers,
_person_row,
create_person_distinct_id,
- get_person_by_distinct_id,
get_persons_by_uuids,
raise_person_version,
)
@@ -67,7 +66,6 @@ _TRANSIENT_RPC_CODES = frozenset(
}
)
-_DB_TIMEOUT_METADATA_KEY = "x-db-timeout"
_FLUSH_TIMEOUT_SECONDS = 5 * 60
@@ -204,30 +202,6 @@ def _is_transient(exc: BaseException) -> bool:
)
-def is_retryable(exc: BaseException) -> bool:
- """Whether a repair failed on a transient error that a later attempt can get past: a busy person, or
- personhog or ClickHouse briefly unavailable."""
- return _is_transient(exc)
-
-
-def is_person_busy(exc: BaseException) -> bool:
- """Whether another operation, such as a merge or delete, held the person: its lifecycle mark was claimed, or
- a wait for its row lock timed out. Other transient errors mean a service was unavailable."""
- if is_transient_rpc_error(exc, codes=frozenset({grpc.StatusCode.FAILED_PRECONDITION})):
- return True
- current: BaseException | None = exc
- while current is not None:
- if isinstance(current, grpc.RpcError):
- code = getattr(current, "code", None)
- trailing = getattr(current, "trailing_metadata", None)
- if not callable(code) or code() != grpc.StatusCode.DEADLINE_EXCEEDED or not callable(trailing):
- return False
- # personhog-replica names the timeout that ended the call; only a lock wait means the person was busy.
- return any(key == _DB_TIMEOUT_METADATA_KEY and value == "lock_timeout" for key, value in trailing() or ())
- current = current.__cause__
- return False
-
-
def _retry_transient(fn: Callable[[], _T], *, what: str, log: Callable[[str], None]) -> _T:
"""Run ``fn`` again after a transient ClickHouse or personhog error, then re-raise once the retries run out.
@@ -263,7 +237,7 @@ def _execute_plan(
)
if apply and stale_merge_distinct_id is not None:
missing = stale_merge._clickhouse_only_properties(plan)
- # A later reset that finds nothing missing raises Postgres. Capture accepting the $set does not mean
+ # A later repair 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.
if missing:
# The $set_once event lands on ingestion like any write, so it is paced like one.
@@ -545,35 +519,3 @@ def repair_persons(
if undelivered:
log(f"{undelivered} ClickHouse messages were not delivered; rerun the repair for the same input")
return outcomes.summary(applied=apply, persons=processed, undelivered=undelivered)
-
-
-def repair_distinct_id(
- team_id: int, distinct_id: str, *, delivery_timeout_seconds: float
-) -> datatypes.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 repair_plan._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.py
index 4eedd00638f0..6b208722d9d9 100644
--- a/posthog/models/person/test/test_divergence.py
+++ b/posthog/models/person/test/test_divergence.py
@@ -41,7 +41,7 @@ from posthog.models.person.divergence.fleet_scans import (
scan_stale_persons,
scan_swept_persons,
)
-from posthog.models.person.divergence.repairs import _WritePacer, repair_distinct_id, repair_persons
+from posthog.models.person.divergence.repairs import _WritePacer, repair_persons
from posthog.models.person.divergence.team_check import _team_check_modulus, check_team
from posthog.models.person.sql import BULK_INSERT_PERSON_DISTINCT_ID2
from posthog.models.person.test.divergence_fixtures import rpc_error
@@ -885,51 +885,6 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):
assert self._pg_mapping_versions(person)["divergent"] == 106
assert self._ch_mapping("divergent") == (str(person.uuid), 0, 106)
- @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.repair_plan._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}
@@ -951,15 +906,23 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):
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:
+ def _repair_with_stale_merge(self, person: Person) -> RepairSummary:
+ return repair_persons(
+ [PersonRef(team_id=self.team.pk, person_uuid=str(person.uuid))],
+ apply=True,
+ on_action=lambda _: None,
+ log=lambda _: None,
+ stale_merge_distinct_ids={str(person.uuid): "target"},
+ )
+
+ def test_a_stale_merge_raises_the_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.stale_merge.capture_internal") as capture:
- first = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)
+ first = self._repair_with_stale_merge(person)
- 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)
@@ -979,22 +942,20 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):
stored.properties = json.dumps({**CH_ONLY_PROPERTIES, **PG_PROPERTIES}).encode()
with patch("posthog.models.person.divergence.stale_merge.capture_internal") as capture:
- second = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)
+ second = self._repair_with_stale_merge(person)
- 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:
+ def test_a_stale_merge_republishes_a_person_whose_clickhouse_properties_postgres_already_holds(self) -> None:
person = self._stale_person_with_target(CH_PROPERTIES)
with patch("posthog.models.person.divergence.stale_merge.capture_internal") as capture:
- summary = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)
+ summary = self._repair_with_stale_merge(person)
- 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)
@@ -1006,7 +967,7 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):
("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(
+ def test_a_stale_merge_leaves_the_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})
@@ -1019,9 +980,8 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):
patch("posthog.models.person.divergence.stale_merge._STALE_MERGE_MAX_BYTES", max_bytes),
patch("posthog.models.person.divergence.stale_merge.capture_internal", return_value=failing) as capture,
):
- summary = repair_distinct_id(self.team.pk, "target", delivery_timeout_seconds=1)
+ summary = self._repair_with_stale_merge(person)
- 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("raise_person_version_floors")
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 4c2b436b81d0..1fe81c755e22 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -4432,18 +4432,6 @@ export const PersonsPropertiesAtTimeRetrieveFormat = {
Json: 'json',
} as const
-export type PersonsResetPersonDistinctIdCreateParams = {
- format?: PersonsResetPersonDistinctIdCreateFormat
-}
-
-export type PersonsResetPersonDistinctIdCreateFormat =
- (typeof PersonsResetPersonDistinctIdCreateFormat)[keyof typeof PersonsResetPersonDistinctIdCreateFormat]
-
-export const PersonsResetPersonDistinctIdCreateFormat = {
- Csv: 'csv',
- Json: 'json',
-} as const
-
export type PersonsValuesRetrieveParams = {
format?: PersonsValuesRetrieveFormat
/**
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index a3d8c54a6448..0bf943077aa8 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -36,7 +36,6 @@ import type {
PersonsPropertiesAtTimeRetrieveParams,
PersonsPropertiesTimelineCreateParams,
PersonsPushNotificationsListParams,
- PersonsResetPersonDistinctIdCreateParams,
PersonsRetrieveParams,
PersonsSplitCreateParams,
PersonsUpdateParams,
@@ -686,42 +685,6 @@ export const personsPropertiesAtTimeRetrieve = async (
})
}
-export const getPersonsResetPersonDistinctIdCreateUrl = (
- projectId: string,
- params?: PersonsResetPersonDistinctIdCreateParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/persons/reset_person_distinct_id/?${stringifiedParams}`
- : `/api/projects/${projectId}/persons/reset_person_distinct_id/`
-}
-
-/**
- * Fix a distinct_id that stays hidden after its person was deleted and created again. Does nothing if no live person uses this distinct_id. In that case, send a new event for it instead.
- */
-export const personsResetPersonDistinctIdCreate = async (
- projectId: string,
- personRecordApi?: NonReadonly<PersonRecordApi>,
- params?: PersonsResetPersonDistinctIdCreateParams,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getPersonsResetPersonDistinctIdCreateUrl(projectId, params), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(personRecordApi),
- })
-}
-
export const getPersonsValuesRetrieveUrl = (projectId: string, params: PersonsValuesRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.ts
index c7765f47cc8e..c01b1c4bad9a 100644
--- a/products/persons/frontend/generated/api.zod.ts
+++ b/products/persons/frontend/generated/api.zod.ts
@@ -141,13 +141,3 @@ export const PersonsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
.default(personsBulkDeleteCreateBodyKeepPersonDefault)
.describe('If true, keep the person records but delete their events and recordings.'),
})
-
-/**
- * Fix a distinct_id that stays hidden after its person was deleted and created again. Does nothing if no live person uses this distinct_id. In that case, send a new event for it instead.
- */
-export const PersonsResetPersonDistinctIdCreateBody = /* @__PURE__ */ zod.object({
- properties: zod
- .unknown()
- .optional()
- .describe('Key-value map of person properties set via $set and $set_once operations.'),
-})
diff --git a/products/persons/frontend/logics/personsSceneLogic.test.ts b/products/persons/frontend/logics/personsSceneLogic.test.ts
index d9cb93c9d5fc..7d426dfbba06 100644
--- a/products/persons/frontend/logics/personsSceneLogic.test.ts
+++ b/products/persons/frontend/logics/personsSceneLogic.test.ts
@@ -3,8 +3,6 @@ import { expectLogic } from 'kea-test-utils'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
-import { useMocks } from '~/mocks/jest'
-import { MockSignature } from '~/mocks/utils'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -18,11 +16,6 @@ describe('personsSceneLogic', () => {
let logic: ReturnType<typeof personsSceneLogic.build>
beforeEach(() => {
- useMocks({
- post: {
- '/api/environments/:team_id/persons/reset_person_distinct_id/': [200, {}],
- },
- })
initKeaTests()
sceneLogic({ scenes }).mount()
logic = personsSceneLogic()
@@ -101,23 +94,6 @@ describe('personsSceneLogic', () => {
})
})
- describe('resetDeletedDistinctId listener', () => {
- it('calls the API to reset a distinct ID', async () => {
- const spy: MockSignature = jest.fn(() => [200, {}])
- useMocks({
- post: {
- '/api/environments/:team_id/persons/reset_person_distinct_id/': spy,
- },
- })
-
- await expectLogic(logic, () => {
- logic.actions.resetDeletedDistinctId('some-distinct-id')
- }).toFinishAllListeners()
-
- expect(spy).toHaveBeenCalledTimes(1)
- })
- })
-
describe('isPeopleListDefaultQuery', () => {
const defaultSelect = [...defaultDataTableColumns(NodeKind.ActorsQuery, false), 'person.$delete']
const lastSeenAtSelect = [...defaultDataTableColumns(NodeKind.ActorsQuery, true), 'person.$delete']
diff --git a/products/persons/frontend/logics/personsSceneLogic.ts b/products/persons/frontend/logics/personsSceneLogic.ts
index 7f3ae993e79c..a30c8d457cad 100644
--- a/products/persons/frontend/logics/personsSceneLogic.ts
+++ b/products/persons/frontend/logics/personsSceneLogic.ts
@@ -1,10 +1,9 @@
import { deepEqual as equal } from 'fast-equals'
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
-import api from 'lib/api'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
@@ -61,9 +60,6 @@ export interface personsSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsSceneLogicActions {
- resetDeletedDistinctId: (distinct_id: string) => {
- distinct_id: string
- }
setIsBannerLoading: (isBannerLoading: boolean) => {
isBannerLoading: boolean
}
@@ -97,7 +93,6 @@ export const personsSceneLogic = kea<personsSceneLogicType>([
actions({
setQuery: (query: DataTableNode) => ({ query }),
- resetDeletedDistinctId: (distinct_id: string) => ({ distinct_id }),
setShowDisplayNameNudge: (showDisplayNameNudge: boolean) => ({ showDisplayNameNudge }),
setIsBannerLoading: (isBannerLoading: boolean) => ({ isBannerLoading }),
}),
@@ -126,15 +121,6 @@ export const personsSceneLogic = kea<personsSceneLogicType>([
],
}),
- listeners({
- resetDeletedDistinctId: async ({ distinct_id }) => {
- await api.persons.resetPersonDistinctId(distinct_id)
- lemonToast.success(
- "Distinct ID reset. If the person doesn't show up within a few minutes, run the reset again."
- )
- },
- }),
-
selectors({
defaultQuery: [
(s) => [s.currentTeam],
diff --git a/products/persons/frontend/pages/PersonsScene.tsx b/products/persons/frontend/pages/PersonsScene.tsx
index fe8def46a108..c0ca27732906 100644
--- a/products/persons/frontend/pages/PersonsScene.tsx
+++ b/products/persons/frontend/pages/PersonsScene.tsx
@@ -1,14 +1,9 @@
-import { useActions, useAsyncActions, useValues } from 'kea'
-
-import { IconRewind } from '@posthog/icons'
-import { LemonDialog, LemonInput } from '@posthog/lemon-ui'
+import { useActions, useValues } from 'kea'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { isUUIDLike } from 'lib/utils/guards'
import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'
import { sceneConfigurations } from 'scenes/scenes'
@@ -17,9 +12,8 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneMenuBar, SceneMenuBarItem, SceneMenuBarMenu } from '~/layout/scenes/components/SceneMenuBar'
+import { SceneMenuBar, SceneMenuBarMenu } from '~/layout/scenes/components/SceneMenuBar'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { ScenePanel, ScenePanelActionsSection } from '~/layout/scenes/SceneLayout'
import { Query } from '~/queries/Query/Query'
import { ActorsQuery, ProductKey } from '~/queries/schema/schema-general'
import { ActivityTab, CustomerProfileScope, OnboardingStepKey } from '~/types'
@@ -39,7 +33,6 @@ export const scene: SceneExport = {
export function PersonsScene(): JSX.Element {
const { query } = useValues(personsSceneLogic)
const { setQuery } = useActions(personsSceneLogic)
- const { resetDeletedDistinctId } = useAsyncActions(personsSceneLogic)
const { currentTeam, baseCurrency } = useValues(teamLogic)
const { loadConfigs } = useActions(customerProfileConfigLogic({ scope: CustomerProfileScope.PERSON }))
const queryUniqueKey = 'persons-query'
@@ -55,25 +48,6 @@ export function PersonsScene(): JSX.Element {
loadConfigs()
})
- const onResetDeletedPerson = (): void => {
- LemonDialog.openForm({
- width: '30rem',
- title: 'Reset deleted person',
- description: `Use this if a deleted person's distinct ID gets new events, but no person shows up for it.
- Resetting the distinct ID makes that person show up again.`,
- initialValues: { distinct_id: '' },
- content: (
- <LemonField name="distinct_id" label="Distinct ID to reset">
- <LemonInput type="text" autoFocus />
- </LemonField>
- ),
- errors: {
- distinct_id: (distinct_id) => (!distinct_id ? 'This is required' : undefined),
- },
- onSubmit: async ({ distinct_id }) => await resetDeletedDistinctId(distinct_id),
- })
- }
-
return (
<SceneContent>
<ActivitySceneTabs activeKey="persons" />
@@ -82,15 +56,6 @@ export function PersonsScene(): JSX.Element {
<SceneMenuBar>
<SceneMenuBarMenu label="File" dataAttr="persons-menubar-file">
<SceneMenuBarFileItems dataAttrKey="persons" />
- <SceneMenuBarItem
- variant="destructive"
- opensFloatingUi
- onClick={onResetDeletedPerson}
- data-attr="persons-menubar-reset-deleted"
- >
- <IconRewind />
- Reset a deleted person
- </SceneMenuBarItem>
</SceneMenuBarMenu>
</SceneMenuBar>
)}
@@ -104,39 +69,6 @@ export function PersonsScene(): JSX.Element {
actions={
<>
<FeedbackButton id="customer-analytics-people-list-feedback-button" />
- <ScenePanel>
- <ScenePanelActionsSection>
- <ButtonPrimitive
- menuItem
- variant="danger"
- onClick={() => {
- LemonDialog.openForm({
- width: '30rem',
- title: 'Reset deleted person',
- description: `Use this if a deleted person's distinct ID gets new events, but no person shows up for it.
- Resetting the distinct ID makes that person show up again.`,
- initialValues: {
- distinct_id: '',
- },
- content: (
- <LemonField name="distinct_id" label="Distinct ID to reset">
- <LemonInput type="text" autoFocus />
- </LemonField>
- ),
- errors: {
- distinct_id: (distinct_id) =>
- !distinct_id ? 'This is required' : undefined,
- },
- onSubmit: async ({ distinct_id }) =>
- await resetDeletedDistinctId(distinct_id),
- })
- }}
- >
- <IconRewind />
- Reset a deleted person...
- </ButtonPrimitive>
- </ScenePanelActionsSection>
- </ScenePanel>
</>
}
/>
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2101cca20e89..0d1d9dcff065 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -141054,18 +141054,6 @@ export namespace Schemas {
Json: 'json',
} as const;
- export type PersonsResetPersonDistinctIdCreateParams = {
- format?: PersonsResetPersonDistinctIdCreateFormat;
- };
-
- export type PersonsResetPersonDistinctIdCreateFormat = typeof PersonsResetPersonDistinctIdCreateFormat[keyof typeof PersonsResetPersonDistinctIdCreateFormat];
-
-
- export const PersonsResetPersonDistinctIdCreateFormat = {
- Csv: 'csv',
- Json: 'json',
- } as const;
-
export type PersonsValuesRetrieveParams = {
format?: PersonsValuesRetrieveFormat;
/**