: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): stop a team purge between batches once its deletion is cancelled (#112112)
Eli Reisman6770f7d4eb59
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 0d905870a713..9d2b343c3aba 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -1,4 +1,5 @@import time+from collections.abc import Callablefrom datetime import timedeltafrom typing import Any@@ -40,6 +41,11 @@ TEAM_DELETE_RPC_TIMEOUT_SECONDS = 30 * 60# Out of Django state since replay/0002, so the Team cascade cannot reach it. Delete with the table.RETIRED_SESSION_SUMMARY_TABLES = ("ee_single_session_summary",)++class TeamPurgeStopped(Exception):+ """A team purge stopped between batches because its caller asked it to, so the purge is incomplete."""++actions_that_require_current_team = ["rotate_secret_token","rotate_heatmaps_screenshot_secret",@@ -183,38 +189,43 @@ def _delete_cohort_members_for_all_teams(team_ids: list[int]) -> None:_delete_cohort_members_for_teams(team_ids, cohort_ids)-def _delete_persons_for_teams(team_ids: list[int]) -> None:+def _delete_persons_for_teams(team_ids: list[int], should_stop: Callable[[], bool] | None = None) -> None:"""Delete Person + PersonDistinctId rows for teams via personhog RPC.- The RPC handles PersonDistinctId deletion automatically.+ The RPC handles PersonDistinctId deletion automatically. ``should_stop`` is checked before each batch."""from functools import partialfrom posthog.personhog_client.client import personhog_callfor team_id in team_ids:- personhog_call(+ finished = personhog_call("delete_persons_for_team",- partial(_delete_persons_for_team_via_personhog, team_id),+ partial(_delete_persons_for_team_via_personhog, team_id, should_stop),)+ if not finished:+ raise TeamPurgeStopped(f"The person purge of team {team_id} stopped before it finished")-def _delete_persons_for_team_via_personhog(team_id: int) -> None:+def _delete_persons_for_team_via_personhog(team_id: int, should_stop: Callable[[], bool] | None = None) -> bool:+ """Return False when ``should_stop`` stopped the loop before every person was deleted."""from posthog.personhog_client.client import require_personhog_clientfrom posthog.personhog_client.proto import DeletePersonsBatchForTeamRequestclient = require_personhog_client()while True:+ if should_stop is not None and should_stop():+ return Falseresp = client.delete_persons_batch_for_team(DeletePersonsBatchForTeamRequest(team_id=team_id, batch_size=TEAM_DELETE_BATCH_SIZE),timeout=TEAM_DELETE_RPC_TIMEOUT_SECONDS,)if resp.deleted_count == 0:- break+ return True-def _delete_groups_for_teams(team_ids: list[int]) -> None:+def _delete_groups_for_teams(team_ids: list[int], should_stop: Callable[[], bool] | None = None) -> None:from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import DeleteGroupsBatchForTeamRequest@@ -222,19 +233,22 @@ def _delete_groups_for_teams(team_ids: list[int]) -> None:for team_id in team_ids:- def _fn(tid: int = team_id) -> None:+ def _fn(tid: int = team_id) -> bool:while True:+ if should_stop is not None and should_stop():+ return Falseresp = client.delete_groups_batch_for_team(DeleteGroupsBatchForTeamRequest(team_id=tid, batch_size=10000),timeout=TEAM_DELETE_RPC_TIMEOUT_SECONDS,)if resp.deleted_count == 0:- break+ return True- personhog_call("delete_groups_for_team", _fn)+ if not personhog_call("delete_groups_for_team", _fn):+ raise TeamPurgeStopped(f"The group purge of team {team_id} stopped before it finished")-def _delete_group_type_mappings_for_teams(team_ids: list[int]) -> None:+def _delete_group_type_mappings_for_teams(team_ids: list[int], should_stop: Callable[[], bool] | None = None) -> None:from posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.proto import DeleteGroupTypeMappingsBatchForTeamRequest@@ -242,16 +256,19 @@ def _delete_group_type_mappings_for_teams(team_ids: list[int]) -> None:for team_id in team_ids:- def _fn(tid: int = team_id) -> None:+ def _fn(tid: int = team_id) -> bool:while True:+ if should_stop is not None and should_stop():+ return Falseresp = client.delete_group_type_mappings_batch_for_team(DeleteGroupTypeMappingsBatchForTeamRequest(team_id=tid, batch_size=10000),timeout=TEAM_DELETE_RPC_TIMEOUT_SECONDS,)if resp.deleted_count == 0:- break+ return True- personhog_call("delete_group_type_mappings_for_team", _fn)+ if not personhog_call("delete_group_type_mappings_for_team", _fn):+ raise TeamPurgeStopped(f"The group type mapping purge of team {team_id} stopped before it finished")def _delete_cohort_members_for_teams(team_ids: list[int], cohort_ids: list[int]) -> None:diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pyindex 1762ff779376..a49379ae1e0c 100644--- a/posthog/temporal/delete_teams/activities.py+++ b/posthog/temporal/delete_teams/activities.py@@ -50,8 +50,13 @@ async def delete_groups_activity(inputs: TeamDataActivityInputs) -> None:async with Heartbeater():from posthog.models.team.util import _delete_group_type_mappings_for_teams, _delete_groups_for_teams- await database_sync_to_async_pool(_delete_groups_for_teams)(inputs.team_ids)- await database_sync_to_async_pool(_delete_group_type_mappings_for_teams)(inputs.team_ids)+ # A cancel does not stop the worker thread, so the purge checks for it between batches.+ await database_sync_to_async_pool(_delete_groups_for_teams)(+ inputs.team_ids, should_stop=temporalio.activity.is_cancelled+ )+ await database_sync_to_async_pool(_delete_group_type_mappings_for_teams)(+ inputs.team_ids, should_stop=temporalio.activity.is_cancelled+ )@temporalio.activity.defn@@ -59,7 +64,10 @@ async def delete_team_persons_activity(inputs: TeamDataActivityInputs) -> None:async with Heartbeater():from posthog.models.team.util import _delete_persons_for_teams- await database_sync_to_async_pool(_delete_persons_for_teams)(inputs.team_ids)+ # A cancel does not stop the worker thread, so the purge checks for it between batches.+ await database_sync_to_async_pool(_delete_persons_for_teams)(+ inputs.team_ids, should_stop=temporalio.activity.is_cancelled+ )@temporalio.activity.defndiff --git a/posthog/temporal/tests/delete_teams/test_purge_stop_on_cancel.py b/posthog/temporal/tests/delete_teams/test_purge_stop_on_cancel.pynew file mode 100644index 000000000000..07c620d8e71e--- /dev/null+++ b/posthog/temporal/tests/delete_teams/test_purge_stop_on_cancel.py@@ -0,0 +1,77 @@+import asyncio+import threading+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from temporalio.testing import ActivityEnvironment++from posthog.models.team import util as team_util+from posthog.temporal.delete_teams.activities import delete_groups_activity, delete_team_persons_activity+from posthog.temporal.delete_teams.types import TeamDataActivityInputs++pytestmark = pytest.mark.asyncio++WAIT_SECONDS = 10+++ "activity_fn,rpc,purge,finished_rpcs",+ [+ (delete_team_persons_activity, "delete_persons_batch_for_team", "_delete_persons_for_teams", []),+ (delete_groups_activity, "delete_groups_batch_for_team", "_delete_groups_for_teams", []),+ (+ delete_groups_activity,+ "delete_group_type_mappings_batch_for_team",+ "_delete_group_type_mappings_for_teams",+ ["delete_groups_batch_for_team"],+ ),+ ],+)+async def test_a_cancelled_purge_sends_no_batch_after_the_cancel(+ activity_fn: Any, rpc: str, purge: str, finished_rpcs: list[str]+) -> None:+ first_batch_sent = threading.Event()+ cancel_delivered = threading.Event()+ purge_ended = threading.Event()+ outcome: list[BaseException | None] = []++ def send_batch(request: Any, timeout: float | None = None) -> MagicMock:+ if first_batch_sent.is_set():+ return MagicMock(deleted_count=0)+ first_batch_sent.set()+ assert cancel_delivered.wait(WAIT_SECONDS)+ return MagicMock(deleted_count=1)++ client = MagicMock()+ for finished in finished_rpcs:+ getattr(client, finished).return_value = MagicMock(deleted_count=0)+ getattr(client, rpc).side_effect = send_batch+ real_purge = getattr(team_util, purge)++ def recording_purge(*args: Any, **kwargs: Any) -> None:+ try:+ real_purge(*args, **kwargs)+ outcome.append(None)+ except BaseException as exc:+ outcome.append(exc)+ raise+ finally:+ purge_ended.set()++ env = ActivityEnvironment()+ with (+ patch("posthog.personhog_client.client.get_personhog_client", return_value=client),+ patch.object(team_util, purge, recording_purge),+ ):+ run = asyncio.create_task(env.run(activity_fn, TeamDataActivityInputs(team_ids=[1], user_id=7)))+ assert await asyncio.to_thread(first_batch_sent.wait, WAIT_SECONDS)+ env.cancel()+ cancel_delivered.set()+ with pytest.raises(asyncio.CancelledError):+ await run+ assert await asyncio.to_thread(purge_ended.wait, WAIT_SECONDS)++ assert getattr(client, rpc).call_count == 1+ assert len(outcome) == 1 and isinstance(outcome[0], team_util.TeamPurgeStopped)