: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
feat(ingestion): stop deleting personless distinct ids on team deletion (#84369)
José Sequeira9c37c93002e3
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 285edec7efad..eb981f392914 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -93,7 +93,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"CoreEvent","ElementGroup","Event",- "PersonlessDistinctId","SessionRecordingEvent",# --- Persons system (managed separately, not looked up by user input) ---"FlatPersonOverride",diff --git a/.semgrep/rules/security/no-direct-persons-db-orm.yaml b/.semgrep/rules/security/no-direct-persons-db-orm.yamlindex 103279e83289..96dac194fe22 100644--- a/.semgrep/rules/security/no-direct-persons-db-orm.yaml+++ b/.semgrep/rules/security/no-direct-persons-db-orm.yaml@@ -17,7 +17,7 @@ rules:- metavariable-regex:metavariable: $MODELregex: >-- ^(Person|PersonDistinctId|PersonlessDistinctId|PersonOverrideMapping|PersonOverride|PendingPersonOverride|FlatPersonOverride|FeatureFlagHashKeyOverride|CohortPeople|Group|GroupTypeMapping)$+ ^(Person|PersonDistinctId|PersonOverrideMapping|PersonOverride|PendingPersonOverride|FlatPersonOverride|FeatureFlagHashKeyOverride|CohortPeople|Group|GroupTypeMapping)$paths:exclude:# personhog client implementationdiff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex d02988dcd635..184cc2ed6e4d 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -45,7 +45,6 @@ BULK_DELETE_PERSONS_DB_MODELS: dict[str, str] = {"grouptypemapping": "Group Type Mappings","person": "Persons","persondistinctid": "Person Distinct IDs",- "personlessdistinctid": "Personless Distinct IDs",}diff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.pyindex 64f0dd0b0d0f..908d12c32671 100644--- a/posthog/api/test/test_team_deletion.py+++ b/posthog/api/test/test_team_deletion.py@@ -172,7 +172,6 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):fake = get_active_fake()for rpc in ["delete_hash_key_overrides_by_teams",- "delete_personless_distinct_ids_batch_for_team","delete_persons_batch_for_team","delete_groups_batch_for_team","delete_group_type_mappings_batch_for_team",diff --git a/posthog/migrations/1307_remove_personlessdistinctid.py b/posthog/migrations/1307_remove_personlessdistinctid.pynew file mode 100644index 000000000000..c4d712fea4fa--- /dev/null+++ b/posthog/migrations/1307_remove_personlessdistinctid.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.17 on 2026-08-18 12:14++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1306_add_youtube_analytics_integration_kind")]++ operations = [+ # State-only: the table lives in the persons database, whose schema is owned by+ # rust/persons_migrations. The DROP TABLE happens there once writes are confirmed stopped.+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="PersonlessDistinctId",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex aa8e754276a8..d3ccb35abd0a 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1306_add_youtube_analytics_integration_kind+1307_remove_personlessdistinctiddiff --git a/posthog/models/person/__init__.py b/posthog/models/person/__init__.pyindex cf1440d842be..dd9b0faeef6d 100644--- a/posthog/models/person/__init__.py+++ b/posthog/models/person/__init__.py@@ -1,4 +1,4 @@-from .person import Person, PersonDistinctId, PersonlessDistinctId, PersonOverride, PersonOverrideMapping+from .person import Person, PersonDistinctId, PersonOverride, PersonOverrideMappingfrom .point_in_time_properties import build_person_properties_at_time__all__ = [@@ -6,6 +6,5 @@ __all__ = ["PersonDistinctId","PersonOverride","PersonOverrideMapping",- "PersonlessDistinctId","build_person_properties_at_time",]diff --git a/posthog/models/person/person.py b/posthog/models/person/person.pyindex 5a164a9ac780..f29e9c371b4d 100644--- a/posthog/models/person/person.py+++ b/posthog/models/person/person.py@@ -449,22 +449,6 @@ class PersonDistinctId(models.Model):constraints = [models.UniqueConstraint(fields=["team", "distinct_id"], name="unique distinct_id for team")]-class PersonlessDistinctId(models.Model):- id = models.BigAutoField(primary_key=True)- # DO_NOTHING + db_constraint=False: Team deletion handled manually, may be cross-database- team = models.ForeignKey("Team", on_delete=models.DO_NOTHING, db_index=False, db_constraint=False)- distinct_id = models.CharField(max_length=400)- is_merged = models.BooleanField(default=False)- created_at = models.DateTimeField(auto_now_add=True, blank=True)-- class Meta:- # migrations managed via rust/persons_migrations- managed = False- constraints = [- models.UniqueConstraint(fields=["team", "distinct_id"], name="unique personless distinct_id for team")- ]--class PersonOverrideMapping(models.Model):# XXX: NOT USED, see https://github.com/PostHog/posthog/pull/23616diff --git a/posthog/models/person/test/test_delete_personless_personhog.py b/posthog/models/person/test/test_delete_personless_personhog.pydeleted file mode 100644index 7bf02522043e..000000000000--- a/posthog/models/person/test/test_delete_personless_personhog.py+++ /dev/null@@ -1,48 +0,0 @@-"""Tests for personless distinct ID deletion via personhog RPC.--Covers routing and RPC behavior for _delete_personless_distinct_ids_for_teams-(team deletion path), which routes through delete_personless_distinct_ids_batch_for_team.-"""--from posthog.test.base import BaseTest-from unittest.mock import MagicMock--from django.test import SimpleTestCase--from posthog.models.team.util import _delete_personless_distinct_ids_for_teams-from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.personhog_client.proto import DeletePersonlessDistinctIdsBatchForTeamResponse---class TestDeletePersonlessDistinctIdsForTeamsRouting(SimpleTestCase):- def test_personhog_loops_until_zero_deleted(self):- # The real RPC returns the number of rows deleted per batch; the caller loops- # until it returns 0. The fake hardcodes 0, so override it with a sequence that- # forces the while loop to run multiple times before breaking.- with fake_personhog_client() as fake:- fake.delete_personless_distinct_ids_batch_for_team = MagicMock(- side_effect=[- DeletePersonlessDistinctIdsBatchForTeamResponse(deleted_count=10000),- DeletePersonlessDistinctIdsBatchForTeamResponse(deleted_count=42),- DeletePersonlessDistinctIdsBatchForTeamResponse(deleted_count=0),- ]- )-- _delete_personless_distinct_ids_for_teams([1])-- # Looped until a batch returned 0: three calls, last returning 0.- assert fake.delete_personless_distinct_ids_batch_for_team.call_count == 3---class TestDeletePersonlessDistinctIdsForTeamsRPC(BaseTest):- def test_personhog_path_calls_batch_rpc_per_team(self):- other_team = self.organization.teams.create(name="Other Team")-- with fake_personhog_client() as fake:- _delete_personless_distinct_ids_for_teams([self.team.pk, other_team.pk])-- calls = fake.assert_called("delete_personless_distinct_ids_batch_for_team")- team_ids_called = {c.request.team_id for c in calls}- assert self.team.pk in team_ids_called- assert other_team.pk in team_ids_called- assert all(c.request.batch_size == 2000 for c in calls)diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 215a31276bd6..4f76033397f3 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -67,7 +67,6 @@ def delete_bulky_postgres_data(team_ids: list[int]):# Each phase is its own batched helper so the Temporal deletion workflow can run them# as separate, individually-retryable activities while Celery keeps calling them in sequence._delete_misc_small_tables_for_teams(team_ids)- _delete_personless_distinct_ids_for_teams(team_ids)_delete_cohort_members_for_all_teams(team_ids)_delete_groups_for_teams(team_ids)_delete_group_type_mappings_for_teams(team_ids)@@ -175,34 +174,6 @@ def _delete_hash_key_overrides_for_teams(team_ids: list[int]) -> None:)-def _delete_personless_distinct_ids_for_teams(team_ids: list[int]) -> None:- """Delete posthog_personlessdistinctid rows for teams via personhog RPC."""- from functools import partial-- from posthog.personhog_client.client import personhog_call-- for team_id in team_ids:- personhog_call(- "delete_personless_distinct_ids_for_team",- partial(_delete_personless_distinct_ids_for_team_via_personhog, team_id),- )---def _delete_personless_distinct_ids_for_team_via_personhog(team_id: int) -> None:- from posthog.personhog_client.client import require_personhog_client- from posthog.personhog_client.proto import DeletePersonlessDistinctIdsBatchForTeamRequest-- client = require_personhog_client()-- while True:- resp = client.delete_personless_distinct_ids_batch_for_team(- DeletePersonlessDistinctIdsBatchForTeamRequest(team_id=team_id, batch_size=TEAM_DELETE_BATCH_SIZE),- timeout=TEAM_DELETE_RPC_TIMEOUT_SECONDS,- )- if resp.deleted_count == 0:- break--def _delete_cohort_members_for_all_teams(team_ids: list[int]) -> None:# Resolve cohort ids from the default DB first to avoid a cross-database join:# CohortPeople lives in persons_db, Cohort in the default db.diff --git a/posthog/person_db_router.py b/posthog/person_db_router.pyindex b6117d4e0fb0..551064ed2309 100644--- a/posthog/person_db_router.py+++ b/posthog/person_db_router.py@@ -67,7 +67,6 @@ def allow_persons_orm():PERSONS_DB_MODELS = {"person","persondistinctid",- "personlessdistinctid","personoverridemapping","personoverride","pendingpersonoverride",diff --git a/posthog/personhog_client/README.md b/posthog/personhog_client/README.mdindex c114aac4ae89..99b4fd97622c 100644--- a/posthog/personhog_client/README.md+++ b/posthog/personhog_client/README.md@@ -29,7 +29,6 @@ Do not query them directly — use the routed helpers or client RPCs.| `posthog_pendingpersonoverride` | `PendingPersonOverride` | Pending person merge overrides || `posthog_flatpersonoverride` | `FlatPersonOverride` | Flattened person overrides || `posthog_featureflaghashkeyoverride` | `FeatureFlagHashKeyOverride` | Feature flag hash key overrides |-| `posthog_personlessdistinctid` | `PersonlessDistinctId` | Personless distinct IDs || `posthog_personoverridemapping` | `PersonOverrideMapping` | Person override mappings |## Client singletondiff --git a/posthog/personhog_client/client.py b/posthog/personhog_client/client.pyindex 13049469f3b5..f1439153a040 100644--- a/posthog/personhog_client/client.py+++ b/posthog/personhog_client/client.py@@ -38,8 +38,6 @@ from posthog.personhog_client.proto import (DeleteGroupTypeMappingsBatchForTeamResponse,DeleteHashKeyOverridesByTeamsRequest,DeleteHashKeyOverridesByTeamsResponse,- DeletePersonlessDistinctIdsBatchForTeamRequest,- DeletePersonlessDistinctIdsBatchForTeamResponse,DeletePersonsBatchForTeamRequest,DeletePersonsBatchForTeamResponse,DeletePersonsRequest,@@ -218,11 +216,6 @@ class PersonHogClient:) -> DeletePersonsBatchForTeamResponse:return self._stub.DeletePersonsBatchForTeam(request, timeout=timeout or self._timeout)- def delete_personless_distinct_ids_batch_for_team(- self, request: DeletePersonlessDistinctIdsBatchForTeamRequest, timeout: float | None = None- ) -> DeletePersonlessDistinctIdsBatchForTeamResponse:- return self._stub.DeletePersonlessDistinctIdsBatchForTeam(request, timeout=timeout or self._timeout)-# -- Person split --def split_person(self, request: SplitPersonRequest, timeout: float | None = None) -> SplitPersonResponse:diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 112f2ee854f4..1df32f952c71 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -611,15 +611,6 @@ class FakePersonHogClient:self.calls.append(_Call("delete_persons_batch_for_team", request, response))return response- def delete_personless_distinct_ids_batch_for_team(- self, request: person_pb2.DeletePersonlessDistinctIdsBatchForTeamRequest, timeout: float | None = None- ) -> person_pb2.DeletePersonlessDistinctIdsBatchForTeamResponse:- # The fake does not model personless distinct IDs, so this records the- # call for assertions and reports nothing deleted.- response = person_pb2.DeletePersonlessDistinctIdsBatchForTeamResponse(deleted_count=0)- self.calls.append(_Call("delete_personless_distinct_ids_batch_for_team", request, response))- return response-# ── Person split ──────────────────────────────────────────────────def split_person(diff --git a/posthog/personhog_client/proto/__init__.py b/posthog/personhog_client/proto/__init__.pyindex 58c58aa90225..58a571f9e8fc 100644--- a/posthog/personhog_client/proto/__init__.py+++ b/posthog/personhog_client/proto/__init__.py@@ -66,8 +66,6 @@ from posthog.personhog_client.proto.generated.personhog.types.v1.group_pb2 imporUpdateGroupTypeMappingResponse,)from posthog.personhog_client.proto.generated.personhog.types.v1.person_pb2 import (- DeletePersonlessDistinctIdsBatchForTeamRequest,- DeletePersonlessDistinctIdsBatchForTeamResponse,DeletePersonsBatchForTeamRequest,DeletePersonsBatchForTeamResponse,DeletePersonsRequest,diff --git a/posthog/temporal/delete_teams/__init__.py b/posthog/temporal/delete_teams/__init__.pyindex cab79be41b97..1a3333cbf24a 100644--- a/posthog/temporal/delete_teams/__init__.py+++ b/posthog/temporal/delete_teams/__init__.py@@ -6,7 +6,6 @@ from posthog.temporal.delete_teams.activities import (delete_loop_trigger_schedules_activity,delete_misc_small_tables_activity,delete_organization_record_activity,- delete_personless_distinct_ids_activity,delete_project_record_activity,delete_team_persons_activity,delete_team_records_activity,@@ -32,7 +31,6 @@ ACTIVITIES = [deprovision_managed_warehouse_activity,queue_recording_deletions_activity,delete_misc_small_tables_activity,- delete_personless_distinct_ids_activity,delete_cohort_members_activity,delete_groups_activity,delete_team_persons_activity,diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pyindex 467ffc9b4fb9..b0264d71a9c9 100644--- a/posthog/temporal/delete_teams/activities.py+++ b/posthog/temporal/delete_teams/activities.py@@ -37,14 +37,6 @@ async def delete_misc_small_tables_activity(inputs: TeamDataActivityInputs) -> Nawait database_sync_to_async_pool(_delete_misc_small_tables_for_teams)(inputs.team_ids)-async def delete_personless_distinct_ids_activity(inputs: TeamDataActivityInputs) -> None:- async with Heartbeater():- from posthog.models.team.util import _delete_personless_distinct_ids_for_teams-- await database_sync_to_async_pool(_delete_personless_distinct_ids_for_teams)(inputs.team_ids)--@temporalio.activity.defnasync def delete_cohort_members_activity(inputs: TeamDataActivityInputs) -> None:async with Heartbeater():diff --git a/posthog/temporal/delete_teams/workflows.py b/posthog/temporal/delete_teams/workflows.pyindex 39a1fc335bac..05b817aacd1e 100644--- a/posthog/temporal/delete_teams/workflows.py+++ b/posthog/temporal/delete_teams/workflows.py@@ -13,7 +13,6 @@ from posthog.temporal.delete_teams.activities import (delete_loop_trigger_schedules_activity,delete_misc_small_tables_activity,delete_organization_record_activity,- delete_personless_distinct_ids_activity,delete_project_record_activity,delete_team_persons_activity,delete_team_records_activity,@@ -62,7 +61,6 @@ EMAIL_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=30)# Bulky Postgres phases, run in dependency-safe order (each its own retryable activity).BULKY_POSTGRES_ACTIVITIES = (delete_misc_small_tables_activity,- delete_personless_distinct_ids_activity,delete_cohort_members_activity,delete_groups_activity,delete_team_persons_activity,diff --git a/posthog/temporal/tests/delete_teams/test_workflows.py b/posthog/temporal/tests/delete_teams/test_workflows.pyindex 4de890a5440f..aa2deee5cda0 100644--- a/posthog/temporal/tests/delete_teams/test_workflows.py+++ b/posthog/temporal/tests/delete_teams/test_workflows.py@@ -35,7 +35,6 @@ WORKFLOWS = [DeleteTeamsDataWorkflow, DeleteProjectDataWorkflow, DeleteOrganizatCORE_ACTIVITY_ORDER = ["queue_recording_deletions_activity","delete_misc_small_tables_activity",- "delete_personless_distinct_ids_activity","delete_cohort_members_activity","delete_groups_activity","delete_team_persons_activity",