: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(teams): batch-delete event properties before the team row (#115657)
Eli Reismanb177f55cc771
diff --git a/posthog/models/team/test_util_deletion.py b/posthog/models/team/test_util_deletion.pyindex 847ae07e9e48..28a44c1e9e56 100644--- a/posthog/models/team/test_util_deletion.py+++ b/posthog/models/team/test_util_deletion.py@@ -1,15 +1,23 @@+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase+from parameterized import parameterized++from posthog.models.team import Teamfrom posthog.models.team.util import (RETIRED_LOOP_TABLES,+ TeamPurgeStopped,+ _delete_event_properties_for_teams,_delete_group_type_mappings_for_teams,_delete_groups_for_teams,_delete_hash_key_overrides_for_teams,_delete_retired_loops_for_teams,)+from products.event_definitions.backend.models import EventProperty+_CLIENT_PATCH = "posthog.personhog_client.client.get_personhog_client"@@ -151,3 +159,31 @@ class TestDeleteHashKeyOverridesForTeams(SimpleTestCase):_delete_hash_key_overrides_for_teams([])mock_get_client.return_value.delete_hash_key_overrides_by_teams.assert_not_called()+++@patch("posthog.models.team.util.time.sleep")+class TestDeleteEventPropertiesForTeams(BaseTest):+ def _create_event_properties(self, team: Team) -> None:+ # Three rows share one property, so small batches end inside a run of equal property names.+ pairs = [("e1", "shared"), ("e2", "shared"), ("e3", "shared"), ("e1", "a"), ("e2", "z")]+ EventProperty.objects.bulk_create(EventProperty(team=team, event=e, property=p) for e, p in pairs)++ @parameterized.expand([(1,), (2,), (3,), (10000,)])+ def test_deletes_every_row_of_the_team_and_no_other(self, _sleep: MagicMock, batch_size: int) -> None:+ other_team = Team.objects.create(organization=self.organization)+ self._create_event_properties(self.team)+ self._create_event_properties(other_team)++ _delete_event_properties_for_teams([self.team.id], batch_size=batch_size)++ assert not EventProperty.objects.filter(team_id=self.team.id).exists()+ assert EventProperty.objects.filter(team_id=other_team.id).count() == 5++ def test_stop_ends_the_purge_between_batches(self, _sleep: MagicMock) -> None:+ self._create_event_properties(self.team)+ stops = iter([False, True])++ with self.assertRaises(TeamPurgeStopped):+ _delete_event_properties_for_teams([self.team.id], should_stop=lambda: next(stops), batch_size=2)++ assert EventProperty.objects.filter(team_id=self.team.id).count() == 3diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex bfd75f653748..6775e0dc10f5 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -13,6 +13,7 @@ from posthog.models.async_migration import is_async_migration_completefrom products.ai_training.backend.facade.api import queue_training_deletionfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.event_definitions.backend.logic.event_property_purge import delete_event_properties_for_teamlogger = structlog.get_logger(__name__)@@ -68,6 +69,7 @@ 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_event_properties_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)@@ -156,6 +158,18 @@ def _delete_retired_team_rows(tables: tuple[str, ...], team_ids: list[int], batctime.sleep(0.1)+def _delete_event_properties_for_teams(+ team_ids: list[int], should_stop: Callable[[], bool] | None = None, batch_size: int = 10000+) -> None:+ """Batch-delete the teams' event properties before the Team cascade, which would delete them in one statement.++ ``should_stop`` is checked before each batch.+ """+ for team_id in team_ids:+ if not delete_event_properties_for_team(team_id, should_stop=should_stop, batch_size=batch_size):+ raise TeamPurgeStopped(f"The event property purge of team {team_id} stopped before it finished")++def _delete_hash_key_overrides_for_teams(team_ids: list[int]) -> None:"""Delete FeatureFlagHashKeyOverride rows for the given teams via personhog.diff --git a/posthog/temporal/delete_teams/__init__.py b/posthog/temporal/delete_teams/__init__.pyindex 8f775109f78a..1552513ed536 100644--- a/posthog/temporal/delete_teams/__init__.py+++ b/posthog/temporal/delete_teams/__init__.py@@ -3,6 +3,7 @@ from posthog.temporal.delete_teams.activities import (delete_batch_exports_activity,delete_cohort_members_activity,delete_data_modeling_schedules_activity,+ delete_event_properties_activity,delete_groups_activity,delete_loop_trigger_schedules_activity,delete_misc_small_tables_activity,@@ -35,6 +36,7 @@ ACTIVITIES = [delete_cohort_members_activity,delete_groups_activity,delete_team_persons_activity,+ delete_event_properties_activity,delete_batch_exports_activity,delete_data_modeling_schedules_activity,delete_loop_trigger_schedules_activity,diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pyindex a9b8484f8f69..147e2351984b 100644--- a/posthog/temporal/delete_teams/activities.py+++ b/posthog/temporal/delete_teams/activities.py@@ -37,6 +37,17 @@ 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_event_properties_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import _delete_event_properties_for_teams++ # A cancel does not stop the worker thread, so the purge checks for it between batches.+ await database_sync_to_async_pool(_delete_event_properties_for_teams)(+ inputs.team_ids, should_stop=temporalio.activity.is_cancelled+ )++@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 a04b3515e153..3e945f1e5f3b 100644--- a/posthog/temporal/delete_teams/workflows.py+++ b/posthog/temporal/delete_teams/workflows.py@@ -10,6 +10,7 @@ from posthog.temporal.delete_teams.activities import (delete_batch_exports_activity,delete_cohort_members_activity,delete_data_modeling_schedules_activity,+ delete_event_properties_activity,delete_groups_activity,delete_loop_trigger_schedules_activity,delete_misc_small_tables_activity,@@ -113,6 +114,17 @@ class DeleteTeamsDataWorkflow(PostHogWorkflow):retry_policy=DELETE_RETRY_POLICY,)+ # Gated with `patched` so in-flight deletions from before this deploy don't fail replay on a new+ # command. The purge leaves the Team cascade no event properties to delete in one statement.+ if temporalio.workflow.patched("delete-event-properties"):+ await temporalio.workflow.execute_activity(+ delete_event_properties_activity,+ team_inputs,+ start_to_close_timeout=HEAVY_ACTIVITY_TIMEOUT,+ heartbeat_timeout=HEAVY_HEARTBEAT_TIMEOUT,+ retry_policy=DELETE_RETRY_POLICY,+ )+# Temporal schedules owned by the teams must be torn down explicitly (CASCADE won't).await temporalio.workflow.execute_activity(delete_batch_exports_activity,diff --git a/posthog/temporal/tests/delete_teams/test_workflows.py b/posthog/temporal/tests/delete_teams/test_workflows.pyindex 4cab53ed2c24..381437bd704f 100644--- a/posthog/temporal/tests/delete_teams/test_workflows.py+++ b/posthog/temporal/tests/delete_teams/test_workflows.py@@ -38,6 +38,7 @@ CORE_ACTIVITY_ORDER = ["delete_cohort_members_activity","delete_groups_activity","delete_team_persons_activity",+ "delete_event_properties_activity","delete_batch_exports_activity","delete_data_modeling_schedules_activity","delete_team_records_activity",diff --git a/products/event_definitions/backend/logic/event_property_purge.py b/products/event_definitions/backend/logic/event_property_purge.pynew file mode 100644index 000000000000..60040ec9cddb--- /dev/null+++ b/products/event_definitions/backend/logic/event_property_purge.py@@ -0,0 +1,42 @@+"""Batched deletion of a team's event properties."""++import time+from collections.abc import Callable++from django.db import connections, router, transaction++from products.event_definitions.backend.models.event_property import EventProperty+++def delete_event_properties_for_team(+ team_id: int, should_stop: Callable[[], bool] | None = None, batch_size: int = 10000+) -> bool:+ """Delete the team's event properties in batches. Return False when ``should_stop`` ended the purge first.++ Each batch resumes the (team_id, property) index walk after the last (property, id) it deleted, so no batch+ reads the index entries of rows that earlier batches deleted. ``should_stop`` is checked before each batch.+ """+ table = EventProperty._meta.db_table+ alias = router.db_for_write(EventProperty)+ # The table name comes from the model, never from input, so interpolating it is safe.+ select_batch = (+ f'SELECT id, property, ctid::text FROM "{table}" WHERE team_id = %s AND (property, id) > (%s, %s) '+ "ORDER BY property, id LIMIT %s"+ )+ # The ctid finds each row without a primary key lookup. The id and team_id checks skip a row that an update+ # moved after the select, and the Team cascade deletes such a row later.+ delete_batch = f'DELETE FROM "{table}" WHERE ctid = ANY(%s::tid[]) AND id = ANY(%s) AND team_id = %s'++ last_property, last_id = "", 0+ while True:+ if should_stop is not None and should_stop():+ return False+ with transaction.atomic(using=alias), connections[alias].cursor() as cursor:+ cursor.execute(select_batch, [team_id, last_property, last_id, batch_size])+ rows = cursor.fetchall()+ if rows:+ cursor.execute(delete_batch, [[row[2] for row in rows], [row[0] for row in rows], team_id])+ if len(rows) < batch_size:+ return True+ last_id, last_property = rows[-1][0], rows[-1][1]+ time.sleep(0.1)diff --git a/tach.toml b/tach.tomlindex 39de0b5a51c4..2a7cb8c245f7 100644--- a/tach.toml+++ b/tach.toml@@ -1456,6 +1456,7 @@ layer = "modules"[[interfaces]]expose = [+ "backend\\.logic\\.event_property_purge.*","backend\\.logic\\.placeholder.*","backend\\.models.*","backend\\.property_type.*",